UNPKG

lerna

Version:

Lerna is a fast, modern build system for managing and publishing multiple JavaScript/TypeScript packages from the same repository

6,778 lines 247 kB
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// libs/core/src/lib/add-dependencies.ts
var init_add_dependencies = __esm({
  "libs/core/src/lib/add-dependencies.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/add-dependents.ts
var import_lodash;
var init_add_dependents = __esm({
  "libs/core/src/lib/add-dependents.ts"() {
    "use strict";
    import_lodash = require("lodash");
  }
});

// libs/child-process/src/set-exit-code.ts
function setExitCode(code) {
  process.exitCode = code;
}
var init_set_exit_code = __esm({
  "libs/child-process/src/set-exit-code.ts"() {
    "use strict";
  }
});

// libs/child-process/src/index.ts
var src_exports = {};
__export(src_exports, {
  exec: () => exec,
  execSync: () => execSync,
  getChildProcessCount: () => getChildProcessCount,
  getExitCode: () => getExitCode,
  spawn: () => spawn,
  spawnStreaming: () => spawnStreaming
});
function exec(command, args, opts) {
  const options = Object.assign({ stdio: "pipe" }, opts);
  const spawned = spawnProcess(command, args, options);
  return wrapError(spawned);
}
function execSync(command, args, opts) {
  return import_execa.default.sync(command, args, opts).stdout;
}
function spawn(command, args, opts) {
  const options = Object.assign({}, opts, { stdio: "inherit" });
  const spawned = spawnProcess(command, args, options);
  return wrapError(spawned);
}
function spawnStreaming(command, args, opts, prefix) {
  const options = Object.assign({}, opts);
  options.stdio = ["ignore", "pipe", "pipe"];
  const spawned = spawnProcess(command, args, options);
  const stdoutOpts = {};
  const stderrOpts = {};
  if (prefix) {
    const colorName = colorWheel[currentColor % NUM_COLORS];
    const color = colorName;
    currentColor += 1;
    stdoutOpts.tag = `${color.bold(prefix)}:`;
    stderrOpts.tag = `${color(prefix)}:`;
  }
  if (children.size > process.stdout.listenerCount("close")) {
    process.stdout.setMaxListeners(children.size);
    process.stderr.setMaxListeners(children.size);
  }
  spawned.stdout?.pipe((0, import_strong_log_transformer.default)(stdoutOpts)).pipe(process.stdout);
  spawned.stderr?.pipe((0, import_strong_log_transformer.default)(stderrOpts)).pipe(process.stderr);
  return wrapError(spawned);
}
function getChildProcessCount() {
  return children.size;
}
function getExitCode(result) {
  if (result.exitCode) {
    return result.exitCode;
  }
  if (typeof result.code === "number") {
    return result.code;
  }
  if (typeof result.code === "string") {
    return import_os.default.constants.errno[result.code];
  }
  return process.exitCode;
}
function spawnProcess(command, args, opts) {
  const child = (0, import_execa.default)(command, args, opts);
  const drain = (exitCode, signal) => {
    children.delete(child);
    if (signal === void 0) {
      child.removeListener("exit", drain);
    }
    if (exitCode) {
      setExitCode(exitCode);
    }
  };
  child.once("exit", drain);
  child.once("error", drain);
  if (opts?.pkg) {
    child.pkg = opts.pkg;
  }
  children.add(child);
  return child;
}
function wrapError(spawned) {
  if (spawned.pkg) {
    return spawned.catch((err) => {
      err.exitCode = getExitCode(err);
      err.pkg = spawned.pkg;
      throw err;
    });
  }
  return spawned;
}
var import_os, import_chalk, import_execa, import_strong_log_transformer, children, colorWheel, NUM_COLORS, currentColor;
var init_src = __esm({
  "libs/child-process/src/index.ts"() {
    "use strict";
    import_os = __toESM(require("os"));
    import_chalk = __toESM(require("chalk"));
    import_execa = __toESM(require("execa"));
    import_strong_log_transformer = __toESM(require("strong-log-transformer"));
    init_set_exit_code();
    children = /* @__PURE__ */ new Set();
    colorWheel = [import_chalk.default.cyan, import_chalk.default.magenta, import_chalk.default.blue, import_chalk.default.yellow, import_chalk.default.green, import_chalk.default.blueBright];
    NUM_COLORS = colorWheel.length;
    currentColor = 0;
  }
});

// libs/core/src/lib/collect-uncommitted.ts
function collectUncommitted({ cwd, log: log48 = import_npmlog.default }) {
  log48.silly("collect-uncommitted", "git status --porcelain (async)");
  return childProcess.exec("git", ["status", "--porcelain"], { cwd }).then(({ stdout }) => transformOutput(stdout));
}
var import_chalk2, import_npmlog, childProcess, maybeColorize, cRed, cGreen, replaceStatus, colorizeStats, splitOnNewLine, filterEmpty, o, transformOutput;
var init_collect_uncommitted = __esm({
  "libs/core/src/lib/collect-uncommitted.ts"() {
    "use strict";
    import_chalk2 = __toESM(require("chalk"));
    import_npmlog = __toESM(require("npmlog"));
    childProcess = (init_src(), __toCommonJS(src_exports));
    maybeColorize = (colorize) => (s) => s !== " " ? colorize(s) : s;
    cRed = maybeColorize(import_chalk2.default.red);
    cGreen = maybeColorize(import_chalk2.default.green);
    replaceStatus = (_, maybeGreen, maybeRed) => `${cGreen(maybeGreen)}${cRed(maybeRed)}`;
    colorizeStats = (stats) => stats.replace(/^([^U]| )([A-Z]| )/gm, replaceStatus).replace(/^\?{2}|U{2}/gm, cRed("$&"));
    splitOnNewLine = (str) => str.split("\n");
    filterEmpty = (lines) => lines.filter((line) => line.length);
    o = (l, r) => (x) => l(r(x));
    transformOutput = o(filterEmpty, o(splitOnNewLine, colorizeStats));
  }
});

// libs/core/src/lib/describe-ref.ts
function getArgs(options, includeMergedTags = false) {
  let args = [
    "describe",
    // fallback to short sha if no tags located
    "--always",
    // always return full result, helps identify existing release
    "--long",
    // annotate if uncommitted changes present
    "--dirty",
    // prefer tags originating on upstream branch
    "--first-parent"
  ];
  if (options.match) {
    args.push("--match", options.match);
  }
  if (includeMergedTags) {
    args = args.filter((arg) => arg !== "--first-parent");
  }
  return args;
}
function describeRef(options = {}, includeMergedTags) {
  const promise = childProcess2.exec("git", getArgs(options, includeMergedTags), options);
  return promise.then(({ stdout }) => {
    const result = parse(stdout, options.cwd);
    import_npmlog2.default.verbose("git-describe", "%j => %j", options && options.match, stdout);
    import_npmlog2.default.silly("git-describe", "parsed => %j", result);
    return result;
  });
}
function describeRefSync(options = {}, includeMergedTags) {
  const stdout = childProcess2.execSync("git", getArgs(options, includeMergedTags), options);
  const result = parse(stdout, options.cwd);
  import_npmlog2.default.silly("git-describe.sync", "%j => %j", stdout, result);
  return result;
}
function parse(stdout, cwd) {
  const minimalShaRegex = /^([0-9a-f]{7,40})(-dirty)?$/;
  if (minimalShaRegex.test(stdout)) {
    const [, sha2, isDirty2] = minimalShaRegex.exec(stdout);
    const refCount2 = childProcess2.execSync("git", ["rev-list", "--count", sha2], { cwd });
    return { refCount: refCount2, sha: sha2, isDirty: Boolean(isDirty2) };
  }
  const [, lastTagName, lastVersion, refCount, sha, isDirty] = /^((?:.*@)?(.*))-(\d+)-g([0-9a-f]+)(-dirty)?$/.exec(stdout) || [];
  return { lastTagName, lastVersion, refCount, sha, isDirty: Boolean(isDirty) };
}
var import_npmlog2, childProcess2;
var init_describe_ref = __esm({
  "libs/core/src/lib/describe-ref.ts"() {
    "use strict";
    import_npmlog2 = __toESM(require("npmlog"));
    childProcess2 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/validation-error.ts
var import_npmlog3, ValidationError;
var init_validation_error = __esm({
  "libs/core/src/lib/validation-error.ts"() {
    "use strict";
    import_npmlog3 = __toESM(require("npmlog"));
    ValidationError = class extends Error {
      constructor(prefix, message, ...rest) {
        super(message);
        this.name = "ValidationError";
        this.prefix = prefix;
        import_npmlog3.default.resume();
        import_npmlog3.default.error(prefix, message, ...rest);
      }
    };
  }
});

// libs/core/src/lib/check-working-tree.ts
function checkWorkingTree({ cwd } = {}) {
  let chain = Promise.resolve();
  chain = chain.then(() => describeRef({ cwd }));
  const tests = [
    // prevent duplicate versioning
    chain.then(throwIfReleased),
    // prevent publish of uncommitted changes
    chain.then(mkThrowIfUncommitted({ cwd }))
  ];
  return chain.then((result) => Promise.all(tests).then(() => result));
}
function throwIfReleased({ refCount }) {
  if (refCount === "0") {
    throw new ValidationError(
      "ERELEASED",
      "The current commit has already been released. Please make new commits before continuing."
    );
  }
}
function mkThrowIfUncommitted(options = {}) {
  return function throwIfUncommitted2(opts) {
    if (opts.isDirty) {
      return collectUncommitted(options).then((uncommitted) => {
        throw new ValidationError("EUNCOMMIT", `${EUNCOMMIT_MSG}${uncommitted.join("\n")}`);
      });
    }
  };
}
var EUNCOMMIT_MSG, throwIfUncommitted;
var init_check_working_tree = __esm({
  "libs/core/src/lib/check-working-tree.ts"() {
    "use strict";
    init_collect_uncommitted();
    init_describe_ref();
    init_validation_error();
    EUNCOMMIT_MSG = "Working tree has uncommitted changes, please commit or remove the following changes before continuing:\n";
    throwIfUncommitted = mkThrowIfUncommitted();
  }
});

// libs/core/src/lib/cli.ts
var import_dedent, import_npmlog4, import_yargs;
var init_cli = __esm({
  "libs/core/src/lib/cli.ts"() {
    "use strict";
    import_dedent = __toESM(require("dedent"));
    import_npmlog4 = __toESM(require("npmlog"));
    import_yargs = __toESM(require("yargs"));
  }
});

// libs/core/src/lib/get-packages-for-option.ts
function getPackagesForOption(option) {
  let inputs = null;
  if (option === true) {
    inputs = ["*"];
  } else if (typeof option === "string") {
    inputs = option.split(",");
  } else if (Array.isArray(option)) {
    inputs = [...option];
  }
  return new Set(inputs);
}
var init_get_packages_for_option = __esm({
  "libs/core/src/lib/get-packages-for-option.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/prerelease-id-from-version.ts
function prereleaseIdFromVersion(version) {
  return (import_semver.default.prerelease(version) || []).shift();
}
var import_semver;
var init_prerelease_id_from_version = __esm({
  "libs/core/src/lib/prerelease-id-from-version.ts"() {
    "use strict";
    import_semver = __toESM(require("semver"));
  }
});

// libs/core/src/lib/project-graph-with-packages.ts
function getPackage(project) {
  if (!project.package) {
    throw new Error(`Failed attempting to find package for project ${project.name}`);
  }
  return project.package;
}
var isExternalNpmDependency;
var init_project_graph_with_packages = __esm({
  "libs/core/src/lib/project-graph-with-packages.ts"() {
    "use strict";
    isExternalNpmDependency = (dep) => dep.startsWith("npm:");
  }
});

// libs/core/src/lib/collect-updates/has-tags.ts
function hasTags(opts) {
  import_npmlog5.default.silly("hasTags");
  let result = false;
  try {
    result = !!childProcess3.execSync("git", ["tag"], opts);
  } catch (err) {
    import_npmlog5.default.warn("ENOTAGS", "No git tags were reachable from this branch!");
    import_npmlog5.default.verbose("hasTags error", err);
  }
  import_npmlog5.default.verbose("hasTags", result);
  return result;
}
var import_npmlog5, childProcess3;
var init_has_tags = __esm({
  "libs/core/src/lib/collect-updates/has-tags.ts"() {
    "use strict";
    import_npmlog5 = __toESM(require("npmlog"));
    childProcess3 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/collect-updates/make-diff-predicate.ts
function makeDiffPredicate(committish, execOpts, ignorePatterns = []) {
  const ignoreFilters = new Set(
    ignorePatterns.map(
      (p) => import_minimatch.default.filter(`!${p}`, {
        matchBase: true,
        // dotfiles inside ignored directories should also match
        dot: true
      })
    )
  );
  if (ignoreFilters.size) {
    import_npmlog6.default.info("ignoring diff in paths matching", ignorePatterns);
  }
  return function hasDiffSinceThatIsntIgnored(node) {
    const diff = diffSinceIn(committish, getPackage(node).location, execOpts);
    if (diff === "") {
      import_npmlog6.default.silly("", "no diff found in %s", node.name);
      return false;
    }
    import_npmlog6.default.silly("found diff in", diff);
    let changedFiles = diff.split("\n");
    if (ignoreFilters.size) {
      for (const ignored of ignoreFilters) {
        changedFiles = changedFiles.filter(ignored);
      }
    }
    if (changedFiles.length) {
      import_npmlog6.default.verbose("filtered diff", changedFiles);
    } else {
      import_npmlog6.default.verbose("", "no diff found in %s (after filtering)", node.name);
    }
    return changedFiles.length > 0;
  };
}
function diffSinceIn(committish, location, opts) {
  const args = ["diff", "--name-only", committish];
  const formattedLocation = (0, import_slash.default)((0, import_path.relative)(opts.cwd, location));
  if (formattedLocation) {
    args.push("--", formattedLocation);
  }
  import_npmlog6.default.silly("checking diff", formattedLocation);
  return execSync2("git", args, opts);
}
var import_minimatch, import_npmlog6, import_path, import_slash, execSync2;
var init_make_diff_predicate = __esm({
  "libs/core/src/lib/collect-updates/make-diff-predicate.ts"() {
    "use strict";
    import_minimatch = __toESM(require("minimatch"));
    import_npmlog6 = __toESM(require("npmlog"));
    import_path = require("path");
    import_slash = __toESM(require("slash"));
    init_project_graph_with_packages();
    ({ execSync: execSync2 } = (init_src(), __toCommonJS(src_exports)));
  }
});

// libs/core/src/lib/collect-updates/collect-project-updates.ts
function collectProjectUpdates(filteredProjects, projectGraph, execOpts, commandOptions) {
  const {
    forcePublish,
    conventionalCommits,
    forceConventionalGraduate,
    conventionalGraduate,
    excludeDependents
  } = commandOptions;
  const useConventionalGraduate = conventionalCommits && (conventionalGraduate || forceConventionalGraduate);
  const forced = getPackagesForOption(useConventionalGraduate ? conventionalGraduate : forcePublish);
  let committish = commandOptions.since ?? "";
  if (hasTags(execOpts)) {
    const { sha, refCount, lastTagName } = describeRefSync(execOpts, commandOptions.includeMergedTags);
    if (refCount === "0" && forced.size === 0 && !committish) {
      import_npmlog7.default.notice("", "Current HEAD is already released, skipping change detection.");
      return [];
    }
    if (commandOptions.canary) {
      committish = `${sha}^..${sha}`;
    } else if (!committish) {
      committish = lastTagName;
    }
  }
  if (forced.size) {
    import_npmlog7.default.warn(
      useConventionalGraduate ? "conventional-graduate" : "force-publish",
      forced.has("*") ? "all packages" : Array.from(forced.values()).join("\n")
    );
  }
  if (useConventionalGraduate) {
    if (forced.has("*")) {
      import_npmlog7.default.info("", "Graduating all prereleased packages");
    } else {
      import_npmlog7.default.info("", "Graduating prereleased packages");
    }
  } else if (!committish || forced.has("*")) {
    import_npmlog7.default.info("", "Assuming all packages changed");
    return collectProjects(filteredProjects, projectGraph, {
      onInclude: (name) => import_npmlog7.default.verbose("updated", name),
      excludeDependents
    });
  }
  import_npmlog7.default.info("", `Looking for changed packages since ${committish}`);
  const hasDiff = makeDiffPredicate(committish, execOpts, commandOptions.ignoreChanges);
  const needsBump = !commandOptions.bump || commandOptions.bump.startsWith("pre") ? () => false : (
    /* skip packages that have not been previously prereleased */
    (node) => !!prereleaseIdFromVersion(getPackage(node).version)
  );
  const isForced = (node, name) => !!((forced.has("*") || forced.has(name)) && ((useConventionalGraduate ? prereleaseIdFromVersion(getPackage(node).version) : true) || forceConventionalGraduate));
  return collectProjects(filteredProjects, projectGraph, {
    isCandidate: (node, name) => isForced(node, name) || needsBump(node) || hasDiff(node),
    onInclude: (name) => import_npmlog7.default.verbose("updated", name),
    excludeDependents
  });
}
function collectProjects(projects, projectGraph, { isCandidate = () => true, onInclude, excludeDependents } = {}) {
  const candidates = {};
  projects.forEach((node) => {
    if (isCandidate(node, getPackage(node).name)) {
      candidates[node.name] = node;
    }
  });
  if (!excludeDependents) {
    collectDependents(candidates, projectGraph).forEach((node) => candidates[node.name] = node);
  }
  const updates = [];
  projects.forEach((node) => {
    if (candidates[node.name]) {
      if (onInclude) {
        onInclude(getPackage(node).name);
      }
      updates.push(node);
    }
  });
  return updates;
}
function collectDependents(nodes, projectGraph) {
  const dependents = (0, import_lodash2.flatten)(
    Object.values(projectGraph.localPackageDependencies)
  ).reduce(
    (prev, next) => ({
      ...prev,
      [next.target]: [...prev[next.target] || [], next.source]
    }),
    {}
  );
  const collected = /* @__PURE__ */ new Set();
  Object.values(nodes).forEach((currentNode) => {
    if (dependents[currentNode.name] && dependents[currentNode.name].length === 0) {
      return;
    }
    const queue2 = [currentNode];
    const seen = /* @__PURE__ */ new Set();
    while (queue2.length) {
      const node = queue2.shift();
      dependents[node.name]?.forEach((dep) => {
        if (seen.has(dep)) {
          return;
        }
        seen.add(dep);
        if (dep === currentNode.name || nodes[dep]) {
          return;
        }
        const dependentNode = projectGraph.nodes[dep];
        collected.add(dependentNode);
        queue2.push(dependentNode);
      });
    }
  });
  return collected;
}
var import_lodash2, import_npmlog7;
var init_collect_project_updates = __esm({
  "libs/core/src/lib/collect-updates/collect-project-updates.ts"() {
    "use strict";
    import_lodash2 = require("lodash");
    import_npmlog7 = __toESM(require("npmlog"));
    init_describe_ref();
    init_get_packages_for_option();
    init_prerelease_id_from_version();
    init_project_graph_with_packages();
    init_has_tags();
    init_make_diff_predicate();
  }
});

// libs/core/src/lib/collect-updates/index.ts
var init_collect_updates = __esm({
  "libs/core/src/lib/collect-updates/index.ts"() {
    "use strict";
    init_collect_project_updates();
  }
});

// libs/core/src/lib/package.ts
function binSafeName({ name, scope }) {
  return scope ? name.substring(scope.length + 1) : name;
}
function shallowCopy(json) {
  return Object.keys(json).reduce((obj, key) => {
    const val = json[key];
    if (Array.isArray(val)) {
      obj[key] = val.slice();
    } else if (val && typeof val === "object") {
      obj[key] = Object.assign({}, val);
    } else {
      obj[key] = val;
    }
    return obj;
  }, {});
}
var import_devkit, import_fs, import_load_json_file, import_npm_package_arg, import_path2, import_write_pkg, PKG, _location, _resolved, _rootPath, _scripts, _contents, Package;
var init_package = __esm({
  "libs/core/src/lib/package.ts"() {
    "use strict";
    import_devkit = require("@nx/devkit");
    import_fs = __toESM(require("fs"));
    import_load_json_file = __toESM(require("load-json-file"));
    import_npm_package_arg = __toESM(require("npm-package-arg"));
    import_path2 = __toESM(require("path"));
    import_write_pkg = __toESM(require("write-pkg"));
    PKG = Symbol("pkg");
    _location = Symbol("location");
    _resolved = Symbol("resolved");
    _rootPath = Symbol("rootPath");
    _scripts = Symbol("scripts");
    _contents = Symbol("contents");
    Package = class _Package {
      static {
        PKG, _location, _resolved, _rootPath, _scripts, _contents;
      }
      /**
       * Create a Package instance from parameters, possibly reusing existing instance.
       * @param ref A path to a package.json file, Package instance, or JSON object
       * @param [dir] If `ref` is a JSON object, this is the location of the manifest
       */
      static lazy(ref, dir = ".") {
        if (typeof ref === "string") {
          const location = import_path2.default.resolve(import_path2.default.basename(ref) === "package.json" ? import_path2.default.dirname(ref) : ref);
          const manifest = import_load_json_file.default.sync(import_path2.default.join(location, "package.json"));
          return new _Package(manifest, location);
        }
        if ("__isLernaPackage" in ref) {
          return ref;
        }
        return new _Package(ref, dir);
      }
      constructor(pkg, location, rootPath = location) {
        const resolved = import_npm_package_arg.default.resolve(pkg.name, `file:${import_path2.default.relative(rootPath, location)}`, rootPath);
        this.name = pkg.name;
        this[PKG] = pkg;
        Object.defineProperty(this, PKG, { enumerable: false, writable: true });
        this[_location] = location;
        this[_resolved] = resolved;
        this[_rootPath] = rootPath;
        this[_scripts] = { ...pkg.scripts };
      }
      // readonly getters
      get location() {
        return this[_location];
      }
      get private() {
        return Boolean(this[PKG].private);
      }
      set private(isPrivate) {
        this[PKG].private = isPrivate;
      }
      get resolved() {
        return this[_resolved];
      }
      get rootPath() {
        return this[_rootPath];
      }
      get scripts() {
        return this[_scripts];
      }
      get lernaConfig() {
        return this[PKG].lerna;
      }
      set lernaConfig(config) {
        this[PKG].lerna = config;
      }
      get bin() {
        const pkg = this[PKG];
        return typeof pkg.bin === "string" ? {
          // See note on function implementation
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          [binSafeName(this.resolved)]: pkg.bin
        } : Object.assign({}, pkg.bin);
      }
      get binLocation() {
        return import_path2.default.join(this.location, "node_modules", ".bin");
      }
      get manifestLocation() {
        return import_path2.default.join(this.location, "package.json");
      }
      get nodeModulesLocation() {
        return import_path2.default.join(this.location, "node_modules");
      }
      // eslint-disable-next-line class-methods-use-this
      get __isLernaPackage() {
        return true;
      }
      // accessors
      get version() {
        return this[PKG].version;
      }
      set version(version) {
        this[PKG].version = version;
      }
      get contents() {
        if (this[_contents]) {
          return this[_contents];
        }
        if (this[PKG].publishConfig && this[PKG].publishConfig.directory) {
          return import_path2.default.join(this.location, this[PKG].publishConfig.directory);
        }
        return this.location;
      }
      set contents(subDirectory) {
        const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || import_devkit.workspaceRoot;
        if (subDirectory.startsWith(_workspaceRoot)) {
          this[_contents] = subDirectory;
          return;
        }
        this[_contents] = import_path2.default.join(this.location, subDirectory);
      }
      // "live" collections
      get dependencies() {
        return this[PKG].dependencies;
      }
      get devDependencies() {
        return this[PKG].devDependencies;
      }
      get optionalDependencies() {
        return this[PKG].optionalDependencies;
      }
      get peerDependencies() {
        return this[PKG].peerDependencies;
      }
      /**
       * Map-like retrieval of arbitrary values
       */
      get(key) {
        return this[PKG][key];
      }
      /**
       * Map-like storage of arbitrary values
       */
      set(key, val) {
        this[PKG][key] = val;
        return this;
      }
      /**
       * Provide shallow copy for munging elsewhere
       */
      toJSON() {
        return shallowCopy(this[PKG]);
      }
      /**
       * Refresh internal state from disk (e.g., changed by external lifecycles)
       */
      refresh() {
        return (0, import_load_json_file.default)(this.manifestLocation).then((pkg) => {
          this[PKG] = pkg;
          return this;
        });
      }
      /**
       * Write manifest changes to disk
       * @returns {Promise} resolves when write finished
       */
      serialize() {
        return (0, import_write_pkg.default)(this.manifestLocation, this[PKG]).then(() => this);
      }
      /**
       * Sync dist manifest version
       */
      async syncDistVersion(doSync) {
        if (doSync) {
          const distPkg = import_path2.default.join(this.contents, "package.json");
          if (distPkg !== this.manifestLocation && import_fs.default.existsSync(distPkg)) {
            const pkg = await (0, import_load_json_file.default)(distPkg);
            pkg.version = this[PKG].version;
            await (0, import_write_pkg.default)(distPkg, pkg);
          }
        }
        return this;
      }
      getLocalDependency(depName) {
        if (this.dependencies && this.dependencies[depName]) {
          return {
            collection: "dependencies",
            spec: this.dependencies[depName]
          };
        }
        if (this.devDependencies && this.devDependencies[depName]) {
          return {
            collection: "devDependencies",
            spec: this.devDependencies[depName]
          };
        }
        if (this.optionalDependencies && this.optionalDependencies[depName]) {
          return {
            collection: "optionalDependencies",
            spec: this.optionalDependencies[depName]
          };
        }
        return null;
      }
      /**
       * Mutate local dependency spec according to type
       * @param resolved npa metadata
       * @param depVersion semver
       * @param savePrefix npm_config_save_prefix
       */
      updateLocalDependency(resolved, depVersion, savePrefix, options = { retainWorkspacePrefix: true }) {
        const depName = resolved.name;
        let depCollection = this.dependencies;
        if (!depCollection || !depCollection[depName]) {
          depCollection = this.optionalDependencies;
        }
        if (!depCollection || !depCollection[depName]) {
          depCollection = this.devDependencies;
        }
        if (resolved.workspaceSpec && options.retainWorkspacePrefix) {
          if (!resolved.workspaceAlias) {
            const workspacePrefix = resolved.workspaceSpec.match(/^(workspace:[*~^]?)/)[0];
            depCollection[depName] = `${workspacePrefix}${depVersion}`;
          }
        } else if (resolved.registry || resolved.type === "directory") {
          depCollection[depName] = `${savePrefix}${depVersion}`;
        } else if (resolved.gitCommittish) {
          const [tagPrefix] = /^\D*/.exec(resolved.gitCommittish);
          const { hosted } = resolved;
          hosted.committish = `${tagPrefix}${depVersion}`;
          depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
        } else if (resolved.gitRange) {
          const { hosted } = resolved;
          hosted.committish = `semver:${savePrefix}${depVersion}`;
          depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
        }
      }
      /**
       * Remove the private property, effectively making the package public.
       */
      removePrivate() {
        delete this[PKG].private;
      }
    };
  }
});

// libs/core/src/lib/project/shallow-extend.ts
function shallowExtend(json, defaults = {}) {
  return Object.keys(json).reduce((obj, key) => {
    const val = json[key];
    if (Array.isArray(val)) {
      obj[key] = val.slice();
    } else if (val && typeof val === "object") {
      obj[key] = shallowExtend(val, obj[key]);
    } else {
      obj[key] = val;
    }
    return obj;
  }, defaults);
}
var init_shallow_extend = __esm({
  "libs/core/src/lib/project/shallow-extend.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/project/apply-extends.ts
function applyExtends(config, cwd, seen = /* @__PURE__ */ new Set()) {
  let defaultConfig = {};
  if ("extends" in config) {
    let pathToDefault;
    try {
      pathToDefault = (0, import_resolve_from.default)(cwd, config.extends);
    } catch (err) {
      throw new ValidationError("ERESOLVED", "Config .extends must be locally-resolvable", err);
    }
    if (seen.has(pathToDefault)) {
      throw new ValidationError("ECIRCULAR", "Config .extends cannot be circular", seen);
    }
    seen.add(pathToDefault);
    defaultConfig = require(pathToDefault);
    delete config.extends;
    defaultConfig = applyExtends(defaultConfig, import_path3.default.dirname(pathToDefault), seen);
  }
  return shallowExtend(config, defaultConfig);
}
var import_path3, import_resolve_from;
var init_apply_extends = __esm({
  "libs/core/src/lib/project/apply-extends.ts"() {
    "use strict";
    import_path3 = __toESM(require("path"));
    import_resolve_from = __toESM(require("resolve-from"));
    init_validation_error();
    init_shallow_extend();
  }
});

// libs/core/src/lib/project/make-file-finder.ts
function normalize(results) {
  return results.map((fp) => import_path4.default.normalize(fp));
}
function getGlobOpts(rootPath, packageConfigs) {
  const globOpts = {
    cwd: rootPath,
    absolute: true,
    expandDirectories: false,
    followSymbolicLinks: false
  };
  if (packageConfigs.some((cfg) => cfg.indexOf("**") > -1)) {
    if (packageConfigs.some((cfg) => cfg.indexOf("node_modules") > -1)) {
      throw new ValidationError(
        "EPKGCONFIG",
        "An explicit node_modules package path does not allow globstars (**)"
      );
    }
    globOpts.ignore = [
      // allow globs like "packages/**",
      // but avoid picking up node_modules/**/package.json
      "**/node_modules/**"
    ];
  }
  return globOpts;
}
function makeFileFinder(rootPath, packageConfigs) {
  const globOpts = getGlobOpts(rootPath, packageConfigs);
  return (fileName, fileMapper, customGlobOpts) => {
    const options = Object.assign({}, customGlobOpts, globOpts);
    const promise = (0, import_p_map.default)(
      Array.from(packageConfigs).sort(),
      (globPath) => {
        let chain = (0, import_globby.default)(import_path4.default.posix.join(globPath, fileName), options);
        chain = chain.then((results) => results.sort());
        chain = chain.then(normalize);
        if (fileMapper) {
          chain = chain.then(fileMapper);
        }
        return chain;
      },
      { concurrency: 4 }
    );
    return promise.then((results) => results.reduce((acc, result) => acc.concat(result), []));
  };
}
function makeSyncFileFinder(rootPath, packageConfigs) {
  const globOpts = getGlobOpts(rootPath, packageConfigs);
  return (fileName, fileMapper) => {
    const patterns = packageConfigs.map((globPath) => import_path4.default.posix.join(globPath, fileName)).sort();
    let results = import_globby.default.sync(patterns, globOpts);
    results = normalize(results);
    return results.map((res) => fileMapper(res));
  };
}
var import_globby, import_p_map, import_path4;
var init_make_file_finder = __esm({
  "libs/core/src/lib/project/make-file-finder.ts"() {
    "use strict";
    import_globby = __toESM(require("globby"));
    import_p_map = __toESM(require("p-map"));
    import_path4 = __toESM(require("path"));
    init_validation_error();
  }
});

// libs/core/src/lib/project/index.ts
var import_devkit2, import_cosmiconfig, import_dedent2, import_fs2, import_glob_parent, import_globby2, import_js_yaml, import_load_json_file2, import_npmlog8, import_p_map2, import_path5, LICENSE_GLOB, Project, getPackages, getPackagesSync;
var init_project = __esm({
  "libs/core/src/lib/project/index.ts"() {
    "use strict";
    import_devkit2 = require("@nx/devkit");
    import_cosmiconfig = require("cosmiconfig");
    import_dedent2 = __toESM(require("dedent"));
    import_fs2 = __toESM(require("fs"));
    import_glob_parent = __toESM(require("glob-parent"));
    import_globby2 = __toESM(require("globby"));
    import_js_yaml = require("js-yaml");
    import_load_json_file2 = __toESM(require("load-json-file"));
    import_npmlog8 = __toESM(require("npmlog"));
    import_p_map2 = __toESM(require("p-map"));
    import_path5 = __toESM(require("path"));
    init_package();
    init_validation_error();
    init_apply_extends();
    init_make_file_finder();
    LICENSE_GLOB = "LICEN{S,C}E{,.*}";
    Project = class _Project {
      /**
       * @deprecated Only used in legacy core utilities
       * TODO: remove in v8
       */
      static getPackages(cwd) {
        return new _Project(cwd).getPackages();
      }
      /**
       * @deprecated Only used in legacy core utilities
       * TODO: remove in v8
       */
      static getPackagesSync(cwd) {
        return new _Project(cwd).getPackagesSync();
      }
      constructor(cwd, options) {
        const { config, configNotFound, filepath } = this.#resolveLernaConfig(cwd);
        this.config = config;
        this.configNotFound = configNotFound || false;
        this.rootConfigLocation = filepath;
        this.rootPath = import_path5.default.dirname(filepath);
        this.manifest = this.#resolveRootPackageJson();
        if (this.configNotFound) {
          throw new ValidationError("ENOLERNA", "`lerna.json` does not exist, have you run `lerna init`?");
        }
        if (!options?.skipLernaConfigValidations) {
          this.#validateLernaConfig(config);
        }
        this.packageConfigs = this.#resolvePackageConfigs();
        import_npmlog8.default.verbose("rootPath", this.rootPath);
      }
      get version() {
        return this.config.version;
      }
      set version(val) {
        this.config.version = val;
      }
      get packageParentDirs() {
        return this.packageConfigs.map((packagePattern) => (0, import_glob_parent.default)(packagePattern)).map((parentDir) => import_path5.default.resolve(this.rootPath, parentDir));
      }
      get licensePath() {
        let licensePath;
        try {
          const search = import_globby2.default.sync(LICENSE_GLOB, {
            cwd: this.rootPath,
            absolute: true,
            caseSensitiveMatch: false,
            // Project license is always a sibling of the root manifest
            deep: 0
          });
          licensePath = search.shift();
          if (licensePath) {
            licensePath = import_path5.default.normalize(licensePath);
            Object.defineProperty(this, "licensePath", {
              value: licensePath
            });
          }
        } catch (err) {
          throw new ValidationError(err.name, err.message);
        }
        return licensePath;
      }
      get fileFinder() {
        const finder = makeFileFinder(this.rootPath, this.packageConfigs);
        Object.defineProperty(this, "fileFinder", {
          value: finder
        });
        return finder;
      }
      /**
       * A promise resolving to a list of Package instances
       */
      getPackages() {
        const mapper = (packageConfigPath) => (0, import_load_json_file2.default)(packageConfigPath).then(
          (packageJson) => new Package(packageJson, import_path5.default.dirname(packageConfigPath), this.rootPath)
        );
        return this.fileFinder("package.json", (filePaths) => (0, import_p_map2.default)(filePaths, mapper, { concurrency: 50 }));
      }
      /**
       * A list of Package instances
       */
      getPackagesSync() {
        const syncFileFinder = makeSyncFileFinder(this.rootPath, this.packageConfigs);
        return syncFileFinder("package.json", (packageConfigPath) => {
          return new Package(
            import_load_json_file2.default.sync(packageConfigPath),
            import_path5.default.dirname(packageConfigPath),
            this.rootPath
          );
        });
      }
      getPackageLicensePaths() {
        return this.fileFinder(LICENSE_GLOB, null, { caseSensitiveMatch: false });
      }
      isIndependent() {
        return this.version === "independent";
      }
      serializeConfig() {
        (0, import_devkit2.writeJsonFile)(this.rootConfigLocation, this.config, { spaces: 2 });
        return this.rootConfigLocation;
      }
      #resolveRootPackageJson() {
        try {
          const manifestLocation = import_path5.default.join(this.rootPath, "package.json");
          const packageJson = import_load_json_file2.default.sync(manifestLocation);
          if (!packageJson.name) {
            packageJson.name = import_path5.default.basename(import_path5.default.dirname(manifestLocation));
          }
          return new Package(packageJson, this.rootPath);
        } catch (err) {
          if (err instanceof Error && err?.name === "JSONError") {
            throw new ValidationError(err.name, err.message);
          }
          throw new ValidationError("ENOPKG", "`package.json` does not exist, have you run `lerna init`?");
        }
      }
      #resolveLernaConfig(cwd) {
        try {
          const explorer = (0, import_cosmiconfig.cosmiconfigSync)("lerna", {
            loaders: {
              ...import_cosmiconfig.defaultLoaders,
              ".json": (filepath, content) => {
                if (!filepath.endsWith("lerna.json")) {
                  return import_cosmiconfig.defaultLoaders[".json"](filepath, content);
                }
                try {
                  return (0, import_devkit2.parseJson)(content);
                } catch (err) {
                  if (err instanceof Error) {
                    err.name = "JSONError";
                    err.message = `Error in: ${filepath}
${err.message}`;
                  }
                  throw err;
                }
              }
            },
            searchPlaces: ["lerna.json", "package.json"],
            transform(obj) {
              if (!obj) {
                const configNotFoundResult = {
                  // No need to distinguish between missing and empty,
                  // saves a lot of noisy guards elsewhere
                  config: {},
                  configNotFound: true,
                  // path.resolve(".", ...) starts from process.cwd()
                  filepath: import_path5.default.resolve(cwd || ".", "lerna.json")
                };
                return configNotFoundResult;
              }
              obj.config = applyExtends(obj.config, import_path5.default.dirname(obj.filepath));
              return obj;
            }
          });
          return explorer.search(cwd);
        } catch (err) {
          if (err.name === "JSONError") {
            throw new ValidationError(err.name, err.message);
          }
          throw err;
        }
      }
      #validateLernaConfig(config) {
        if (!this.version) {
          throw new ValidationError("ENOVERSION", "Required property version does not exist in `lerna.json`");
        }
        if (config.useWorkspaces !== void 0) {
          throw new ValidationError(
            "ECONFIGWORKSPACES",
            `The "useWorkspaces" option has been removed. By default lerna will resolve your packages using your package manager's workspaces configuration. Alternatively, you can manually provide a list of package globs to be used instead via the "packages" option in lerna.json.`
          );
        }
      }
      #resolvePnpmWorkspaceConfig() {
        let config;
        try {
          const configLocation = import_path5.default.join(this.rootPath, "pnpm-workspace.yaml");
          const configContent = import_fs2.default.readFileSync(configLocation, { encoding: "utf8" });
          config = (0, import_js_yaml.load)(configContent);
        } catch (err) {
          if (err.message.includes("ENOENT: no such file or directory")) {
            throw new ValidationError(
              "ENOENT",
              "No pnpm-workspace.yaml found. See https://pnpm.io/workspaces for help configuring workspaces in pnpm."
            );
          }
          throw new ValidationError(err.name, err.message);
        }
        return config;
      }
      /**
       * By default, the user's package manager workspaces configuration will be used to resolve packages.
       * However, they can optionally specify an explicit set of package globs to be used instead.
       *
       * NOTE: This does not impact the project graph creation process, which will still ultimately use
       * the package manager workspaces configuration to construct a full graph, it will only impact which
       * of the packages in that graph will be considered when running commands.
       */
      #resolvePackageConfigs() {
        if (this.config.packages) {
          import_npmlog8.default.verbose(
            "packageConfigs",
            `Explicit "packages" configuration found in lerna.json. Resolving packages using the configured glob(s): ${JSON.stringify(
              this.config.packages
            )}`
          );
          return this.config.packages;
        }
        if (this.config.npmClient === "pnpm") {
          import_npmlog8.default.verbose(
            "packageConfigs",
            'Package manager "pnpm" detected. Resolving packages using `pnpm-workspace.yaml`.'
          );
          const workspaces2 = this.#resolvePnpmWorkspaceConfig().packages;
          if (!workspaces2) {
            throw new ValidationError(
              "EWORKSPACES",
              'No "packages" property found in `pnpm-workspace.yaml`. See https://pnpm.io/workspaces for help configuring workspaces in pnpm.'
            );
          }
          return workspaces2;
        }
        const workspaces = this.manifest?.get("workspaces");
        const isYarnClassicWorkspacesObjectConfig = Boolean(
          workspaces && typeof workspaces === "object" && Array.isArray(workspaces.packages)
        );
        const isValidWorkspacesConfig = Array.isArray(workspaces) || isYarnClassicWorkspacesObjectConfig;
        if (!workspaces || !isValidWorkspacesConfig) {
          throw new ValidationError(
            "EWORKSPACES",
            import_dedent2.default`
          Lerna is expecting to able to resolve the "workspaces" configuration from your package manager in order to determine what packages to work on, but no "workspaces" config was found.
          (A) Did you mean to specify a "packages" config manually in lerna.json instead of using your workspaces config?
          (B) Alternatively, if you are using pnpm as your package manager, make sure you set "npmClient": "pnpm" in your lerna.json so that lerna knows to read from the "pnpm-workspace.yaml" file instead of package.json.
          See: https://lerna.js.org/docs/getting-started
        `
          );
        }
        import_npmlog8.default.verbose("packageConfigs", `Resolving packages based on package.json "workspaces" configuration.`);
        if (isYarnClassicWorkspacesObjectConfig) {
          return workspaces.packages;
        }
        return workspaces;
      }
    };
    getPackages = Project.getPackages;
    getPackagesSync = Project.getPackagesSync;
  }
});

// libs/core/src/lib/write-log-file.ts
function writeLogFile(cwd) {
  let logOutput = "";
  import_npmlog9.default.record.forEach((m) => {
    let pref = [m.id, m.level];
    if (m.prefix) {
      pref.push(m.prefix);
    }
    pref = pref.join(" ");
    m.message.trim().split(/\r?\n/).map((line) => `${pref} ${line}`.trim()).forEach((line) => {
      logOutput += line + import_os2.default.EOL;
    });
  });
  import_write_file_atomic.default.sync(import_path6.default.join(cwd, "lerna-debug.log"), logOutput);
  import_npmlog9.default.record.length = 0;
}
var import_npmlog9, import_os2, import_path6, import_write_file_atomic;
var init_write_log_file = __esm({
  "libs/core/src/lib/write-log-file.ts"() {
    "use strict";
    import_npmlog9 = __toESM(require("npmlog"));
    import_os2 = __toESM(require("os"));
    import_path6 = __toESM(require("path"));
    import_write_file_atomic = __toESM(require("write-file-atomic"));
  }
});

// libs/core/src/lib/command/clean-stack.ts
function cleanStack(err, className) {
  const lines = isErrorWithStack(err) ? err.stack.split("\n") : String(err).split("\n");
  const cutoff = new RegExp(`^    at ${className}.runCommand .*$`);
  const relevantIndex = lines.findIndex((line) => cutoff.test(line));
  if (relevantIndex) {
    return lines.slice(0, relevantIndex).join("\n");
  }
  return err.toString();
}
function isErrorWithStack(err) {
  return err.stack !== void 0;
}
var init_clean_stack = __esm({
  "libs/core/src/lib/command/clean-stack.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/command/default-options.ts
function defaultOptions(...sources) {
  const options = {};
  for (const source of sources) {
    if (source != null) {
      for (const key of Object.keys(source)) {
        if (options[key] === void 0) {
          options[key] = source[key];
        }
      }
    }
  }
  return options;
}
var init_default_options = __esm({
  "libs/core/src/lib/command/default-options.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/get-package-manifest-path.ts
function getPackageManifestPath(node, files) {
  const pkgJsonPath = (0, import_path7.resolve)((0, import_path7.join)(node.data.root, "package.json"));
  return files.find((f) => (0, import_path7.resolve)(f.file) === pkgJsonPath)?.file;
}
var import_path7;
var init_get_package_manifest_path = __esm({
  "libs/core/src/lib/get-package-manifest-path.ts"() {
    "use strict";
    import_path7 = require("path");
  }
});

// libs/core/src/lib/command/create-project-graph-with-packages.ts
async function createProjectGraphWithPackages(projectGraph, projectFileMap, packageConfigs) {
  const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || import_devkit3.workspaceRoot;
  const projectNodes = Object.values(projectGraph.nodes);
  const projectNodesMatchingPackageConfigs = projectNodes.filter((node) => {
    const matchesRootPath = (config) => (0, import_minimatch2.default)(node.data.root, config);
    return packageConfigs.some(matchesRootPath);
  });
  const tuples = await Promise.all(
    projectNodesMatchingPackageConfigs.map(
      (node) => new Promise((resolve3) => {
        const manifestPath = getPackageManifestPath(node, projectFileMap[node.name] || []);
        if (manifestPath) {
          const fullManifestPath = (0, import_path8.join)(_workspaceRoot, manifestPath);
          resolve3((0, import_fs_extra.readJson)(fullManifestPath).then((manifest) => [node, manifest]));
        } else {
          resolve3([node, null]);
        }
      })
    )
  );
  const projectGraphWithOrderedNodes = {
    ...projectGraph,
    nodes: {},
    localPackageDependencies: {}
  };
  const projectLookupByPackageName = {};
  const sortedTuples = (0, import_lodash3.sortBy)(tuples, (t) => t[0].data.root);
  sortedTuples.forEach(([node, manifest]) => {
    let pkg = null;
    if (manifest) {
      pkg = new Package(manifest, (0, import_path8.join)(_workspaceRoot, node.data.root), _workspaceRoot);
      projectLookupByPackageName[pkg.name] = node.name;
    }
    projectGraphWithOrderedNodes.nodes[node.name] = {
      ...node,
      package: pkg
    };
  });
  projectGraphWithOrderedNodes.dependencies = (0, import_lodash3.reduce)(
    (0, import_lodash3.sortBy)(Object.keys(projectGraphWithOrderedNodes.dependencies)),
    (prev, next) => ({ ...prev, [next]: projectGraphWithOrderedNodes.dependencies[next] }),
    {}
  );
  Object.values(projectGraphWithOrderedNodes.dependencies).forEach((projectDeps) => {
    const workspaceDeps = projectDeps.filter(
      (dep) => !isExternalNpmDependency(dep.target) && !isExternalNpmDependency(dep.source)
    );
    for (const dep of workspaceDeps) {
      const source = projectGraphWithOrderedNodes.nodes[dep.source];
      const target = projectGraphWithOrderedNodes.nodes[dep.target];
      if (!source || !source.package || !target || !target.package) {
        continue;
      }
      const sourcePkg = getPackage(source);
      const targetPkg = getPackage(target);
      const sourceNpmDependency = sourcePkg.getLocalDependency(targetPkg.name);
      if (!sourceNpmDependency) {
        continue;
      }
      const workspaceDep = dep;
      const resolvedTarget = resolvePackage(
        targetPkg.name,
        targetPkg.version,
        sourceNpmDependency.spec,
        sourcePkg.location
      );
      const targetMatchesRequirement = resolvedTarget.fetchSpec === targetPkg.location || (0, import_semver2.satisfies)(
        targetPkg.version,
        resolvedTarget.gitCommittish || resolvedTarget.gitRange || resolvedTarget.fetchSpec
      );
      workspaceDep.dependencyCollection = sourceNpmDependency.collection;
      workspaceDep.targetResolvedNpaResult = resolvedTarget;
      workspaceDep.targetVersionMatchesDependencyRequirement = targetMatchesRequirement;
      if (workspaceDep.targetVersionMatchesDependencyRequirement) {
        projectGraphWithOrderedNodes.localPackageDependencies[dep.source] = [
          ...projectGraphWithOrderedNodes.localPackageDependencies[dep.source] || [],
          workspaceDep
        ];
      }
    }
  });
  return projectGraphWithOrderedNodes;
}
var import_devkit3, import_fs_extra, import_lodash3, import_minimatch2, import_npm_package_arg2, import_path8, import_semver2, resolvePackage;
var init_create_project_graph_with_packages = __esm({
  "libs/core/src/lib/command/create-project-graph-with-packages.ts"() {
    "use strict";
    import_devkit3 = require("@nx/devkit");
    import_fs_extra = require("fs-extra");
    import_lodash3 = require("lodash");
    import_minimatch2 = __toESM(require("minimatch"));
    import_npm_package_arg2 = require("npm-package-arg");
    import_path8 = require("path");
    import_semver2 = require("semver");
    init_get_package_manifest_path();
    init_package();
    init_project_graph_with_packages();
    resolvePackage = (name, version, spec, location) => {
      spec = spec.replace(/^link:/, "file:");
      const isWorkspaceSpec = /^workspace:/.test(spec);
      let fullWorkspaceSpec;
      let workspaceAlias;
      if (isWorkspaceSpec) {
        fullWorkspaceSpec = spec;
        spec = spec.replace(/^workspace:/, "");
        if (spec === "*" || spec === "^" || spec === "~") {
          workspaceAlias = spec;
          if (version) {
            const prefix = spec === "*" ? "" : spec;
            spec = `${prefix}${version}`;
          } else {
            spec = "*";
          }
        }
      }
      const resolved = (0, import_npm_package_arg2.resolve)(name, spec, location);
      resolved.workspaceSpec = fullWorkspaceSpec;
      resolved.workspaceAlias = workspaceAlias;
      return resolved;
    };
  }
});

// libs/core/src/lib/command/detect-projects.ts
async function detectProjects(packageConfigs) {
  const _projectGraph = await (0, import_devkit4.createProjectGraphAsync)();
  const projectFileMap = await (0, import_devkit4.createProjectFileMapUsingProjectGraph)(_projectGraph);
  const projectGraph = await createProjectGraphWithPackages(_projectGraph, projectFileMap, packageConfigs);
  return {
    projectGraph,
    projectFileMap
  };
}
var import_devkit4;
var init_detect_projects = __esm({
  "libs/core/src/lib/command/detect-projects.ts"() {
    "use strict";
    import_devkit4 = require("@nx/devkit");
    init_create_project_graph_with_packages();
  }
});

// libs/core/src/lib/command/is-git-initialized.ts
function isGitInitialized(cwd) {
  const opts = {
    cwd,
    // don't throw, just want boolean
    reject: false,
    // only return code, no stdio needed
    stdio: "ignore"
  };
  return import_execa2.default.sync("git", ["rev-parse"], opts).exitCode === 0;
}
var import_execa2;
var init_is_git_initialized = __esm({
  "libs/core/src/lib/command/is-git-initialized.ts"() {
    "use strict";
    import_execa2 = __toESM(require("execa"));
  }
});

// libs/core/src/lib/command/log-package-error.ts
function logPackageError(err, stream = false) {
  import_npmlog10.default.error(err.command, `exited ${err.exitCode} in '${err.pkg.name}'`);
  if (stream) {
    return;
  }
  if (err.stdout) {
    import_npmlog10.default.error(err.command, "stdout:");
    directLog(err.stdout);
  }
  if (err.stderr) {
    import_npmlog10.default.error(err.command, "stderr:");
    directLog(err.stderr);
  }
  import_npmlog10.default.error(err.command, `exited ${err.exitCode} in '${err.pkg.name}'`);
}
function directLog(message) {
  import_npmlog10.default.pause();
  console.error(message);
  import_npmlog10.default.resume();
}
var import_npmlog10;
var init_log_package_error = __esm({
  "libs/core/src/lib/command/log-package-error.ts"() {
    "use strict";
    import_npmlog10 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/command/warn-if-hanging.ts
function warnIfHanging() {
  const childProcessCount = childProcess4.getChildProcessCount();
  if (childProcessCount > 0) {
    import_npmlog11.default.warn(
      "complete",
      `Waiting for ${childProcessCount} child process${childProcessCount === 1 ? "" : "es"} to exit. CTRL-C to exit immediately.`
    );
  }
}
var import_npmlog11, childProcess4;
var init_warn_if_hanging = __esm({
  "libs/core/src/lib/command/warn-if-hanging.ts"() {
    "use strict";
    import_npmlog11 = __toESM(require("npmlog"));
    childProcess4 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/command/index.ts
var import_clone_deep, import_dedent3, import_npmlog12, import_client, import_os3, DEFAULT_CONCURRENCY, Command;
var init_command = __esm({
  "libs/core/src/lib/command/index.ts"() {
    "use strict";
    import_clone_deep = __toESM(require("clone-deep"));
    import_dedent3 = __toESM(require("dedent"));
    import_npmlog12 = __toESM(require("npmlog"));
    import_client = require("nx/src/daemon/client/client");
    import_os3 = __toESM(require("os"));
    init_project();
    init_validation_error();
    init_write_log_file();
    init_clean_stack();
    init_default_options();
    init_detect_projects();
    init_is_git_initialized();
    init_log_package_error();
    init_warn_if_hanging();
    DEFAULT_CONCURRENCY = import_os3.default.cpus().length;
    Command = class _Command {
      constructor(_argv, {
        skipValidations,
        preInitializedProjectData
      } = { skipValidations: false }) {
        this.options = {};
        this.concurrency = 0;
        this.toposort = false;
        this.execOpts = {};
        this.argv = {};
        import_npmlog12.default.pause();
        import_npmlog12.default.heading = "lerna";
        const argv = (0, import_clone_deep.default)(_argv);
        import_npmlog12.default.silly(
          "argv",
          argv
          /*types declaration of npmlog is not correct here see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/67232 */
        );
        this.name = this.constructor.name.replace(/Command$/, "").toLowerCase();
        this.composed = typeof argv.composed === "string" && argv.composed !== this.name;
        if (!this.composed) {
          import_npmlog12.default.notice("cli", `v${argv.lernaVersion}`);
        }
        let runner = new Promise((resolve3, reject) => {
          let chain = Promise.resolve();
          chain = chain.then(() => {
            this.project = new Project(argv.cwd, { skipLernaConfigValidations: skipValidations });
          });
          chain = chain.then(() => this.configureEnvironment());
          chain = chain.then(() => this.configureOptions());
          chain = chain.then(() => this.configureProperties());
          chain = chain.then(() => {
            this.logger = _Command.createLogger(this.name, this.options.loglevel);
          });
          if (!skipValidations) {
            chain = chain.then(() => this.runValidations());
          }
          chain = chain.then(() => {
            if (preInitializedProjectData) {
              this.projectFileMap = preInitializedProjectData.projectFileMap;
              this.projectGraph = preInitializedProjectData.projectGraph;
              return;
            }
            return this.detectProjects();
          });
          chain = chain.then(() => this.runPreparations());
          chain = chain.then(() => this.runCommand());
          chain.then(
            (result) => {
              warnIfHanging();
              import_client.daemonClient.reset();
              resolve3(result);
            },
            (err) => {
              if (err.pkg) {
                logPackageError(err, this.options.stream);
              } else if (err.name !== "ValidationError") {
                import_npmlog12.default.error("", cleanStack(err, this.constructor.name));
              }
              if (err.name !== "ValidationError" && !err.pkg) {
                writeLogFile(this.project.rootPath);
              }
              warnIfHanging();
              import_client.daemonClient.reset();
              reject(err);
            }
          );
        });
        if (argv.onResolved || argv.onRejected) {
          runner = runner.then(argv.onResolved, argv.onRejected);
          delete argv.onResolved;
          delete argv.onRejected;
        }
        for (const key of ["cwd", "$0"]) {
          Object.defineProperty(argv, key, { enumerable: false });
        }
        Object.defineProperty(this, "argv", {
          value: Object.freeze(argv)
        });
        this.runner = runner;
      }
      get project() {
        if (this._project === void 0) {
          throw new ValidationError("ENOPROJECT", "Lerna Project not initialized!");
        }
        return this._project;
      }
      set project(project) {
        this._project = project;
      }
      static createLogger(name, loglevel) {
        if (loglevel) {
          import_npmlog12.default.level = loglevel;
        }
        import_npmlog12.default.addLevel("success", 3001, { fg: "green", bold: true });
        import_npmlog12.default.resume();
        return import_npmlog12.default["newGroup"](name);
      }
      // proxy "Promise" methods to "private" instance
      then(onResolved, onRejected) {
        return this.runner.then(onResolved, onRejected);
      }
      /* istanbul ignore next */
      catch(onRejected) {
        return this.runner.catch(onRejected);
      }
      get requiresGit() {
        return true;
      }
      // Override this to inherit config from another command.
      // For example `changed` inherits config from `publish`.
      get otherCommandConfigs() {
        return [];
      }
      async detectProjects() {
        const { projectGraph, projectFileMap } = await detectProjects(this.project.packageConfigs);
        this.projectGraph = projectGraph;
        this.projectFileMap = projectFileMap;
      }
      configureEnvironment() {
        const ci = require("is-ci");
        let loglevel;
        let progress;
        if (ci || !process.stderr.isTTY) {
          import_npmlog12.default.disableColor();
          progress = false;
        } else if (!process.stdout.isTTY) {
          progress = false;
          loglevel = "error";
        } else if (process.stderr.isTTY) {
          import_npmlog12.default.enableColor();
          import_npmlog12.default.enableUnicode();
        }
        Object.defineProperty(this, "envDefaults", {
          value: {
            ci,
            progress,
            loglevel
          }
        });
      }
      configureOptions() {
        const commandConfig = this.project.config.command || {};
        const overrides = [this.name, ...this.otherCommandConfigs].map((key) => commandConfig[key]);
        this.options = defaultOptions(
          // CLI flags, which if defined overrule subsequent values
          this.argv,
          ...overrides,
          // Global options from `lerna.json`
          this.project.config,
          // Environmental defaults prepared in previous step
          this.envDefaults
        );
        if (this.options.verbose && this.options.loglevel !== "silly") {
          this.options.loglevel = "verbose";
        }
      }
      configureProperties() {
        const { concurrency = 0, sort, maxBuffer } = this.options;
        this.concurrency = Math.max(1, +concurrency || DEFAULT_CONCURRENCY);
        this.toposort = sort === void 0 || sort;
        this.execOpts = {
          cwd: this.project.rootPath,
          maxBuffer
        };
      }
      enableProgressBar() {
        if (this.options.progress !== false) {
          import_npmlog12.default.enableProgress();
        }
      }
      runValidations() {
        if ((this.options.since !== void 0 || this.requiresGit) && !isGitInitialized(this.project.rootPath)) {
          throw new ValidationError("ENOGIT", "The git binary was not found, or this is not a git repository.");
        }
        if (this.options.independent && !this.project.isIndependent()) {
          throw new ValidationError(
            "EVERSIONMODE",
            import_dedent3.default`
          You ran lerna with --independent or -i, but the repository is not set to independent mode.
          To use independent mode you need to set lerna.json's "version" property to "independent".
          Then you won't need to pass the --independent or -i flags.
        `
          );
        }
      }
      runPreparations() {
        if (!this.composed && this.project.isIndependent()) {
          import_npmlog12.default.info("versioning", "independent");
        }
        if (!this.composed && this.options.ci) {
          import_npmlog12.default.info("ci", "enabled");
        }
      }
      async runCommand() {
        const proceed = await this.initialize();
        if (proceed !== false) {
          return this.execute();
        }
        return void 0;
      }
      initialize() {
        throw new ValidationError(this.name, "initialize() needs to be implemented.");
      }
      /**
       * The execute() method can return a value in some cases (e.g. on the version command)
       */
      execute() {
        throw new ValidationError(this.name, "execute() needs to be implemented.");
      }
    };
  }
});

// libs/core/src/lib/conventional-commits/apply-build-metadata.ts
function applyBuildMetadata(version, buildMetadata) {
  if (!buildMetadata) {
    return version;
  }
  if (isValidBuildMetadata(buildMetadata)) {
    return `${version}+${buildMetadata}`;
  }
  throw new ValidationError("EBUILDMETADATA", "Build metadata does not satisfy SemVer specification.");
}
function isValidBuildMetadata(buildMetadata) {
  return BUILD_METADATA_REGEX.test(buildMetadata);
}
var BUILD_METADATA_REGEX;
var init_apply_build_metadata = __esm({
  "libs/core/src/lib/conventional-commits/apply-build-metadata.ts"() {
    "use strict";
    init_validation_error();
    BUILD_METADATA_REGEX = /^[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*$/;
  }
});

// libs/core/src/lib/conventional-commits/get-changelog-config.ts
function isFunction(config) {
  return Object.prototype.toString.call(config) === "[object Function]" || Object.prototype.toString.call(config) === "[object AsyncFunction]";
}
function resolveConfigPromise(presetPackageName, presetConfig) {
  import_npmlog13.default.verbose("getChangelogConfig", "Attempting to resolve preset %j", presetPackageName);
  let config = require(presetPackageName);
  import_npmlog13.default.info("getChangelogConfig", "Successfully resolved preset %j", presetPackageName);
  if (isFunction(config)) {
    try {
      config = config(presetConfig);
    } catch (_) {
      config = (0, import_pify.default)(config)();
    }
  }
  return config;
}
function getChangelogConfig(changelogPreset = "conventional-changelog-angular", rootPath) {
  const presetName = typeof changelogPreset === "string" ? changelogPreset : changelogPreset.name;
  const presetConfig = typeof changelogPreset === "object" ? changelogPreset : {};
  const cacheKey = `${presetName}${presetConfig ? JSON.stringify(presetConfig) : ""}`;
  let config = cfgCache.get(cacheKey);
  if (!config) {
    let presetPackageName = presetName;
    const parsed = (0, import_npm_package_arg3.default)(presetPackageName, rootPath);
    import_npmlog13.default.verbose("getChangelogConfig", "using preset %j", presetPackageName);
    import_npmlog13.default.silly("npa", parsed);
    if (parsed.type === "directory") {
      if (parsed.raw[0] === "@") {
        parsed.name = parsed.raw;
        parsed.scope = parsed.raw.substring(0, parsed.raw.indexOf("/"));
      } else {
        presetPackageName = parsed.fetchSpec;
      }
    } else if (parsed.type === "git" && parsed.hosted && parsed.hosted.default === "shortcut") {
      parsed.name = parsed.raw;
    }
    try {
      config = resolveConfigPromise(presetPackageName, presetConfig);
      cfgCache.set(cacheKey, config);
      return Promise.resolve(config);
    } catch (err) {
      import_npmlog13.default.verbose("getChangelogConfig", err.message);
      import_npmlog13.default.info("getChangelogConfig", "Auto-prefixing conventional-changelog preset %j", presetName);
      parsed.name = parsed.raw;
    }
    if (parsed.name.indexOf("conventional-changelog-") < 0) {
      const parts = parsed.name.split("/");
      const start = parsed.scope ? 1 : 0;
      parts.splice(start, 1, `conventional-changelog-${parts[start]}`);
      presetPackageName = parts.join("/");
    }
    try {
      config = resolveConfigPromise(presetPackageName, presetConfig);
      cfgCache.set(cacheKey, config);
    } catch (err) {
      import_npmlog13.default.warn("getChangelogConfig", err.message);
      throw new ValidationError(
        "EPRESET",
        `Unable to load conventional-changelog preset '${presetName}'${presetName !== presetPackageName ? ` (${presetPackageName})` : ""}`
      );
    }
  }
  return Promise.resolve(config);
}
var import_npm_package_arg3, import_npmlog13, import_pify, cfgCache;
var init_get_changelog_config = __esm({
  "libs/core/src/lib/conventional-commits/get-changelog-config.ts"() {
    "use strict";
    import_npm_package_arg3 = __toESM(require("npm-package-arg"));
    import_npmlog13 = __toESM(require("npmlog"));
    import_pify = __toESM(require("pify"));
    init_validation_error();
    cfgCache = /* @__PURE__ */ new Map();
  }
});

// libs/core/src/lib/conventional-commits/recommend-version.ts
function recommendVersion(pkg, type, {
  changelogPreset,
  rootPath,
  tagPrefix,
  prereleaseId,
  conventionalBumpPrerelease,
  buildMetadata
}, premajorVersionBump) {
  import_npmlog14.default.silly(type, "for %s at %s", pkg.name, pkg.location);
  const options = {
    path: pkg.location
  };
  if (type === "independent") {
    options.lernaPackage = pkg.name;
  } else {
    options.tagPrefix = tagPrefix;
  }
  const shouldBumpPrerelease = (releaseType, version) => {
    if (!import_semver3.default.prerelease(version)) {
      return true;
    }
    switch (releaseType) {
      case "major":
        return import_semver3.default.minor(version) !== 0 || import_semver3.default.patch(version) !== 0;
      case "minor":
        return import_semver3.default.patch(version) !== 0;
      default:
        return false;
    }
  };
  let chain = Promise.resolve();
  chain = chain.then(() => getChangelogConfig(changelogPreset, rootPath));
  chain = chain.then((config) => {
    options.config = config;
    return new Promise((resolve3, reject) => {
      (0, import_conventional_recommended_bump.default)(options, (err, data) => {
        if (err) {
          return reject(err);
        }
        let releaseType = data.releaseType || "patch";
        if (prereleaseId) {
          const shouldBump = conventionalBumpPrerelease || shouldBumpPrerelease(releaseType, pkg.version);
          const prereleaseType = shouldBump ? `pre${releaseType}` : "prerelease";
          import_npmlog14.default.verbose(type, "increment %s by %s", pkg.version, prereleaseType);
          resolve3(applyBuildMetadata(import_semver3.default.inc(pkg.version, prereleaseType, prereleaseId), buildMetadata));
        } else {
          if (import_semver3.default.major(pkg.version) === 0) {
            if (releaseType === "major") {
              releaseType = "minor";
            } else if (premajorVersionBump === "force-patch") {
              releaseType = "patch";
            }
          }
          import_npmlog14.default.verbose(type, "increment %s by %s", pkg.version, releaseType);
          resolve3(applyBuildMetadata(import_semver3.default.inc(pkg.version, releaseType), buildMetadata));
        }
      });
    });
  });
  return chain;
}
var import_conventional_recommended_bump, import_npmlog14, import_semver3;
var init_recommend_version = __esm({
  "libs/core/src/lib/conventional-commits/recommend-version.ts"() {
    "use strict";
    import_conventional_recommended_bump = __toESM(require("conventional-recommended-bump"));
    import_npmlog14 = __toESM(require("npmlog"));
    import_semver3 = __toESM(require("semver"));
    init_apply_build_metadata();
    init_get_changelog_config();
  }
});

// libs/core/src/lib/conventional-commits/constants.ts
var EOL, BLANK_LINE, COMMIT_GUIDELINE, CHANGELOG_HEADER;
var init_constants = __esm({
  "libs/core/src/lib/conventional-commits/constants.ts"() {
    "use strict";
    EOL = "\n";
    BLANK_LINE = EOL + EOL;
    COMMIT_GUIDELINE = "See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.";
    CHANGELOG_HEADER = [
      "# Change Log",
      "",
      "All notable changes to this project will be documented in this file.",
      COMMIT_GUIDELINE
    ].join(EOL);
  }
});

// libs/core/src/lib/conventional-commits/make-bump-only-filter.ts
function makeBumpOnlyFilter(pkg) {
  return (newEntry) => {
    if (!newEntry.split("\n").some((line) => line.startsWith("*"))) {
      const message = `**Note:** Version bump only for package ${pkg.name}`;
      return [newEntry.trim(), message, BLANK_LINE].join(BLANK_LINE);
    }
    return newEntry;
  };
}
var init_make_bump_only_filter = __esm({
  "libs/core/src/lib/conventional-commits/make-bump-only-filter.ts"() {
    "use strict";
    init_constants();
  }
});

// libs/core/src/lib/conventional-commits/read-existing-changelog.ts
function readExistingChangelog(pkg) {
  const changelogFileLoc = import_path9.default.join(pkg.location, "CHANGELOG.md");
  let chain = Promise.resolve();
  chain = chain.then(() => import_fs_extra2.default.readFile(changelogFileLoc, "utf8").catch(() => ""));
  chain = chain.then((changelogContents) => {
    const headerIndex = changelogContents.indexOf(COMMIT_GUIDELINE);
    if (headerIndex !== -1) {
      return changelogContents.substring(headerIndex + COMMIT_GUIDELINE.length + BLANK_LINE.length);
    }
    return changelogContents;
  });
  chain = chain.then((changelogContents) => [changelogFileLoc, changelogContents]);
  return chain;
}
var import_fs_extra2, import_path9;
var init_read_existing_changelog = __esm({
  "libs/core/src/lib/conventional-commits/read-existing-changelog.ts"() {
    "use strict";
    import_fs_extra2 = __toESM(require("fs-extra"));
    import_path9 = __toESM(require("path"));
    init_constants();
  }
});

// libs/core/src/lib/conventional-commits/update-changelog.ts
function updateChangelog(pkg, type, {
  changelogPreset,
  changelogEntryAdditionalMarkdown,
  rootPath,
  tagPrefix = "v",
  version
}) {
  import_npmlog15.default.silly(type, "for %s at %s", pkg.name, pkg.location);
  return getChangelogConfig(changelogPreset, rootPath).then((config) => {
    const options = {};
    const context = {};
    if (config.conventionalChangelog) {
      options.config = Object.assign({}, config.conventionalChangelog);
    } else {
      options.config = Object.assign({}, config);
    }
    const gitRawCommitsOpts = Object.assign({}, options.config.gitRawCommitsOpts);
    if (type === "root") {
      context.version = version;
      context.currentTag = `${tagPrefix}${version}`;
      options.tagPrefix = tagPrefix;
    } else {
      gitRawCommitsOpts.path = pkg.location;
      options.pkg = { path: pkg.manifestLocation };
      if (type === "independent") {
        options.lernaPackage = pkg.name;
      } else {
        options.tagPrefix = tagPrefix;
        context.currentTag = `${tagPrefix}${pkg.version}`;
      }
    }
    const changelogStream = (0, import_conventional_changelog_core.default)(options, context, gitRawCommitsOpts);
    return Promise.all([
      (0, import_get_stream.default)(changelogStream).then(makeBumpOnlyFilter(pkg)),
      readExistingChangelog(pkg)
    ]).then(([newEntry, [changelogFileLoc, changelogContents]]) => {
      if (changelogEntryAdditionalMarkdown) {
        const trailingWhitespace = newEntry.match(/\s*$/);
        newEntry = newEntry.replace(
          /\s*$/,
          BLANK_LINE + changelogEntryAdditionalMarkdown + trailingWhitespace
        );
      }
      import_npmlog15.default.silly(type, "writing new entry: %j", newEntry);
      const content = [CHANGELOG_HEADER, newEntry, changelogContents].join(BLANK_LINE);
      return import_fs_extra3.default.writeFile(changelogFileLoc, content.trim() + EOL).then(() => {
        import_npmlog15.default.verbose(type, "wrote", changelogFileLoc);
        return {
          logPath: changelogFileLoc,
          newEntry
        };
      });
    });
  });
}
var import_conventional_changelog_core, import_fs_extra3, import_get_stream, import_npmlog15;
var init_update_changelog = __esm({
  "libs/core/src/lib/conventional-commits/update-changelog.ts"() {
    "use strict";
    import_conventional_changelog_core = __toESM(require("conventional-changelog-core"));
    import_fs_extra3 = __toESM(require("fs-extra"));
    import_get_stream = __toESM(require("get-stream"));
    import_npmlog15 = __toESM(require("npmlog"));
    init_constants();
    init_get_changelog_config();
    init_make_bump_only_filter();
    init_read_existing_changelog();
  }
});

// libs/core/src/lib/conventional-commits/index.ts
var init_conventional_commits = __esm({
  "libs/core/src/lib/conventional-commits/index.ts"() {
    "use strict";
    init_recommend_version();
    init_update_changelog();
    init_apply_build_metadata();
  }
});

// libs/core/src/lib/corepack/is-corepack-enabled.ts
function isCorepackEnabled() {
  return process.env["COREPACK_ROOT"] !== void 0;
}
var init_is_corepack_enabled = __esm({
  "libs/core/src/lib/corepack/is-corepack-enabled.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/corepack/exec-package-manager.ts
function createCommandAndArgs(npmClient, args) {
  let command = npmClient;
  const commandArgs = [...args];
  if (isCorepackEnabled()) {
    commandArgs.unshift(command);
    command = "corepack";
  }
  return { command, commandArgs };
}
function execPackageManager(npmClient, args, opts) {
  const { command, commandArgs } = createCommandAndArgs(npmClient, args);
  return childProcess5.exec(command, commandArgs, opts);
}
function execPackageManagerSync(npmClient, args, opts) {
  const { command, commandArgs } = createCommandAndArgs(npmClient, args);
  return childProcess5.execSync(command, commandArgs, opts);
}
var childProcess5;
var init_exec_package_manager = __esm({
  "libs/core/src/lib/corepack/exec-package-manager.ts"() {
    "use strict";
    init_is_corepack_enabled();
    childProcess5 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/corepack/index.ts
var init_corepack = __esm({
  "libs/core/src/lib/corepack/index.ts"() {
    "use strict";
    init_exec_package_manager();
  }
});

// libs/core/src/lib/filter-options.ts
var import_dedent4, import_npmlog16;
var init_filter_options = __esm({
  "libs/core/src/lib/filter-options.ts"() {
    "use strict";
    import_dedent4 = __toESM(require("dedent"));
    import_npmlog16 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/filter-projects.ts
var import_multimatch, import_npmlog17;
var init_filter_projects = __esm({
  "libs/core/src/lib/filter-projects.ts"() {
    "use strict";
    import_multimatch = __toESM(require("multimatch"));
    import_npmlog17 = __toESM(require("npmlog"));
    init_add_dependencies();
    init_add_dependents();
    init_collect_project_updates();
    init_validation_error();
  }
});

// libs/core/src/lib/git-checkout.ts
function gitCheckout(stagedFiles, gitOpts, execOpts) {
  const files = gitOpts.granularPathspec ? stagedFiles : ".";
  import_npmlog18.default.silly("gitCheckout", files);
  return childProcess6.exec("git", ["checkout", "--"].concat(files), execOpts);
}
var import_npmlog18, childProcess6;
var init_git_checkout = __esm({
  "libs/core/src/lib/git-checkout.ts"() {
    "use strict";
    import_npmlog18 = __toESM(require("npmlog"));
    childProcess6 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/has-npm-version.ts
var import_semver4, childProcess7;
var init_has_npm_version = __esm({
  "libs/core/src/lib/has-npm-version.ts"() {
    "use strict";
    import_semver4 = __toESM(require("semver"));
    childProcess7 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/cycles/get-cycles.ts
function getCycles(dependencies) {
  const cycles = [];
  const visited = /* @__PURE__ */ new Set();
  function dfs(next, path19) {
    visited.add(next);
    path19.push(next);
    for (const dep of dependencies[next] || []) {
      if (path19.includes(dep)) {
        const cycle = path19.slice(path19.indexOf(dep));
        cycles.push(cycle);
      } else if (!visited.has(dep)) {
        dfs(dep, path19);
      }
    }
    path19.pop();
  }
  for (const next of Object.keys(dependencies)) {
    if (!visited.has(next)) {
      dfs(next, []);
    }
  }
  return cycles;
}
var init_get_cycles = __esm({
  "libs/core/src/lib/cycles/get-cycles.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/cycles/merge-overlapping-cycles.ts
function mergeOverlappingCycles(cycles) {
  const mergedCycles = [];
  cycles.forEach((cycle) => {
    let intersectionNodes = [];
    const mergedCycle = mergedCycles.find((mergedCycle2) => {
      intersectionNodes = (0, import_lodash4.intersection)(mergedCycle2, cycle);
      return intersectionNodes.length > 0;
    });
    if (mergedCycle) {
      mergedCycle.push(...(0, import_lodash4.difference)(cycle, intersectionNodes));
    } else {
      mergedCycles.push(cycle);
    }
  });
  return mergedCycles;
}
var import_lodash4;
var init_merge_overlapping_cycles = __esm({
  "libs/core/src/lib/cycles/merge-overlapping-cycles.ts"() {
    "use strict";
    import_lodash4 = require("lodash");
  }
});

// libs/core/src/lib/cycles/report-cycles.ts
function reportCycles(cycles, rejectCycles) {
  const cyclesWithRepeatedNodes = cycles.map((cycle) => [...cycle, cycle[0]]);
  const paths = Array.from(cyclesWithRepeatedNodes, (cycle) => cycle.join(" -> "), false);
  if (!paths.length) {
    return;
  }
  const cycleMessage = ["Dependency cycles detected, you should fix these!"].concat(paths).join("\n");
  if (rejectCycles) {
    throw new ValidationError("ECYCLE", cycleMessage);
  }
  import_npmlog19.default.warn("ECYCLE", cycleMessage);
}
var import_npmlog19;
var init_report_cycles = __esm({
  "libs/core/src/lib/cycles/report-cycles.ts"() {
    "use strict";
    import_npmlog19 = __toESM(require("npmlog"));
    init_validation_error();
  }
});

// libs/core/src/lib/cycles/index.ts
var init_cycles = __esm({
  "libs/core/src/lib/cycles/index.ts"() {
    "use strict";
    init_get_cycles();
    init_merge_overlapping_cycles();
    init_report_cycles();
  }
});

// libs/core/src/lib/toposort-projects.ts
var import_lodash5;
var init_toposort_projects = __esm({
  "libs/core/src/lib/toposort-projects.ts"() {
    "use strict";
    import_lodash5 = require("lodash");
    init_cycles();
  }
});

// libs/core/src/lib/listable-format-projects.ts
function toJSONList(resultList, addtionalProperties = () => ({})) {
  return resultList.map((project) => {
    const pkg = getPackage(project);
    return {
      name: pkg.name,
      version: pkg.version,
      private: pkg.private,
      location: pkg.location,
      ...addtionalProperties(project)
    };
  });
}
function formatJSON(resultList, additionalProperties = () => ({})) {
  return JSON.stringify(toJSONList(resultList, additionalProperties), null, 2);
}
var import_chalk3, import_columnify;
var init_listable_format_projects = __esm({
  "libs/core/src/lib/listable-format-projects.ts"() {
    "use strict";
    import_chalk3 = __toESM(require("chalk"));
    import_columnify = __toESM(require("columnify"));
    init_project_graph_with_packages();
    init_toposort_projects();
  }
});

// libs/core/src/lib/listable-options.ts
var init_listable_options = __esm({
  "libs/core/src/lib/listable-options.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/log-packed.ts
function logPacked(tarball) {
  import_npmlog20.default.notice("");
  import_npmlog20.default.notice("", `${hasUnicode ? "\u{1F4E6} " : "package:"} ${tarball.name}@${tarball.version}`);
  if (tarball.files && tarball.files.length) {
    import_npmlog20.default.notice("=== Tarball Contents ===");
    import_npmlog20.default.notice(
      "",
      (0, import_columnify2.default)(
        tarball.files.map((f) => {
          const bytes = (0, import_byte_size.default)(f.size);
          return {
            path: f.path,
            size: `${bytes.value}${bytes.unit}`
          };
        }),
        {
          // TODO: refactor based on TS feedback
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          include: ["size", "path"],
          showHeaders: false
        }
      )
    );
  }
  if (tarball.bundled && tarball.bundled.length) {
    import_npmlog20.default.notice("=== Bundled Dependencies ===");
    tarball.bundled.forEach((name) => import_npmlog20.default.notice("", name));
  }
  import_npmlog20.default.notice("=== Tarball Details ===");
  import_npmlog20.default.notice(
    "",
    (0, import_columnify2.default)(
      [
        { name: "name:", value: tarball.name },
        { name: "version:", value: tarball.version },
        tarball.filename && { name: "filename:", value: tarball.filename },
        tarball.size && { name: "package size:", value: (0, import_byte_size.default)(tarball.size) },
        tarball.unpackedSize && { name: "unpacked size:", value: (0, import_byte_size.default)(tarball.unpackedSize) },
        tarball.shasum && { name: "shasum:", value: tarball.shasum },
        tarball.integrity && { name: "integrity:", value: elideIntegrity(tarball.integrity) },
        tarball.bundled && tarball.bundled.length && {
          name: "bundled deps:",
          value: tarball.bundled.length
        },
        tarball.bundled && tarball.bundled.length && {
          name: "bundled files:",
          value: tarball.entryCount - tarball.files.length
        },
        tarball.bundled && tarball.bundled.length && {
          name: "own files:",
          value: tarball.files.length
        },
        tarball.entryCount && { name: "total files:", value: tarball.entryCount }
      ].filter((x) => x),
      {
        // TODO: refactor based on TS feedback
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        include: ["name", "value"],
        showHeaders: false
      }
    )
  );
  import_npmlog20.default.notice("", "");
}
function elideIntegrity(integrity) {
  const str = integrity.toString();
  return `${str.substr(0, 20)}[...]${str.substr(80)}`;
}
var import_byte_size, import_columnify2, import_npmlog20, import_has_unicode, hasUnicode;
var init_log_packed = __esm({
  "libs/core/src/lib/log-packed.ts"() {
    "use strict";
    import_byte_size = __toESM(require("byte-size"));
    import_columnify2 = __toESM(require("columnify"));
    import_npmlog20 = __toESM(require("npmlog"));
    import_has_unicode = __toESM(require("has-unicode"));
    hasUnicode = (0, import_has_unicode.default)();
  }
});

// libs/core/src/lib/npm-conf/env-replace.ts
function envReplace(str) {
  if (typeof str !== "string" || !str) {
    return str;
  }
  const regex = /(\\*)\$\{([^}]+)\}/g;
  return str.replace(regex, (orig, esc, name) => {
    esc = esc.length > 0 && esc.length % 2;
    if (esc) {
      return orig;
    }
    if (process.env[name] === void 0) {
      throw new Error(`Failed to replace env in config: ${orig}`);
    }
    return process.env[name];
  });
}
var init_env_replace = __esm({
  "libs/core/src/lib/npm-conf/env-replace.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/npm-conf/find-prefix.ts
function findPrefix(start) {
  let dir = import_path10.default.resolve(start);
  let walkedUp = false;
  while (import_path10.default.basename(dir) === "node_modules") {
    dir = import_path10.default.dirname(dir);
    walkedUp = true;
  }
  if (walkedUp) {
    return dir;
  }
  return find(dir, dir);
}
function find(name, original) {
  if (name === "/" || process.platform === "win32" && /^[a-zA-Z]:(\\|\/)?$/.test(name)) {
    return original;
  }
  try {
    const files = import_fs3.default.readdirSync(name);
    if (files.indexOf("node_modules") !== -1 || files.indexOf("package.json") !== -1) {
      return name;
    }
    const dirname = import_path10.default.dirname(name);
    if (dirname === name) {
      return original;
    }
    return find(dirname, original);
  } catch (err) {
    if (name === original) {
      if (err.code === "ENOENT") {
        return original;
      }
      throw err;
    }
    return original;
  }
}
var import_fs3, import_path10;
var init_find_prefix = __esm({
  "libs/core/src/lib/npm-conf/find-prefix.ts"() {
    "use strict";
    import_fs3 = __toESM(require("fs"));
    import_path10 = __toESM(require("path"));
  }
});

// libs/core/src/lib/npm-conf/types.ts
var require_types = __commonJS({
  "libs/core/src/lib/npm-conf/types.ts"(exports2) {
    "use strict";
    var import_path22 = __toESM(require("path"));
    var import_stream = require("stream");
    var import_url2 = __toESM(require("url"));
    var Umask = () => {
    };
    var getLocalAddresses = () => [];
    var semver7 = () => {
    };
    exports2.types = {
      access: [null, "restricted", "public"],
      "allow-same-version": Boolean,
      "always-auth": Boolean,
      also: [null, "dev", "development"],
      audit: Boolean,
      "audit-level": ["low", "moderate", "high", "critical"],
      "auth-type": ["legacy", "sso", "saml", "oauth"],
      "bin-links": Boolean,
      browser: [null, String],
      ca: [null, String, Array],
      cafile: import_path22.default,
      cache: import_path22.default,
      "cache-lock-stale": Number,
      "cache-lock-retries": Number,
      "cache-lock-wait": Number,
      "cache-max": Number,
      "cache-min": Number,
      cert: [null, String],
      cidr: [null, String, Array],
      color: ["always", Boolean],
      depth: Number,
      description: Boolean,
      dev: Boolean,
      "dry-run": Boolean,
      editor: String,
      "engine-strict": Boolean,
      force: Boolean,
      "fetch-retries": Number,
      "fetch-retry-factor": Number,
      "fetch-retry-mintimeout": Number,
      "fetch-retry-maxtimeout": Number,
      git: String,
      "git-tag-version": Boolean,
      "commit-hooks": Boolean,
      global: Boolean,
      globalconfig: import_path22.default,
      "global-style": Boolean,
      group: [Number, String],
      "https-proxy": [null, import_url2.default],
      "user-agent": String,
      "ham-it-up": Boolean,
      heading: String,
      "if-present": Boolean,
      "ignore-prepublish": Boolean,
      "ignore-scripts": Boolean,
      "init-module": import_path22.default,
      "init-author-name": String,
      "init-author-email": String,
      "init-author-url": ["", import_url2.default],
      "init-license": String,
      "init-version": semver7,
      json: Boolean,
      key: [null, String],
      "legacy-bundling": Boolean,
      link: Boolean,
      "local-address": getLocalAddresses(),
      loglevel: ["silent", "error", "warn", "notice", "http", "timing", "info", "verbose", "silly"],
      logstream: import_stream.Stream,
      "logs-max": Number,
      long: Boolean,
      maxsockets: Number,
      message: String,
      "metrics-registry": [null, String],
      "node-options": [null, String],
      "node-version": [null, semver7],
      noproxy: [null, String, Array],
      offline: Boolean,
      "onload-script": [null, String],
      only: [null, "dev", "development", "prod", "production"],
      optional: Boolean,
      "package-lock": Boolean,
      otp: [null, String],
      "package-lock-only": Boolean,
      parseable: Boolean,
      "prefer-offline": Boolean,
      "prefer-online": Boolean,
      prefix: import_path22.default,
      preid: String,
      production: Boolean,
      progress: Boolean,
      // allow proxy to be disabled explicitly
      proxy: [null, false, import_url2.default],
      "read-only": Boolean,
      "rebuild-bundle": Boolean,
      registry: [null, import_url2.default],
      rollback: Boolean,
      save: Boolean,
      "save-bundle": Boolean,
      "save-dev": Boolean,
      "save-exact": Boolean,
      "save-optional": Boolean,
      "save-prefix": String,
      "save-prod": Boolean,
      scope: String,
      "script-shell": [null, String],
      "scripts-prepend-node-path": [false, true, "auto", "warn-only"],
      searchopts: String,
      searchexclude: [null, String],
      searchlimit: Number,
      searchstaleness: Number,
      "send-metrics": Boolean,
      shell: String,
      shrinkwrap: Boolean,
      "sign-git-commit": Boolean,
      "sign-git-tag": Boolean,
      "sso-poll-frequency": Number,
      "sso-type": [null, "oauth", "saml"],
      "strict-ssl": Boolean,
      tag: String,
      timing: Boolean,
      tmp: import_path22.default,
      unicode: Boolean,
      "unsafe-perm": Boolean,
      "update-notifier": Boolean,
      usage: Boolean,
      user: [Number, String],
      userconfig: import_path22.default,
      umask: Umask,
      version: Boolean,
      "tag-version-prefix": String,
      versions: Boolean,
      viewer: String,
      _exit: Boolean
    };
  }
});

// libs/core/src/lib/npm-conf/parse-field.ts
function parseField(input, key) {
  if (typeof input !== "string") {
    return input;
  }
  const typeList = [].concat(types[key]);
  const isPath = typeList.indexOf(import_path11.default) !== -1;
  const isBool = typeList.indexOf(Boolean) !== -1;
  const isString = typeList.indexOf(String) !== -1;
  const isNumber = typeList.indexOf(Number) !== -1;
  let field = `${input}`.trim();
  if (/^".*"$/.test(field)) {
    try {
      field = JSON.parse(field);
    } catch (err) {
      throw new Error(`Failed parsing JSON config key ${key}: ${field}`);
    }
  }
  if (isBool && !isString && field === "") {
    return true;
  }
  switch (field) {
    case "true": {
      return true;
    }
    case "false": {
      return false;
    }
    case "null": {
      return null;
    }
    case "undefined": {
      return void 0;
    }
  }
  field = envReplace(field);
  if (isPath) {
    const regex = process.platform === "win32" ? /^~(\/|\\)/ : /^~\//;
    if (regex.test(field) && process.env["HOME"]) {
      field = import_path11.default.resolve(process.env["HOME"], field.substr(2));
    }
    field = import_path11.default.resolve(field);
  }
  if (isNumber && !Number.isNaN(field)) {
    field = Number(field);
  }
  return field;
}
var import_path11, types;
var init_parse_field = __esm({
  "libs/core/src/lib/npm-conf/parse-field.ts"() {
    "use strict";
    import_path11 = __toESM(require("path"));
    init_env_replace();
    ({ types } = require_types());
  }
});

// libs/core/src/lib/npm-conf/nerf-dart.ts
function toNerfDart(uri) {
  const parsed = import_url.default.parse(uri);
  delete parsed.protocol;
  delete parsed.auth;
  delete parsed.query;
  delete parsed.search;
  delete parsed.hash;
  return import_url.default.resolve(import_url.default.format(parsed), ".");
}
var import_url;
var init_nerf_dart = __esm({
  "libs/core/src/lib/npm-conf/nerf-dart.ts"() {
    "use strict";
    import_url = __toESM(require("url"));
  }
});

// libs/core/src/lib/npm-conf/config-chain/proto-list.ts
var require_proto_list = __commonJS({
  "libs/core/src/lib/npm-conf/config-chain/proto-list.ts"(exports2, module2) {
    "use strict";
    module2.exports = ProtoList;
    function setProto(obj, proto) {
      if (typeof Object.setPrototypeOf === "function")
        return Object.setPrototypeOf(obj, proto);
      else
        obj.__proto__ = proto;
    }
    function ProtoList() {
      this.list = [];
      var root = null;
      Object.defineProperty(this, "root", {
        get: function() {
          return root;
        },
        set: function(r) {
          root = r;
          if (this.list.length) {
            setProto(this.list[this.list.length - 1], r);
          }
        },
        enumerable: true,
        configurable: true
      });
    }
    ProtoList.prototype = {
      get length() {
        return this.list.length;
      },
      get keys() {
        var k = [];
        for (var i in this.list[0])
          k.push(i);
        return k;
      },
      get snapshot() {
        var o2 = {};
        this.keys.forEach(function(k) {
          o2[k] = this.get(k);
        }, this);
        return o2;
      },
      get store() {
        return this.list[0];
      },
      push: function(obj) {
        if (typeof obj !== "object")
          obj = { valueOf: obj };
        if (this.list.length >= 1) {
          setProto(this.list[this.list.length - 1], obj);
        }
        setProto(obj, this.root);
        return this.list.push(obj);
      },
      pop: function() {
        if (this.list.length >= 2) {
          setProto(this.list[this.list.length - 2], this.root);
        }
        return this.list.pop();
      },
      unshift: function(obj) {
        setProto(obj, this.list[0] || this.root);
        return this.list.unshift(obj);
      },
      shift: function() {
        if (this.list.length === 1) {
          setProto(this.list[0], this.root);
        }
        return this.list.shift();
      },
      get: function(key) {
        return this.list[0][key];
      },
      set: function(key, val, save) {
        if (!this.length)
          this.push({});
        if (save && this.list[0].hasOwnProperty(key))
          this.push({});
        return this.list[0][key] = val;
      },
      forEach: function(fn, thisp) {
        for (var key in this.list[0])
          fn.call(thisp, key, this.list[0][key]);
      },
      slice: function() {
        return this.list.slice.apply(this.list, arguments);
      },
      splice: function() {
        var ret = this.list.splice.apply(this.list, arguments);
        for (var i = 0, l = this.list.length; i < l; i++) {
          setProto(this.list[i], this.list[i + 1] || this.root);
        }
        return ret;
      }
    };
  }
});

// libs/core/src/lib/npm-conf/config-chain/index.ts
var require_config_chain = __commonJS({
  "libs/core/src/lib/npm-conf/config-chain/index.ts"(exports2, module2) {
    "use strict";
    var ProtoList = require_proto_list();
    var path19 = require("path");
    var fs15 = require("fs");
    var ini = require("ini");
    var EE = require("events").EventEmitter;
    var url2 = require("url");
    var http = require("http");
    var exports2 = module2.exports = function() {
      var args = [].slice.call(arguments), conf = new ConfigChain2();
      while (args.length) {
        var a = args.shift();
        if (a)
          conf.push("string" === typeof a ? json(a) : a);
      }
      return conf;
    };
    var find2 = exports2.find = function() {
      var rel = path19.join.apply(null, [].slice.call(arguments));
      function find3(start, rel2) {
        var file = path19.join(start, rel2);
        try {
          fs15.statSync(file);
          return file;
        } catch (err) {
          if (path19.dirname(start) !== start)
            return find3(path19.dirname(start), rel2);
        }
      }
      return find3(__dirname, rel);
    };
    var parse2 = exports2.parse = function(content, file, type) {
      content = "" + content;
      if (!type) {
        try {
          return JSON.parse(content);
        } catch (er) {
          return ini.parse(content);
        }
      } else if (type === "json") {
        if (this.emit) {
          try {
            return JSON.parse(content);
          } catch (er) {
            this.emit("error", er);
          }
        } else {
          return JSON.parse(content);
        }
      } else {
        return ini.parse(content);
      }
    };
    var json = exports2.json = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      var file = path19.join.apply(null, args);
      var content;
      try {
        content = fs15.readFileSync(file, "utf-8");
      } catch (err) {
        return;
      }
      return parse2(content, file, "json");
    };
    var env = exports2.env = function(prefix, env2) {
      env2 = env2 || process.env;
      var obj = {};
      var l = prefix.length;
      for (var k in env2) {
        if (k.indexOf(prefix) === 0)
          obj[k.substring(l)] = env2[k];
      }
      return obj;
    };
    exports2.ConfigChain = ConfigChain2;
    function ConfigChain2() {
      EE.apply(this);
      ProtoList.apply(this, arguments);
      this._awaiting = 0;
      this._saving = 0;
      this.sources = {};
    }
    var extras = {
      constructor: { value: ConfigChain2 }
    };
    Object.keys(EE.prototype).forEach(function(k) {
      extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k);
    });
    ConfigChain2.prototype = Object.create(ProtoList.prototype, extras);
    ConfigChain2.prototype.del = function(key, where) {
      if (where) {
        var target = this.sources[where];
        target = target && target.data;
        if (!target) {
          return this.emit("error", new Error("not found " + where));
        }
        delete target[key];
      } else {
        for (var i = 0, l = this.list.length; i < l; i++) {
          delete this.list[i][key];
        }
      }
      return this;
    };
    ConfigChain2.prototype.set = function(key, value, where) {
      var target;
      if (where) {
        target = this.sources[where];
        target = target && target.data;
        if (!target) {
          return this.emit("error", new Error("not found " + where));
        }
      } else {
        target = this.list[0];
        if (!target) {
          return this.emit("error", new Error("cannot set, no confs!"));
        }
      }
      target[key] = value;
      return this;
    };
    ConfigChain2.prototype.get = function(key, where) {
      if (where) {
        where = this.sources[where];
        if (where)
          where = where.data;
        if (where && Object.hasOwnProperty.call(where, key))
          return where[key];
        return void 0;
      }
      return this.list[0][key];
    };
    ConfigChain2.prototype.save = function(where, type, cb) {
      if (typeof type === "function")
        cb = type, type = null;
      var target = this.sources[where];
      if (!target || !(target.path || target.source) || !target.data) {
        return this.emit("error", new Error("bad save target: " + where));
      }
      if (target.source) {
        var pref = target.prefix || "";
        Object.keys(target.data).forEach(function(k) {
          target.source[pref + k] = target.data[k];
        });
        return this;
      }
      var type = type || target.type;
      var data = target.data;
      if (target.type === "json") {
        data = JSON.stringify(data);
      } else {
        data = ini.stringify(data);
      }
      this._saving++;
      fs15.writeFile(
        target.path,
        data,
        "utf8",
        function(er) {
          this._saving--;
          if (er) {
            if (cb)
              return cb(er);
            else
              return this.emit("error", er);
          }
          if (this._saving === 0) {
            if (cb)
              cb();
            this.emit("save");
          }
        }.bind(this)
      );
      return this;
    };
    ConfigChain2.prototype.addFile = function(file, type, name) {
      name = name || file;
      var marker = { __source__: name };
      this.sources[name] = { path: file, type };
      this.push(marker);
      this._await();
      fs15.readFile(
        file,
        "utf8",
        function(er, data) {
          if (er)
            this.emit("error", er);
          this.addString(data, file, type, marker);
        }.bind(this)
      );
      return this;
    };
    ConfigChain2.prototype.addEnv = function(prefix, env2, name) {
      name = name || "env";
      var data = exports2.env(prefix, env2);
      this.sources[name] = { data, source: env2, prefix };
      return this.add(data, name);
    };
    ConfigChain2.prototype.addUrl = function(req, type, name) {
      this._await();
      var href = url2.format(req);
      name = name || href;
      var marker = { __source__: name };
      this.sources[name] = { href, type };
      this.push(marker);
      http.request(
        req,
        function(res) {
          var c = [];
          var ct = res.headers["content-type"];
          if (!type) {
            type = ct.indexOf("json") !== -1 ? "json" : ct.indexOf("ini") !== -1 ? "ini" : href.match(/\.json$/) ? "json" : href.match(/\.ini$/) ? "ini" : null;
            marker.type = type;
          }
          res.on("data", c.push.bind(c)).on(
            "end",
            function() {
              this.addString(Buffer.concat(c), href, type, marker);
            }.bind(this)
          ).on("error", this.emit.bind(this, "error"));
        }.bind(this)
      ).on("error", this.emit.bind(this, "error")).end();
      return this;
    };
    ConfigChain2.prototype.addString = function(data, file, type, marker) {
      data = this.parse(data, file, type);
      this.add(data, marker);
      return this;
    };
    ConfigChain2.prototype.add = function(data, marker) {
      if (marker && typeof marker === "object") {
        var i = this.list.indexOf(marker);
        if (i === -1) {
          return this.emit("error", new Error("bad marker"));
        }
        this.splice(i, 1, data);
        marker = marker.__source__;
        this.sources[marker] = this.sources[marker] || {};
        this.sources[marker].data = data;
        this._resolve();
      } else {
        if (typeof marker === "string") {
          this.sources[marker] = this.sources[marker] || {};
          this.sources[marker].data = data;
        }
        this._await();
        this.push(data);
        process.nextTick(this._resolve.bind(this));
      }
      return this;
    };
    ConfigChain2.prototype.parse = exports2.parse;
    ConfigChain2.prototype._await = function() {
      this._awaiting++;
    };
    ConfigChain2.prototype._resolve = function() {
      this._awaiting--;
      if (this._awaiting === 0)
        this.emit("load", this);
    };
  }
});

// libs/core/src/lib/npm-conf/conf.ts
var import_assert, import_fs4, import_path12, ConfigChain, Conf;
var init_conf = __esm({
  "libs/core/src/lib/npm-conf/conf.ts"() {
    "use strict";
    import_assert = __toESM(require("assert"));
    import_fs4 = __toESM(require("fs"));
    import_path12 = __toESM(require("path"));
    init_env_replace();
    init_find_prefix();
    init_parse_field();
    init_nerf_dart();
    ({ ConfigChain } = require_config_chain());
    Conf = class extends ConfigChain {
      // https://github.com/npm/npm/blob/latest/lib/config/core.js#L208-L222
      constructor(base) {
        super(base);
        this.root = base;
      }
      // https://github.com/npm/npm/blob/latest/lib/config/core.js#L332-L342
      add(data, marker) {
        try {
          for (const x of Object.keys(data)) {
            const newKey = envReplace(x);
            const newField = parseField(data[x], newKey);
            delete data[x];
            data[newKey] = newField;
          }
        } catch (err) {
          throw err;
        }
        return super.add(data, marker);
      }
      // https://github.com/npm/npm/blob/latest/lib/config/core.js#L312-L325
      addFile(file, name = file) {
        const marker = { __source__: name };
        this["sources"][name] = { path: file, type: "ini" };
        this["push"](marker);
        this["_await"]();
        try {
          const contents = import_fs4.default.readFileSync(file, "utf8");
          this["addString"](contents, file, "ini", marker);
        } catch (err) {
          this["add"]({}, marker);
        }
        return this;
      }
      // https://github.com/npm/npm/blob/latest/lib/config/core.js#L344-L360
      addEnv(env = process.env) {
        const conf = {};
        Object.keys(env).filter((x) => /^npm_config_/i.test(x)).forEach((x) => {
          if (!env[x]) {
            return;
          }
          const p = x.toLowerCase().replace(/^npm_config_/, "").replace(/(?!^)_/g, "-");
          conf[p] = env[x];
        });
        return super.addEnv("", conf, "env");
      }
      // https://github.com/npm/npm/blob/latest/lib/config/load-prefix.js
      loadPrefix() {
        const cli = this["list"][0];
        Object.defineProperty(this, "prefix", {
          enumerable: true,
          set: (prefix) => {
            const g = this["get"]("global");
            this[g ? "globalPrefix" : "localPrefix"] = prefix;
          },
          get: () => {
            const g = this["get"]("global");
            return g ? this["globalPrefix"] : this["localPrefix"];
          }
        });
        Object.defineProperty(this, "globalPrefix", {
          enumerable: true,
          set: (prefix) => {
            this["set"]("prefix", prefix);
          },
          get: () => import_path12.default.resolve(this["get"]("prefix"))
        });
        let p;
        Object.defineProperty(this, "localPrefix", {
          enumerable: true,
          set: (prefix) => {
            p = prefix;
          },
          get: () => p
        });
        if (Object.prototype.hasOwnProperty.call(cli, "prefix")) {
          p = import_path12.default.resolve(cli.prefix);
        } else {
          try {
            p = findPrefix(process.cwd());
          } catch (err) {
            throw err;
          }
        }
        return p;
      }
      // https://github.com/npm/npm/blob/latest/lib/config/load-cafile.js
      loadCAFile(file) {
        if (!file) {
          return;
        }
        try {
          const contents = import_fs4.default.readFileSync(file, "utf8");
          const delim = "-----END CERTIFICATE-----";
          const output2 = contents.split(delim).filter((x) => Boolean(x.trim())).map((x) => x.trimLeft() + delim);
          this["set"]("ca", output2);
        } catch (err) {
          if (err.code === "ENOENT") {
            return;
          }
          throw err;
        }
      }
      // https://github.com/npm/npm/blob/latest/lib/config/set-user.js
      loadUser() {
        const defConf = this.root;
        if (this["get"]("global")) {
          return;
        }
        if (process.env["SUDO_UID"]) {
          defConf.user = Number(process.env["SUDO_UID"]);
          return;
        }
        const prefix = import_path12.default.resolve(this["get"]("prefix"));
        try {
          const stats = import_fs4.default.statSync(prefix);
          defConf.user = stats.uid;
        } catch (err) {
          if (err.code === "ENOENT") {
            return;
          }
          throw err;
        }
      }
      // https://github.com/npm/npm/blob/24ec9f2/lib/config/get-credentials-by-uri.js
      getCredentialsByURI(uri) {
        (0, import_assert.default)(uri && typeof uri === "string", "registry URL is required");
        const nerfed = toNerfDart(uri);
        const defnerf = toNerfDart(this["get"]("registry"));
        const c = {
          scope: nerfed,
          token: void 0,
          password: void 0,
          username: void 0,
          email: void 0,
          auth: void 0,
          alwaysAuth: void 0
        };
        if (this["get"](`${nerfed}:always-auth`) !== void 0) {
          const val = this["get"](`${nerfed}:always-auth`);
          c.alwaysAuth = val === "false" ? false : !!val;
        } else if (this["get"]("always-auth") !== void 0) {
          c.alwaysAuth = this["get"]("always-auth");
        }
        if (this["get"](`${nerfed}:_authToken`)) {
          c.token = this["get"](`${nerfed}:_authToken`);
          return c;
        }
        let authDef = this["get"]("_auth");
        let userDef = this["get"]("username");
        let passDef = this["get"]("_password");
        if (authDef && !(userDef && passDef)) {
          authDef = Buffer.from(authDef, "base64").toString();
          authDef = authDef.split(":");
          userDef = authDef.shift();
          passDef = authDef.join(":");
        }
        if (this["get"](`${nerfed}:_password`)) {
          c.password = Buffer.from(this["get"](`${nerfed}:_password`), "base64").toString("utf8");
        } else if (nerfed === defnerf && passDef) {
          c.password = passDef;
        }
        if (this["get"](`${nerfed}:username`)) {
          c.username = this["get"](`${nerfed}:username`);
        } else if (nerfed === defnerf && userDef) {
          c.username = userDef;
        }
        if (this["get"](`${nerfed}:email`)) {
          c.email = this["get"](`${nerfed}:email`);
        } else if (this["get"]("email")) {
          c.email = this["get"]("email");
        }
        if (c.username && c.password) {
          c.auth = Buffer.from(`${c.username}:${c.password}`).toString("base64");
        }
        return c;
      }
      // https://github.com/npm/npm/blob/24ec9f2/lib/config/set-credentials-by-uri.js
      setCredentialsByURI(uri, c) {
        (0, import_assert.default)(uri && typeof uri === "string", "registry URL is required");
        (0, import_assert.default)(c && typeof c === "object", "credentials are required");
        const nerfed = toNerfDart(uri);
        if (c.token) {
          this["set"](`${nerfed}:_authToken`, c.token, "user");
          this["del"](`${nerfed}:_password`, "user");
          this["del"](`${nerfed}:username`, "user");
          this["del"](`${nerfed}:email`, "user");
          this["del"](`${nerfed}:always-auth`, "user");
        } else if (c.username || c.password || c.email) {
          (0, import_assert.default)(c.username, "must include username");
          (0, import_assert.default)(c.password, "must include password");
          (0, import_assert.default)(c.email, "must include email address");
          this["del"](`${nerfed}:_authToken`, "user");
          const encoded = Buffer.from(c.password, "utf8").toString("base64");
          this["set"](`${nerfed}:_password`, encoded, "user");
          this["set"](`${nerfed}:username`, c.username, "user");
          this["set"](`${nerfed}:email`, c.email, "user");
          if (c.alwaysAuth !== void 0) {
            this["set"](`${nerfed}:always-auth`, c.alwaysAuth, "user");
          } else {
            this["del"](`${nerfed}:always-auth`, "user");
          }
        } else {
          throw new Error("No credentials to set.");
        }
      }
    };
  }
});

// libs/core/src/lib/get-npm-exec-opts.ts
function getNpmExecOpts(pkg, registry) {
  const env = {
    LERNA_PACKAGE_NAME: pkg.name
  };
  if (registry) {
    env.npm_config_registry = registry;
  }
  import_npmlog21.default.silly("getNpmExecOpts", pkg.location, registry);
  return {
    cwd: pkg.location,
    env,
    pkg
  };
}
var import_npmlog21;
var init_get_npm_exec_opts = __esm({
  "libs/core/src/lib/get-npm-exec-opts.ts"() {
    "use strict";
    import_npmlog21 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/npm-install.ts
function npmInstall(pkg, { registry, npmClient, npmClientArgs, npmGlobalStyle, mutex, stdio = "pipe", subCommand = "install" }) {
  const opts = getNpmExecOpts(pkg, registry);
  const args = [subCommand];
  let cmd = npmClient || "npm";
  if (npmGlobalStyle) {
    cmd = "npm";
    args.push("--global-style");
  }
  if (cmd === "yarn" && mutex) {
    args.push("--mutex", mutex);
  }
  if (cmd === "yarn") {
    args.push("--non-interactive");
  }
  if (npmClientArgs && npmClientArgs.length) {
    args.push(...npmClientArgs);
  }
  opts.stdio = stdio;
  opts.env.LERNA_EXEC_PATH = pkg.location;
  opts.env.LERNA_ROOT_PATH = pkg.rootPath;
  import_npmlog22.default.silly("npmInstall", [cmd, args]);
  return childProcess8.exec(cmd, args, opts);
}
function npmInstallDependencies(pkg, dependencies, config) {
  import_npmlog22.default.silly("npmInstallDependencies", pkg.name, dependencies);
  if (!(dependencies && dependencies.length)) {
    import_npmlog22.default.verbose("npmInstallDependencies", "no dependencies to install");
    return Promise.resolve();
  }
  const packageJsonBkp = `${pkg.manifestLocation}.lerna_backup`;
  import_npmlog22.default.silly("npmInstallDependencies", "backup", pkg.manifestLocation);
  return import_fs_extra4.default.copy(pkg.manifestLocation, packageJsonBkp).then(() => {
    const cleanup = () => {
      import_npmlog22.default.silly("npmInstallDependencies", "cleanup", pkg.manifestLocation);
      import_fs_extra4.default.renameSync(packageJsonBkp, pkg.manifestLocation);
    };
    const unregister = (0, import_signal_exit.default)(cleanup);
    const done = (finalError) => {
      cleanup();
      unregister();
      if (finalError) {
        throw finalError;
      }
    };
    const tempJson = transformManifest(pkg, dependencies);
    import_npmlog22.default.silly("npmInstallDependencies", "writing tempJson", tempJson);
    return (0, import_write_pkg2.default)(pkg.manifestLocation, tempJson).then(() => npmInstall(pkg, config)).then(() => done(), done);
  });
}
function transformManifest(pkg, dependencies) {
  const json = pkg.toJSON();
  const depMap = new Map(
    dependencies.map((dep) => {
      const { name, rawSpec } = (0, import_npm_package_arg4.default)(dep, pkg.location);
      return [name, rawSpec || "*"];
    })
  );
  delete json.scripts;
  ["dependencies", "devDependencies", "optionalDependencies"].forEach((depType) => {
    const collection = json[depType];
    if (collection) {
      Object.keys(collection).forEach((depName) => {
        if (depMap.has(depName)) {
          collection[depName] = depMap.get(depName);
          depMap.delete(depName);
        } else {
          delete collection[depName];
        }
      });
    }
  });
  ["bundledDependencies", "bundleDependencies"].forEach((depType) => {
    const collection = json[depType];
    if (Array.isArray(collection)) {
      const newCollection = [];
      for (const depName of collection) {
        if (depMap.has(depName)) {
          newCollection.push(depName);
          depMap.delete(depName);
        }
      }
      json[depType] = newCollection;
    }
  });
  if (depMap.size) {
    if (!json.dependencies) {
      json.dependencies = {};
    }
    depMap.forEach((depVersion, depName) => {
      json.dependencies[depName] = depVersion;
    });
  }
  return json;
}
var import_fs_extra4, import_npm_package_arg4, import_npmlog22, import_signal_exit, import_write_pkg2, childProcess8;
var init_npm_install = __esm({
  "libs/core/src/lib/npm-install.ts"() {
    "use strict";
    import_fs_extra4 = __toESM(require("fs-extra"));
    import_npm_package_arg4 = __toESM(require("npm-package-arg"));
    import_npmlog22 = __toESM(require("npmlog"));
    import_signal_exit = __toESM(require("signal-exit"));
    import_write_pkg2 = __toESM(require("write-pkg"));
    init_get_npm_exec_opts();
    childProcess8 = (init_src(), __toCommonJS(src_exports));
    module.exports.npmInstallDependencies = npmInstallDependencies;
  }
});

// libs/core/src/lib/prompt.ts
function promptConfirmation(message) {
  import_npmlog23.default.pause();
  return import_inquirer.default.prompt([
    {
      type: "expand",
      name: "confirm",
      message,
      default: 2,
      // default to help in order to avoid clicking straight through
      choices: [
        { key: "y", name: "Yes", value: true },
        { key: "n", name: "No", value: false }
      ]
    }
  ]).then((answers) => {
    import_npmlog23.default.resume();
    return answers["confirm"];
  });
}
function promptSelectOne(message, { choices, filter, validate } = {}) {
  import_npmlog23.default.pause();
  return import_inquirer.default.prompt([
    {
      type: "list",
      name: "prompt",
      message,
      choices,
      pageSize: choices?.length,
      filter,
      validate
    }
  ]).then((answers) => {
    import_npmlog23.default.resume();
    return answers["prompt"];
  });
}
function promptTextInput(message, { filter, validate } = {}) {
  import_npmlog23.default.pause();
  return import_inquirer.default.prompt([
    {
      type: "input",
      name: "input",
      message,
      filter,
      validate
    }
  ]).then((answers) => {
    import_npmlog23.default.resume();
    return answers["input"];
  });
}
var import_inquirer, import_npmlog23;
var init_prompt = __esm({
  "libs/core/src/lib/prompt.ts"() {
    "use strict";
    import_inquirer = __toESM(require("inquirer"));
    import_npmlog23 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/otplease.ts
function otplease(fn, _opts, otpCache) {
  const opts = { ...otpCache, ..._opts };
  return attempt(fn, opts, otpCache);
}
function attempt(fn, opts, otpCache) {
  return new Promise((resolve3) => {
    resolve3(fn(opts));
  }).catch((err) => {
    if (err.code !== "EOTP" && !(err.code === "E401" && /one-time pass/.test(err.body))) {
      throw err;
    } else if (!process.stdin.isTTY || !process.stdout.isTTY) {
      throw err;
    } else {
      if (otpCache != null && otpCache.otp != null && otpCache.otp !== opts["otp"]) {
        return attempt(fn, { ...opts, ...otpCache }, otpCache);
      }
      return semaphore.wait().then(() => {
        if (otpCache != null && otpCache.otp != null && otpCache.otp !== opts["otp"]) {
          semaphore.release();
          return attempt(fn, { ...opts, ...otpCache }, otpCache);
        }
        return getOneTimePassword().then(
          (otp) => {
            if (otpCache != null) {
              otpCache.otp = otp;
            }
            semaphore.release();
            return otp;
          },
          (promptError) => {
            semaphore.release();
            return Promise.reject(promptError);
          }
        ).then((otp) => {
          return fn({ ...opts, otp });
        });
      });
    }
  });
}
function getOneTimePassword(message = "This operation requires a one-time password:") {
  return promptTextInput(message, {
    filter: (otp) => otp.replace(/\s+/g, ""),
    validate: (otp) => otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp) || "Must be a valid one-time-password. See https://docs.npmjs.com/getting-started/using-two-factor-authentication"
  });
}
var semaphore;
var init_otplease = __esm({
  "libs/core/src/lib/otplease.ts"() {
    "use strict";
    init_prompt();
    semaphore = {
      _promise: void 0,
      _resolve: void 0,
      wait() {
        return new Promise((resolve3) => {
          if (!this._promise) {
            this._promise = new Promise((release) => {
              this._resolve = release;
            });
            resolve3(void 0);
          } else {
            resolve3(this._promise.then(() => this.wait()));
          }
        });
      },
      release() {
        const resolve3 = this._resolve;
        if (resolve3) {
          this._resolve = void 0;
          this._promise = void 0;
          resolve3();
        }
      }
    };
  }
});

// libs/core/src/lib/npm-conf/defaults.ts
var require_defaults = __commonJS({
  "libs/core/src/lib/npm-conf/defaults.ts"(exports2) {
    "use strict";
    var import_os5 = __toESM(require("os"));
    var import_path22 = __toESM(require("path"));
    var temp = import_os5.default.tmpdir();
    var uidOrPid = process.getuid ? process.getuid() : process.pid;
    var hasUnicode2 = () => true;
    var isWindows = process.platform === "win32";
    var osenv = {
      editor: () => process.env["EDITOR"] || process.env["VISUAL"] || (isWindows ? "notepad.exe" : "vi"),
      shell: () => isWindows ? process.env["COMSPEC"] || "cmd.exe" : process.env["SHELL"] || "/bin/bash"
    };
    var umask = {
      fromString: () => process.umask()
    };
    var home = import_os5.default.homedir();
    if (home) {
      process.env["HOME"] = home;
    } else {
      home = import_path22.default.resolve(temp, `npm-${uidOrPid}`);
    }
    var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
    var cacheRoot = process.platform === "win32" && process.env["APPDATA"] || home;
    var cache = import_path22.default.resolve(cacheRoot, cacheExtra);
    var defaults;
    var globalPrefix;
    Object.defineProperty(exports2, "defaults", {
      get() {
        if (defaults) {
          return defaults;
        }
        if (process.env["PREFIX"]) {
          globalPrefix = process.env["PREFIX"];
        } else if (process.platform === "win32") {
          globalPrefix = import_path22.default.dirname(process.execPath);
        } else {
          globalPrefix = import_path22.default.dirname(import_path22.default.dirname(process.execPath));
          if (process.env["DESTDIR"]) {
            globalPrefix = import_path22.default.join(process.env["DESTDIR"], globalPrefix);
          }
        }
        defaults = {
          access: null,
          "allow-same-version": false,
          "always-auth": false,
          also: null,
          audit: true,
          "audit-level": "low",
          "auth-type": "legacy",
          "bin-links": true,
          browser: null,
          ca: null,
          cafile: null,
          cache,
          "cache-lock-stale": 6e4,
          "cache-lock-retries": 10,
          "cache-lock-wait": 1e4,
          "cache-max": Infinity,
          "cache-min": 10,
          cert: null,
          cidr: null,
          color: process.env["NO_COLOR"] == null,
          depth: Infinity,
          description: true,
          dev: false,
          "dry-run": false,
          editor: osenv.editor(),
          "engine-strict": false,
          force: false,
          "fetch-retries": 2,
          "fetch-retry-factor": 10,
          "fetch-retry-mintimeout": 1e4,
          "fetch-retry-maxtimeout": 6e4,
          git: "git",
          "git-tag-version": true,
          "commit-hooks": true,
          global: false,
          globalconfig: import_path22.default.resolve(globalPrefix, "etc", "npmrc"),
          "global-style": false,
          group: process.platform === "win32" ? 0 : process.env["SUDO_GID"] || process.getgid && process.getgid(),
          "ham-it-up": false,
          heading: "npm",
          "if-present": false,
          "ignore-prepublish": false,
          "ignore-scripts": false,
          "init-module": import_path22.default.resolve(home, ".npm-init.js"),
          "init-author-name": "",
          "init-author-email": "",
          "init-author-url": "",
          "init-version": "1.0.0",
          "init-license": "ISC",
          json: false,
          key: null,
          "legacy-bundling": false,
          link: false,
          "local-address": void 0,
          loglevel: "notice",
          logstream: process.stderr,
          "logs-max": 10,
          long: false,
          maxsockets: 50,
          message: "%s",
          "metrics-registry": null,
          "node-options": null,
          "node-version": process.version,
          offline: false,
          "onload-script": false,
          only: null,
          optional: true,
          otp: void 0,
          "package-lock": true,
          "package-lock-only": false,
          parseable: false,
          "prefer-offline": false,
          "prefer-online": false,
          prefix: globalPrefix,
          preid: "",
          production: process.env["NODE_ENV"] === "production",
          progress: !process.env["TRAVIS"] && !process.env["CI"],
          proxy: null,
          "https-proxy": null,
          noproxy: null,
          "user-agent": "npm/{npm-version} node/{node-version} {platform} {arch}",
          "read-only": false,
          "rebuild-bundle": true,
          registry: "https://registry.npmjs.org/",
          rollback: true,
          save: true,
          "save-bundle": false,
          "save-dev": false,
          "save-exact": false,
          "save-optional": false,
          "save-prefix": "^",
          "save-prod": false,
          scope: "",
          "script-shell": void 0,
          "scripts-prepend-node-path": "warn-only",
          searchopts: "",
          searchexclude: null,
          searchlimit: 20,
          searchstaleness: 15 * 60,
          "send-metrics": false,
          shell: osenv.shell(),
          shrinkwrap: true,
          "sign-git-commit": false,
          "sign-git-tag": false,
          "sso-poll-frequency": 500,
          "sso-type": "oauth",
          "strict-ssl": true,
          tag: "latest",
          "tag-version-prefix": "v",
          timing: false,
          tmp: temp,
          unicode: hasUnicode2(),
          "unsafe-perm": process.platform === "win32" || process.platform === "cygwin" || // TODO: refactor based on TS feedback
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          !(process.getuid && process.setuid && process.getgid && process.setgid) || process.getuid() !== 0,
          "update-notifier": true,
          usage: false,
          user: process.platform === "win32" || import_os5.default.type() === "OS400" ? 0 : "nobody",
          userconfig: import_path22.default.resolve(home, ".npmrc"),
          // TODO: refactor based on TS feedback
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          umask: process.umask ? process.umask() : umask.fromString("022"),
          version: false,
          versions: false,
          viewer: process.platform === "win32" ? "browser" : "man",
          _exit: true
        };
        return defaults;
      }
    });
  }
});

// libs/core/src/lib/npm-conf/index.ts
var require_npm_conf = __commonJS({
  "libs/core/src/lib/npm-conf/index.ts"(exports2, module2) {
    "use strict";
    var import_path22 = __toESM(require("path"));
    init_conf();
    init_nerf_dart();
    var { defaults } = require_defaults();
    module2.exports = npmConf3;
    module2.exports.Conf = Conf;
    module2.exports.defaults = Object.assign({}, defaults);
    module2.exports.toNerfDart = toNerfDart;
    function npmConf3(opts) {
      const conf = new Conf(Object.assign({}, defaults));
      const cleanOpts = opts ? Object.keys(opts).reduce((acc, key) => {
        if (opts[key] !== void 0) {
          acc[key] = opts[key];
        }
        return acc;
      }, {}) : {};
      conf.add(cleanOpts, "cli");
      conf.addEnv();
      conf.loadPrefix();
      const projectConf = import_path22.default.resolve(conf["localPrefix"], ".npmrc");
      const userConf = conf["get"]("userconfig");
      if (!conf["get"]("global") && projectConf !== userConf) {
        conf.addFile(projectConf, "project");
      } else {
        conf.add({}, "project");
      }
      conf.addFile(conf["get"]("userconfig"), "user");
      if (conf["get"]("prefix")) {
        const etc = import_path22.default.resolve(conf["get"]("prefix"), "etc");
        conf.root.globalconfig = import_path22.default.resolve(etc, "npmrc");
        conf.root.globalignorefile = import_path22.default.resolve(etc, "npmignore");
      }
      conf.addFile(conf["get"]("globalconfig"), "global");
      conf.loadUser();
      const caFile = conf["get"]("cafile");
      if (caFile) {
        conf.loadCAFile(caFile);
      }
      return conf;
    }
  }
});

// libs/core/src/lib/run-lifecycle.ts
function flattenOptions(obj) {
  return {
    ignorePrepublish: obj["ignore-prepublish"],
    ignoreScripts: obj["ignore-scripts"],
    nodeOptions: obj["node-options"],
    scriptShell: obj["script-shell"],
    scriptsPrependNodePath: obj["scripts-prepend-node-path"],
    unsafePerm: obj["unsafe-perm"],
    ...obj
  };
}
function printCommandBanner(id, event, cmd, path19) {
  return console.log(`
> ${id ? `${id} ` : ""}${event} ${path19}
> ${cmd.trim().replace(/\n/g, "\n> ")}
`);
}
function runLifecycle(pkg, stage, options) {
  if ("root" in options) {
    options = options.snapshot;
  }
  const opts = {
    log: import_npmlog24.default,
    unsafePerm: true,
    ...flattenOptions(options)
  };
  const dir = pkg.location;
  const id = `${pkg.name}@${pkg.version}`;
  const config = {};
  if (opts.ignoreScripts) {
    opts.log.verbose("lifecycle", "%j ignored in %j", stage, pkg.name);
    return Promise.resolve();
  }
  if (!pkg.scripts || !pkg.scripts[stage]) {
    opts.log.silly("lifecycle", "No script for %j in %j, continuing", stage, pkg.name);
    return Promise.resolve();
  }
  if (stage === "prepublish" && opts.ignorePrepublish) {
    opts.log.verbose("lifecycle", "%j ignored in %j", stage, pkg.name);
    return Promise.resolve();
  }
  for (const [key, val] of Object.entries(opts)) {
    if (val != null && key !== "log" && key !== "logstream") {
      config[key] = val;
    }
  }
  if (pkg.__isLernaPackage) {
    pkg = pkg.toJSON();
  }
  pkg._id = id;
  opts.log.silly("lifecycle", "%j starting in %j", stage, pkg.name);
  opts.log.info("lifecycle", `${id}~${stage}: ${id}`);
  const stdio = opts.stdio || "pipe";
  if (import_npmlog24.default.level !== "silent") {
    printCommandBanner(id, stage, pkg.scripts[stage], dir);
  }
  return queue.add(
    async () => runScript({
      event: stage,
      path: dir,
      pkg,
      args: [],
      stdio,
      banner: false,
      // TODO: refactor based on TS feedback
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      scriptShell: config.scriptShell
    }).then(
      ({ stdout }) => {
        if (stdout) {
          process.stdout.write(stdout.toString().trimEnd() + "\n");
        }
        opts.log.silly("lifecycle", "%j finished in %j", stage, pkg.name);
      },
      (err) => {
        const exitCode = err.code || 1;
        import_npmlog24.default.error("lifecycle", "%j errored in %j, exiting %d", stage, pkg.name, exitCode);
        err.name = "ValidationError";
        err.exitCode = exitCode;
        process.exitCode = exitCode;
        throw err;
      }
    )
  );
}
function createRunner(commandOptions) {
  const cfg = npmConf(commandOptions).snapshot;
  return (pkg, stage) => runLifecycle(pkg, stage, cfg);
}
var import_npmlog24, import_p_queue, runScript, npmConf, queue;
var init_run_lifecycle = __esm({
  "libs/core/src/lib/run-lifecycle.ts"() {
    "use strict";
    import_npmlog24 = __toESM(require("npmlog"));
    import_p_queue = __toESM(require("p-queue"));
    runScript = require("@npmcli/run-script");
    npmConf = require_npm_conf();
    queue = new import_p_queue.default({ concurrency: 1 });
  }
});

// libs/core/src/lib/npm-publish.ts
function flattenOptions2(obj) {
  return {
    // eslint-disable-next-line dot-notation -- (npm v7 compat)
    defaultTag: obj["tag"] || "latest",
    dryRun: obj["dry-run"],
    // libnpmpublish / npm-registry-fetch check strictSSL rather than strict-ssl
    strictSSL: obj["strict-ssl"],
    ...obj
  };
}
function npmPublish(pkg, tarFilePath, options = {}, otpCache) {
  const { dryRun, ...remainingOptions } = flattenOptions2(options);
  const { scope } = (0, import_npm_package_arg5.default)(pkg.name);
  const opts = {
    log: import_npmlog25.default,
    ...remainingOptions,
    projectScope: scope
  };
  opts.log.verbose("publish", pkg.name);
  let chain = Promise.resolve();
  if (!dryRun) {
    chain = chain.then(() => {
      let { manifestLocation } = pkg;
      if (pkg.contents !== pkg.location) {
        manifestLocation = import_path13.default.join(pkg.contents, "package.json");
      }
      return Promise.all([import_fs_extra5.default.readFile(tarFilePath), readJSONAsync(manifestLocation)]);
    });
    chain = chain.then(([tarData, manifest]) => {
      if (opts.defaultTag !== "latest" && manifest.publishConfig && manifest.publishConfig.tag && manifest.publishConfig.tag !== opts.defaultTag) {
        manifest.publishConfig.tag = opts.defaultTag;
      }
      if (manifest.publishConfig) {
        Object.assign(opts, publishConfigToOpts(manifest.publishConfig));
      }
      return otplease((innerOpts) => (0, import_libnpmpublish.publish)(manifest, tarData, innerOpts), opts, otpCache);
    });
  }
  chain = chain.then(() => runLifecycle(pkg, "publish", opts));
  chain = chain.then(() => runLifecycle(pkg, "postpublish", opts));
  return chain;
}
function publishConfigToOpts(publishConfig) {
  const opts = { ...publishConfig };
  if (publishConfig.tag) {
    opts.defaultTag = publishConfig.tag;
    delete opts.tag;
  }
  return opts;
}
var import_fs_extra5, import_libnpmpublish, import_npm_package_arg5, import_npmlog25, import_path13, import_pify2, readJSON, readJSONAsync;
var init_npm_publish = __esm({
  "libs/core/src/lib/npm-publish.ts"() {
    "use strict";
    import_fs_extra5 = __toESM(require("fs-extra"));
    import_libnpmpublish = require("libnpmpublish");
    import_npm_package_arg5 = __toESM(require("npm-package-arg"));
    import_npmlog25 = __toESM(require("npmlog"));
    import_path13 = __toESM(require("path"));
    import_pify2 = __toESM(require("pify"));
    init_otplease();
    init_run_lifecycle();
    readJSON = require("read-package-json");
    readJSONAsync = (0, import_pify2.default)(readJSON);
  }
});

// libs/core/src/lib/npm-run-script.ts
var import_npmlog26, childProcess9;
var init_npm_run_script = __esm({
  "libs/core/src/lib/npm-run-script.ts"() {
    "use strict";
    import_npmlog26 = __toESM(require("npmlog"));
    init_get_npm_exec_opts();
    childProcess9 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/output.ts
function output(...args) {
  import_npmlog27.default["clearProgress"]();
  console.log(...args);
  import_npmlog27.default["showProgress"]();
}
var import_npmlog27;
var init_output = __esm({
  "libs/core/src/lib/output.ts"() {
    "use strict";
    import_npmlog27 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/get-packed.ts
function getPacked(pkg, tarFilePath) {
  const bundledWanted = new Set(pkg.bundleDependencies || pkg.bundledDependencies || []);
  const bundled = /* @__PURE__ */ new Set();
  const files = [];
  let totalEntries = 0;
  let totalEntrySize = 0;
  return import_tar.default.list({
    file: tarFilePath,
    onentry(entry) {
      totalEntries += 1;
      totalEntrySize += entry.size;
      const p = entry.path;
      if (p.startsWith("package/node_modules/")) {
        const name = p.match(/^package\/node_modules\/((?:@[^/]+\/)?[^/]+)/)[1];
        if (bundledWanted.has(name)) {
          bundled.add(name);
        }
      } else {
        files.push({
          path: entry.path.replace(/^package\//, ""),
          size: entry.size,
          mode: entry.mode
        });
      }
    },
    strip: 1
  }).then(
    () => Promise.all([
      import_fs_extra6.default.stat(tarFilePath),
      import_ssri.default.fromStream(import_fs_extra6.default.createReadStream(tarFilePath), {
        algorithms: ["sha1", "sha512"]
      })
    ])
  ).then(([{ size }, { sha1, sha512 }]) => {
    const shasum = sha1[0].hexDigest();
    return {
      id: `${pkg.name}@${pkg.version}`,
      name: pkg.name,
      version: pkg.version,
      size,
      unpackedSize: totalEntrySize,
      shasum,
      integrity: import_ssri.default.parse(sha512[0]),
      filename: import_path14.default.basename(tarFilePath),
      files,
      entryCount: totalEntries,
      bundled: Array.from(bundled),
      tarFilePath
    };
  });
}
var import_fs_extra6, import_path14, import_ssri, import_tar;
var init_get_packed = __esm({
  "libs/core/src/lib/get-packed.ts"() {
    "use strict";
    import_fs_extra6 = __toESM(require("fs-extra"));
    import_path14 = __toESM(require("path"));
    import_ssri = __toESM(require("ssri"));
    import_tar = __toESM(require("tar"));
  }
});

// libs/core/src/lib/temp-write.ts
async function tempWrite(fileContent, filePath) {
  const tempPath = tempfile(filePath);
  const write = (0, import_is_stream.default)(fileContent) ? writeStream : writeFileP;
  await (0, import_make_dir.default)(import_path15.default.dirname(tempPath));
  await write(tempPath, fileContent);
  return tempPath;
}
var import_graceful_fs, import_is_stream, import_make_dir, import_path15, import_temp_dir, import_util, uuid, writeFileP, tempfile, writeStream, temp_write_default;
var init_temp_write = __esm({
  "libs/core/src/lib/temp-write.ts"() {
    "use strict";
    import_graceful_fs = __toESM(require("graceful-fs"));
    import_is_stream = __toESM(require("is-stream"));
    import_make_dir = __toESM(require("make-dir"));
    import_path15 = __toESM(require("path"));
    import_temp_dir = __toESM(require("temp-dir"));
    import_util = require("util");
    uuid = __toESM(require("uuid"));
    writeFileP = (0, import_util.promisify)(import_graceful_fs.default.writeFile);
    tempfile = (filePath) => import_path15.default.join(import_temp_dir.default, uuid.v4(), filePath || "");
    writeStream = async (filePath, fileContent) => new Promise((resolve3, reject) => {
      const writable = import_graceful_fs.default.createWriteStream(filePath);
      fileContent.on("error", (error) => {
        reject(error);
        fileContent.unpipe(writable);
        writable.end();
      }).pipe(writable).on("error", reject).on("finish", resolve3);
    });
    tempWrite.sync = (fileContent, filePath) => {
      const tempPath = tempfile(filePath);
      import_make_dir.default.sync(import_path15.default.dirname(tempPath));
      import_graceful_fs.default.writeFileSync(tempPath, fileContent);
      return tempPath;
    };
    temp_write_default = tempWrite;
  }
});

// libs/core/src/lib/pack-directory.ts
function packDirectory(_pkg, dir, options) {
  const pkg = Package.lazy(_pkg, dir);
  const opts = {
    log: import_npmlog28.default,
    ...options
  };
  opts.log.verbose("pack-directory", import_path16.default.relative(".", pkg.contents));
  let chain = Promise.resolve();
  if (opts.ignorePrepublish !== true) {
    chain = chain.then(() => runLifecycle(pkg, "prepublish", opts));
  }
  chain = chain.then(() => runLifecycle(pkg, "prepare", opts));
  if (opts.lernaCommand === "publish") {
    opts.stdio = "inherit";
    chain = chain.then(() => pkg.refresh());
    chain = chain.then(() => runLifecycle(pkg, "prepublishOnly", opts));
    chain = chain.then(() => pkg.refresh());
  }
  chain = chain.then(() => runLifecycle(pkg, "prepack", opts));
  chain = chain.then(() => pkg.refresh());
  chain = chain.then(() => (0, import_npm_packlist.default)({ path: pkg.contents }));
  chain = chain.then(
    (files) => import_tar2.default.create(
      {
        cwd: pkg.contents,
        prefix: "package/",
        portable: true,
        // Provide a specific date in the 1980s for the benefit of zip,
        // which is confounded by files dated at the Unix epoch 0.
        // TODO: refactor based on TS feedback
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        mtime: /* @__PURE__ */ new Date("1985-10-26T08:15:00.000Z"),
        gzip: true
      },
      // NOTE: node-tar does some Magic Stuff depending on prefixes for files
      //       specifically with @ signs, so we just neutralize that one
      //       and any such future "features" by prepending `./`
      // TODO: refactor based on TS feedback
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      files.map((f) => `./${f}`)
    )
  );
  chain = chain.then((stream) => temp_write_default(stream, getTarballName(pkg)));
  chain = chain.then(
    (tarFilePath) => getPacked(pkg, tarFilePath).then(
      (packed) => Promise.resolve().then(() => runLifecycle(pkg, "postpack", opts)).then(() => packed)
    )
  );
  return chain;
}
function getTarballName(pkg) {
  const name = pkg.name[0] === "@" ? (
    // scoped packages get special treatment
    pkg.name.substr(1).replace(/\//g, "-")
  ) : pkg.name;
  return `${name}-${pkg.version}.tgz`;
}
var import_npm_packlist, import_npmlog28, import_path16, import_tar2;
var init_pack_directory = __esm({
  "libs/core/src/lib/pack-directory.ts"() {
    "use strict";
    import_npm_packlist = __toESM(require("npm-packlist"));
    import_npmlog28 = __toESM(require("npmlog"));
    import_path16 = __toESM(require("path"));
    import_tar2 = __toESM(require("tar"));
    init_get_packed();
    init_package();
    init_run_lifecycle();
    init_temp_write();
  }
});

// libs/core/src/lib/profiler.ts
var import_fs_extra7, import_npmlog29, import_upath;
var init_profiler = __esm({
  "libs/core/src/lib/profiler.ts"() {
    "use strict";
    import_fs_extra7 = __toESM(require("fs-extra"));
    import_npmlog29 = __toESM(require("npmlog"));
    import_upath = __toESM(require("upath"));
  }
});

// libs/core/src/lib/pulse-till-done.ts
function pulseStart(prefix) {
  pulsers += 1;
  if (pulsers > 1) {
    return;
  }
  pulse = setInterval(() => import_npmlog30.default["gauge"].pulse(prefix), 150);
}
function pulseStop() {
  pulsers -= 1;
  if (pulsers > 0) {
    return;
  }
  clearInterval(pulse);
}
function pulseTillDone(prefix, promise) {
  if (!promise) {
    promise = prefix;
    prefix = "";
  }
  pulseStart(prefix);
  return Promise.resolve(promise).then(
    (val) => {
      pulseStop();
      return val;
    },
    (err) => {
      pulseStop();
      throw err;
    }
  );
}
var import_npmlog30, pulsers, pulse;
var init_pulse_till_done = __esm({
  "libs/core/src/lib/pulse-till-done.ts"() {
    "use strict";
    import_npmlog30 = __toESM(require("npmlog"));
    pulsers = 0;
  }
});

// libs/core/src/lib/rimraf-dir.ts
var import_npmlog31, import_rimraf;
var init_rimraf_dir = __esm({
  "libs/core/src/lib/rimraf-dir.ts"() {
    "use strict";
    import_npmlog31 = __toESM(require("npmlog"));
    import_rimraf = __toESM(require("rimraf"));
  }
});

// libs/core/src/lib/run-projects-topologically.ts
async function runProjectsTopologically(projects, projectGraph, runner, { concurrency, rejectCycles } = {}) {
  const queue2 = new import_p_queue2.default({ concurrency });
  const returnValues = [];
  const projectsMap = new Map(projects.map((p) => [p.name, p]));
  const localDependencies = projectGraph.localPackageDependencies;
  const flattenedLocalDependencies = (0, import_lodash6.flatten)(Object.values(localDependencies));
  const getProject = (name) => {
    const project = projectsMap.get(name);
    if (!project) {
      throw new Error(`Failed to find project ${name}. This is likely a bug in Lerna's toposort algorithm.`);
    }
    return project;
  };
  const dependenciesBySource = projects.reduce(
    (prev, next) => ({
      ...prev,
      [next.name]: /* @__PURE__ */ new Set()
    }),
    {}
  );
  flattenedLocalDependencies.forEach((dep) => {
    if (dependenciesBySource[dep.source] && projectsMap.has(dep.target)) {
      dependenciesBySource[dep.source].add(dep.target);
    }
  });
  const unmergedCycles = getCycles(dependenciesBySource);
  reportCycles(unmergedCycles, rejectCycles);
  const cycles = new Set(mergeOverlappingCycles(unmergedCycles));
  const seen = /* @__PURE__ */ new Set();
  const errors = [];
  const queueNextPackages = () => {
    if (seen.size === projects.length) {
      return;
    }
    let batch = Object.keys(dependenciesBySource).filter((p) => dependenciesBySource[p].size === 0).filter((p) => !seen.has(p));
    if (batch.length === 0) {
      const cycle = Array.from(cycles.values()).find((cycle2) => {
        const cycleHasExternalDependencies = cycle2.some((project) => {
          const projectDeps = dependenciesBySource[project];
          const depIsNotInCycle = (dep) => cycle2.indexOf(dep) === -1;
          return !!projectDeps && Array.from(projectDeps).filter(depIsNotInCycle).length > 0;
        });
        return !cycleHasExternalDependencies;
      });
      if (cycle) {
        cycles.delete(cycle);
        batch = cycle.filter((p) => projectsMap.has(p));
      }
    }
    batch.forEach((p) => {
      const project = getProject(p);
      seen.add(p);
      queue2.add(
        () => runner(project).then((value) => {
          returnValues.push(value);
          delete dependenciesBySource[p];
          Object.keys(dependenciesBySource).forEach((dep) => dependenciesBySource[dep].delete(p));
          queueNextPackages();
        })
      ).catch((err) => {
        errors.push(err);
      });
    });
  };
  queueNextPackages();
  await queue2.onIdle();
  if (errors.length) {
    throw errors[0];
  }
  if (seen.size !== projects.length) {
    throw new ValidationError("ERROR", "Not all tasks were run. This is likely a bug in Lerna.");
  }
  return returnValues;
}
var import_lodash6, import_p_queue2;
var init_run_projects_topologically = __esm({
  "libs/core/src/lib/run-projects-topologically.ts"() {
    "use strict";
    import_lodash6 = require("lodash");
    import_p_queue2 = __toESM(require("p-queue"));
    init_cycles();
    init_validation_error();
  }
});

// libs/core/src/lib/scm-clients/github/create-github-client.ts
function createGitHubClient() {
  import_npmlog32.default.silly("createGitHubClient");
  const { GH_TOKEN, GHE_API_URL, GHE_VERSION } = process.env;
  if (!GH_TOKEN) {
    throw new ValidationError(
      "",
      `A GH_TOKEN environment variable is required when "createRelease" is set to "github"`
    );
  }
  if (GHE_VERSION) {
    import_rest.Octokit.plugin(require(`@octokit/plugin-enterprise-rest/ghe-${GHE_VERSION}`));
  }
  const options = {
    auth: `token ${GH_TOKEN}`
  };
  if (GHE_API_URL) {
    options.baseUrl = GHE_API_URL;
  }
  return new import_rest.Octokit(options);
}
function parseGitRepo(remote = "origin", opts) {
  import_npmlog32.default.silly("parseGitRepo");
  const args = ["config", "--get", `remote.${remote}.url`];
  import_npmlog32.default.verbose("git", args);
  const url2 = childProcess10.execSync("git", args, opts);
  if (!url2) {
    throw new ValidationError("", `Git remote URL could not be found using "${remote}".`);
  }
  return (0, import_git_url_parse.default)(url2);
}
var import_rest, import_git_url_parse, import_npmlog32, childProcess10;
var init_create_github_client = __esm({
  "libs/core/src/lib/scm-clients/github/create-github-client.ts"() {
    "use strict";
    import_rest = require("@octokit/rest");
    import_git_url_parse = __toESM(require("git-url-parse"));
    import_npmlog32 = __toESM(require("npmlog"));
    init_validation_error();
    childProcess10 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/core/src/lib/scm-clients/gitlab/gitlab-client.ts
var import_node_fetch, import_npmlog33, import_path17, GitLabClient;
var init_gitlab_client = __esm({
  "libs/core/src/lib/scm-clients/gitlab/gitlab-client.ts"() {
    "use strict";
    import_node_fetch = __toESM(require("node-fetch"));
    import_npmlog33 = __toESM(require("npmlog"));
    import_path17 = __toESM(require("path"));
    GitLabClient = class {
      constructor(token, baseUrl = "https://gitlab.com/api/v4") {
        this.token = token;
        this.baseUrl = baseUrl;
      }
      // TODO: refactor based on TS feedback
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      createRelease({ owner, repo, name, tag_name: tagName, body }) {
        const releasesUrl = this.releasesUrl(owner, repo, "releases");
        import_npmlog33.default.silly("Requesting GitLab releases", releasesUrl);
        return (0, import_node_fetch.default)(releasesUrl, {
          method: "post",
          body: JSON.stringify({ name, tag_name: tagName, description: body }),
          headers: {
            "PRIVATE-TOKEN": this.token,
            "Content-Type": "application/json"
          }
        }).then(({ ok, status, statusText }) => {
          if (!ok) {
            import_npmlog33.default.error("gitlab", `Failed to create release
Request returned ${status} ${statusText}`);
          } else {
            import_npmlog33.default.silly("gitlab", "Created release successfully.");
          }
        });
      }
      releasesUrl(namespace, project) {
        return new URL(
          `${this.baseUrl}/${import_path17.default.join("projects", encodeURIComponent(`${namespace}/${project}`), "releases")}`
        ).toString();
      }
    };
  }
});

// libs/core/src/lib/scm-clients/gitlab/create-gitlab-client.ts
function OcktokitAdapter(client) {
  return { repos: { createRelease: client.createRelease.bind(client) } };
}
function createGitLabClient() {
  const { GL_API_URL, GL_TOKEN } = process.env;
  import_npmlog34.default.silly("Creating a GitLab client...");
  if (!GL_TOKEN) {
    throw new Error("A GL_TOKEN environment variable is required.");
  }
  const client = new GitLabClient(GL_TOKEN, GL_API_URL);
  return OcktokitAdapter(client);
}
var import_npmlog34;
var init_create_gitlab_client = __esm({
  "libs/core/src/lib/scm-clients/gitlab/create-gitlab-client.ts"() {
    "use strict";
    import_npmlog34 = __toESM(require("npmlog"));
    init_gitlab_client();
  }
});

// libs/core/src/lib/scm-clients/index.ts
var init_scm_clients = __esm({
  "libs/core/src/lib/scm-clients/index.ts"() {
    "use strict";
    init_create_github_client();
    init_create_gitlab_client();
  }
});

// libs/core/src/lib/timer.ts
var init_timer = __esm({
  "libs/core/src/lib/timer.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/npm-dist-tag.ts
var npm_dist_tag_exports = {};
__export(npm_dist_tag_exports, {
  add: () => add,
  list: () => list,
  remove: () => remove
});
function add(spec, tag, options, otpCache) {
  const opts = {
    log: import_npmlog35.default,
    ...options,
    spec: (0, import_npm_package_arg6.default)(spec)
  };
  const cleanTag = (tag || opts.defaultTag || opts.tag).trim();
  const { name, rawSpec: version } = opts.spec;
  opts.log.verbose("dist-tag", `adding "${cleanTag}" to ${name}@${version}`);
  if (opts.dryRun) {
    opts.log.silly("dist-tag", "dry-run configured, bailing now");
    return Promise.resolve();
  }
  return fetchTags(opts).then((tags) => {
    if (tags[cleanTag] === version) {
      opts.log.warn("dist-tag", `${name}@${cleanTag} already set to ${version}`);
      return tags;
    }
    const uri = `/-/package/${opts.spec.escapedName}/dist-tags/${encodeURIComponent(cleanTag)}`;
    const payload = {
      ...opts,
      method: "PUT",
      body: JSON.stringify(version),
      headers: {
        // cannot use fetch.json() due to HTTP 204 response,
        // so we manually set the required content-type
        "content-type": "application/json"
      },
      spec: opts.spec
    };
    return otplease((wrappedPayload) => (0, import_npm_registry_fetch.default)(uri, wrappedPayload), payload, otpCache).then(() => {
      opts.log.verbose("dist-tag", `added "${cleanTag}" to ${name}@${version}`);
      tags[cleanTag] = version;
      return tags;
    });
  });
}
function remove(spec, tag, options, otpCache) {
  const opts = {
    log: import_npmlog35.default,
    ...options,
    spec: (0, import_npm_package_arg6.default)(spec)
  };
  opts.log.verbose("dist-tag", `removing "${tag}" from ${opts.spec.name}`);
  if (opts.dryRun) {
    opts.log.silly("dist-tag", "dry-run configured, bailing now");
    return Promise.resolve();
  }
  return fetchTags(opts).then((tags) => {
    const version = tags[tag];
    if (!version) {
      opts.log.info("dist-tag", `"${tag}" is not a dist-tag on ${opts.spec.name}`);
      return tags;
    }
    const uri = `/-/package/${opts.spec.escapedName}/dist-tags/${encodeURIComponent(tag)}`;
    const payload = {
      ...opts,
      method: "DELETE",
      spec: opts.spec
    };
    return otplease((wrappedPayload) => (0, import_npm_registry_fetch.default)(uri, wrappedPayload), payload, otpCache).then(() => {
      opts.log.verbose("dist-tag", `removed "${tag}" from ${opts.spec.name}@${version}`);
      delete tags[tag];
      return tags;
    });
  });
}
function list(spec, options) {
  const opts = {
    log: import_npmlog35.default,
    ...options,
    spec: (0, import_npm_package_arg6.default)(spec)
  };
  if (opts.dryRun) {
    opts.log.silly("dist-tag", "dry-run configured, bailing now");
    return Promise.resolve();
  }
  return fetchTags(opts);
}
function fetchTags(opts) {
  return import_npm_registry_fetch.default.json(`/-/package/${opts.spec.escapedName}/dist-tags`, {
    ...opts,
    preferOnline: true,
    spec: opts.spec
  }).then((data) => {
    if (data && typeof data === "object") {
      delete data["_etag"];
    }
    return data || {};
  });
}
var import_npm_package_arg6, import_npm_registry_fetch, import_npmlog35;
var init_npm_dist_tag = __esm({
  "libs/core/src/lib/npm-dist-tag.ts"() {
    "use strict";
    import_npm_package_arg6 = __toESM(require("npm-package-arg"));
    import_npm_registry_fetch = __toESM(require("npm-registry-fetch"));
    import_npmlog35 = __toESM(require("npmlog"));
    init_otplease();
  }
});

// libs/core/src/index.ts
var npmConf2, npmDistTag;
var init_src2 = __esm({
  "libs/core/src/index.ts"() {
    "use strict";
    init_add_dependencies();
    init_add_dependents();
    init_check_working_tree();
    init_cli();
    init_collect_updates();
    init_command();
    init_detect_projects();
    init_is_git_initialized();
    init_conventional_commits();
    init_corepack();
    init_describe_ref();
    init_filter_options();
    init_filter_projects();
    init_get_package_manifest_path();
    init_get_packages_for_option();
    init_git_checkout();
    init_has_npm_version();
    init_listable_format_projects();
    init_listable_options();
    init_log_packed();
    init_conf();
    init_npm_install();
    init_npm_publish();
    init_npm_run_script();
    init_otplease();
    init_output();
    init_pack_directory();
    init_package();
    init_prerelease_id_from_version();
    init_profiler();
    init_project();
    init_project_graph_with_packages();
    init_prompt();
    init_pulse_till_done();
    init_rimraf_dir();
    init_run_lifecycle();
    init_run_projects_topologically();
    init_scm_clients();
    init_temp_write();
    init_timer();
    init_toposort_projects();
    init_validation_error();
    npmConf2 = require_npm_conf();
    npmDistTag = (init_npm_dist_tag(), __toCommonJS(npm_dist_tag_exports));
  }
});

// libs/commands/publish/src/lib/create-temp-licenses.ts
function createTempLicenses(srcLicensePath, packagesToBeLicensed) {
  if (!srcLicensePath || !packagesToBeLicensed.length) {
    return Promise.resolve();
  }
  const licenseFileName = import_path18.default.basename(srcLicensePath);
  const options = {
    // make an effort to keep package contents stable over time
    preserveTimestamps: process.arch !== "ia32"
    // (give up on 32-bit architecture to avoid fs-extra warning)
  };
  packagesToBeLicensed.forEach((pkg) => {
    pkg.licensePath = import_path18.default.join(pkg.contents, licenseFileName);
  });
  return (0, import_p_map3.default)(packagesToBeLicensed, (pkg) => import_fs_extra8.default.copy(srcLicensePath, pkg.licensePath, options));
}
var import_fs_extra8, import_p_map3, import_path18;
var init_create_temp_licenses = __esm({
  "libs/commands/publish/src/lib/create-temp-licenses.ts"() {
    "use strict";
    import_fs_extra8 = __toESM(require("fs-extra"));
    import_p_map3 = __toESM(require("p-map"));
    import_path18 = __toESM(require("path"));
  }
});

// libs/commands/publish/src/lib/get-current-sha.ts
function getCurrentSHA(opts) {
  import_npmlog36.default.silly("getCurrentSHA", "");
  const sha = childProcess11.execSync("git", ["rev-parse", "HEAD"], opts);
  import_npmlog36.default.verbose("getCurrentSHA", sha);
  return sha;
}
var import_npmlog36, childProcess11;
var init_get_current_sha = __esm({
  "libs/commands/publish/src/lib/get-current-sha.ts"() {
    "use strict";
    import_npmlog36 = __toESM(require("npmlog"));
    childProcess11 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/publish/src/lib/get-current-tags.ts
async function getCurrentTags(execOpts, matchingPattern) {
  import_npmlog37.default.silly("getCurrentTags", "matching %j", matchingPattern);
  const opts = Object.assign({}, execOpts, {
    // don't reject due to non-zero exit code when there are no results
    reject: false
  });
  const result = await childProcess12.exec(
    "git",
    ["tag", "--sort", "version:refname", "--points-at", "HEAD", "--list", matchingPattern],
    opts
  );
  const lines = result.stdout.split("\n").filter(Boolean);
  if (matchingPattern === "*@*") {
    return lines.map((tag) => (0, import_npm_package_arg7.default)(tag).name);
  }
  return lines;
}
var import_npm_package_arg7, import_npmlog37, childProcess12;
var init_get_current_tags = __esm({
  "libs/commands/publish/src/lib/get-current-tags.ts"() {
    "use strict";
    import_npm_package_arg7 = __toESM(require("npm-package-arg"));
    import_npmlog37 = __toESM(require("npmlog"));
    childProcess12 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/publish/src/lib/fetch-config.ts
function getFetchConfig(options, extra) {
  return {
    log: import_npmlog38.default,
    ...options,
    ...extra
  };
}
var import_npmlog38;
var init_fetch_config = __esm({
  "libs/commands/publish/src/lib/fetch-config.ts"() {
    "use strict";
    import_npmlog38 = __toESM(require("npmlog"));
  }
});

// libs/commands/publish/src/lib/get-profile-data.ts
function getProfileData(opts) {
  opts.log.verbose("", "Retrieving npm user profile");
  return pulseTillDone(import_npm_registry_fetch2.default.json("/-/npm/v1/user", opts)).then((data) => {
    opts.log.silly("npm profile get", "received %j", data);
    return Object.assign(
      // remap to match legacy whoami format
      { username: data.name },
      data
    );
  });
}
var import_npm_registry_fetch2;
var init_get_profile_data = __esm({
  "libs/commands/publish/src/lib/get-profile-data.ts"() {
    "use strict";
    init_src2();
    import_npm_registry_fetch2 = __toESM(require("npm-registry-fetch"));
  }
});

// libs/commands/publish/src/lib/get-whoami.ts
function getWhoAmI(opts) {
  opts.log.verbose("", "Retrieving npm username");
  return pulseTillDone(import_npm_registry_fetch3.default.json("/-/whoami", opts)).then((data) => {
    opts.log.silly("npm whoami", "received %j", data);
    return data;
  });
}
var import_npm_registry_fetch3;
var init_get_whoami = __esm({
  "libs/commands/publish/src/lib/get-whoami.ts"() {
    "use strict";
    init_src2();
    import_npm_registry_fetch3 = __toESM(require("npm-registry-fetch"));
  }
});

// libs/commands/publish/src/lib/get-npm-username.ts
function getNpmUsername(options = {}) {
  const opts = getFetchConfig(options, {
    // don't wait forever for third-party failures to be dealt with
    fetchRetries: 0
  });
  opts.log.info("", "Verifying npm credentials");
  return getProfileData(opts).catch((err) => {
    if (err.code === "E500" || err.code === "E404") {
      return getWhoAmI(opts);
    }
    throw err;
  }).then(success, failure);
  function success(result) {
    opts.log.silly("get npm username", "received %j", result);
    if (!result.username) {
      throw new ValidationError(
        "ENEEDAUTH",
        "You must be logged in to publish packages. Use `npm login` and try again."
      );
    }
    return result.username;
  }
  function failure(err) {
    opts.log.pause();
    console.error(err.message);
    opts.log.resume();
    if (opts.registry === "https://registry.npmjs.org/") {
      if (err.code === "E403") {
        throw new ValidationError(
          "ENEEDAUTH",
          "Access verification failed. Ensure that your npm access token has both read and write access, or remove the verifyAccess option to skip this verification. Note that npm automation tokens do NOT have read access (https://docs.npmjs.com/creating-and-viewing-access-tokens)."
        );
      }
      throw new ValidationError("EWHOAMI", "Authentication error. Use `npm whoami` to troubleshoot.");
    }
    opts.log.warn(
      "EWHOAMI",
      "Unable to determine npm username from third-party registry, this command will likely fail soon!"
    );
  }
}
var init_get_npm_username = __esm({
  "libs/commands/publish/src/lib/get-npm-username.ts"() {
    "use strict";
    init_src2();
    init_fetch_config();
    init_get_profile_data();
    init_get_whoami();
  }
});

// libs/commands/publish/src/lib/get-packages-without-license.ts
function getPackagesWithoutLicense(project, packagesToPublish) {
  return project.getPackageLicensePaths().then((licensePaths) => {
    const licensed = new Set(licensePaths.map((lp) => import_path19.default.dirname(lp)));
    return packagesToPublish.filter((pkg) => !licensed.has(pkg.location));
  });
}
var import_path19;
var init_get_packages_without_license = __esm({
  "libs/commands/publish/src/lib/get-packages-without-license.ts"() {
    "use strict";
    import_path19 = __toESM(require("path"));
  }
});

// libs/commands/publish/src/lib/get-projects-with-tagged-packages.ts
async function getProjectsWithTaggedPackages(projectNodes, projectFileMap, execOpts) {
  import_npmlog39.default.silly("getTaggedPackages", "");
  const result = await childProcess13.exec(
    "git",
    ["diff-tree", "--name-only", "--no-commit-id", "--root", "-r", "-c", "HEAD"],
    execOpts
  );
  const stdout = result.stdout;
  const files = new Set(stdout.split("\n"));
  return projectNodes.filter((node) => projectFileMap[node.name]?.some((file) => files.has(file.file)));
}
var import_npmlog39, childProcess13;
var init_get_projects_with_tagged_packages = __esm({
  "libs/commands/publish/src/lib/get-projects-with-tagged-packages.ts"() {
    "use strict";
    import_npmlog39 = __toESM(require("npmlog"));
    childProcess13 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/publish/src/lib/get-projects-with-unpublished-packages.ts
async function getProjectsWithUnpublishedPackages(projectNodes, opts) {
  import_npmlog40.default.silly("getProjectsWithUnpublishedPackages", "");
  const mapper = (node) => {
    const pkg = getPackage(node);
    opts["strictSSL"] = opts["strict-ssl"];
    return import_pacote.default.packument(pkg.name, opts).then(
      (packument) => {
        if (packument.versions === void 0 || packument.versions[pkg.version] === void 0) {
          return node;
        }
      },
      () => {
        import_npmlog40.default.warn("", "Unable to determine published version, assuming %j unpublished.", pkg.name);
        return node;
      }
    );
  };
  const results = await (0, import_p_map4.default)(projectNodes, mapper, { concurrency: 4 });
  return results.filter(Boolean);
}
var import_npmlog40, import_p_map4, import_pacote;
var init_get_projects_with_unpublished_packages = __esm({
  "libs/commands/publish/src/lib/get-projects-with-unpublished-packages.ts"() {
    "use strict";
    init_src2();
    import_npmlog40 = __toESM(require("npmlog"));
    import_p_map4 = __toESM(require("p-map"));
    import_pacote = __toESM(require("pacote"));
  }
});

// libs/commands/publish/src/lib/get-two-factor-auth-required.ts
function getTwoFactorAuthRequired(options = {}) {
  const opts = getFetchConfig(options, {
    // don't wait forever for third-party failures to be dealt with
    fetchRetries: 0
  });
  opts.log.info("", "Checking two-factor auth mode");
  return getProfileData(opts).then(success, failure);
  function success(result) {
    opts.log.silly("2FA", result.tfa);
    if (result.tfa.pending) {
      return false;
    }
    return result.tfa.mode === "auth-and-writes";
  }
  function failure(err) {
    if (err.code === "E500" || err.code === "E404") {
      opts.log.warn(
        "EREGISTRY",
        `Registry "${opts.registry}" does not support 'npm profile get', skipping two-factor auth check...`
      );
      return false;
    }
    opts.log.pause();
    console.error(err.message);
    opts.log.resume();
    throw new ValidationError("ETWOFACTOR", "Unable to obtain two-factor auth mode");
  }
}
var init_get_two_factor_auth_required = __esm({
  "libs/commands/publish/src/lib/get-two-factor-auth-required.ts"() {
    "use strict";
    init_src2();
    init_fetch_config();
    init_get_profile_data();
  }
});

// libs/commands/publish/src/lib/git-checkout.ts
var init_git_checkout2 = __esm({
  "libs/commands/publish/src/lib/git-checkout.ts"() {
    "use strict";
    init_src2();
  }
});

// libs/commands/publish/src/lib/interpolate.ts
function interpolate(template, data) {
  const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || import_devkit5.workspaceRoot;
  if (template.includes("{workspaceRoot}", 1)) {
    throw new Error(
      `Config '${template}' is invalid. {workspaceRoot} can only be used at the beginning of the expression.`
    );
  }
  if (data.projectRoot == "." && template.includes("{projectRoot}", 1)) {
    throw new Error(
      `Config '${template}' is invalid. When {projectRoot} is '.', it can only be used at the beginning of the expression.`
    );
  }
  let res = template.replace("{workspaceRoot}", _workspaceRoot);
  if (data.projectRoot == ".") {
    res = res.replace("{projectRoot}/", "");
  }
  return res.replace(/{([\s\S]+?)}/g, (match) => {
    let value = data;
    const path19 = match.slice(1, -1).trim().split(".");
    for (let idx = 0; idx < path19.length; idx++) {
      if (!value[path19[idx]]) {
        return match;
      }
      value = value[path19[idx]];
    }
    return value;
  });
}
var import_devkit5;
var init_interpolate = __esm({
  "libs/commands/publish/src/lib/interpolate.ts"() {
    "use strict";
    import_devkit5 = require("@nx/devkit");
  }
});

// libs/commands/publish/src/lib/remove-temp-licenses.ts
function removeTempLicenses(packagesToBeLicensed) {
  if (!packagesToBeLicensed.length) {
    return Promise.resolve();
  }
  return (0, import_p_map5.default)(packagesToBeLicensed, (pkg) => import_fs_extra9.default.remove(pkg.licensePath));
}
var import_fs_extra9, import_p_map5;
var init_remove_temp_licenses = __esm({
  "libs/commands/publish/src/lib/remove-temp-licenses.ts"() {
    "use strict";
    import_fs_extra9 = __toESM(require("fs-extra"));
    import_p_map5 = __toESM(require("p-map"));
  }
});

// libs/commands/publish/src/lib/verify-npm-package-access.ts
function verifyNpmPackageAccess(packages, username, options) {
  const opts = getFetchConfig(options, {
    // don't wait forever for third-party failures to be dealt with
    fetchRetries: 0
  });
  opts.log.silly("verifyNpmPackageAccess", "");
  return pulseTillDone(import_libnpmaccess.default.getPackages(username, opts)).then(success, failure);
  function success(result) {
    const userPackages = Object.keys(result || {});
    if (userPackages.length === 0) {
      opts.log.warn(
        "",
        "The logged-in user does not have any previously-published packages, skipping permission checks..."
      );
      return;
    }
    for (const pkg of packages) {
      if (pkg.name in result && result[pkg.name] !== "read-write") {
        throw new ValidationError(
          "EACCESS",
          `You do not have write permission required to publish "${pkg.name}"`
        );
      }
    }
  }
  function failure(err) {
    if (err.code === "E500" || err.code === "E404") {
      opts.log.warn(
        "EREGISTRY",
        "Registry %j does not support `npm access list packages`, skipping permission checks...",
        // registry
        opts.registry
      );
      return;
    }
    opts.log.pause();
    console.error(err.message);
    opts.log.resume();
    throw new ValidationError("EWHOAMI", "Authentication error. Use `npm whoami` to troubleshoot.");
  }
}
var import_libnpmaccess;
var init_verify_npm_package_access = __esm({
  "libs/commands/publish/src/lib/verify-npm-package-access.ts"() {
    "use strict";
    init_src2();
    import_libnpmaccess = __toESM(require("libnpmaccess"));
    init_fetch_config();
  }
});

// libs/commands/version/src/lib/create-release.ts
function createReleaseClient(type) {
  switch (type) {
    case "gitlab":
      return createGitLabClient();
    case "github":
      return createGitHubClient();
    default:
      throw new ValidationError("ERELEASE", "Invalid release client type");
  }
}
function createRelease(client, { tags, releaseNotes }, { gitRemote, execOpts }) {
  const repo = parseGitRepo(gitRemote, execOpts);
  return Promise.all(
    releaseNotes.map(({ notes, name }) => {
      const tag = name === "fixed" ? tags[0] : tags.find((t) => t.startsWith(`${name}@`));
      if (!tag) {
        return Promise.resolve();
      }
      const prereleaseParts = import_semver5.default.prerelease(tag.replace(`${name}@`, "")) || [];
      return client.repos.createRelease({
        owner: repo.owner,
        repo: repo.name,
        tag_name: tag,
        name: tag,
        body: notes,
        draft: false,
        prerelease: prereleaseParts.length > 0
      });
    })
  );
}
var import_semver5;
var init_create_release = __esm({
  "libs/commands/version/src/lib/create-release.ts"() {
    "use strict";
    init_src2();
    import_semver5 = __toESM(require("semver"));
  }
});

// libs/commands/version/src/lib/get-current-branch.ts
function getCurrentBranch(opts) {
  import_npmlog41.default.silly("getCurrentBranch");
  const branch = childProcess14.execSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], opts);
  import_npmlog41.default.verbose("currentBranch", branch);
  return branch;
}
var import_npmlog41, childProcess14;
var init_get_current_branch = __esm({
  "libs/commands/version/src/lib/get-current-branch.ts"() {
    "use strict";
    import_npmlog41 = __toESM(require("npmlog"));
    childProcess14 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/git-add.ts
function resolvePrettier() {
  if (!resolvedPrettier) {
    try {
      const packageJson = (0, import_devkit6.readJsonFile)(import_path20.default.join(import_devkit6.workspaceRoot, "package.json"));
      const hasPrettier = packageJson.devDependencies?.prettier || packageJson.dependencies?.prettier;
      if (!hasPrettier) {
        return;
      }
      resolvedPrettier = require("prettier");
    } catch {
      return;
    }
  }
  return resolvedPrettier;
}
async function maybeFormatFile(filePath) {
  const prettier = resolvePrettier();
  if (!prettier) {
    return;
  }
  const config = await resolvedPrettier.resolveConfig(filePath);
  const ignorePath = import_path20.default.join(import_devkit6.workspaceRoot, ".prettierignore");
  const fullFilePath = import_path20.default.join(import_devkit6.workspaceRoot, filePath);
  const fileInfo = await resolvedPrettier.getFileInfo(fullFilePath, { ignorePath });
  if (fileInfo.ignored) {
    import_npmlog42.default.silly("version", `Skipped applying prettier to ignored file: ${filePath}`);
    return;
  }
  try {
    const input = import_fs5.default.readFileSync(fullFilePath, "utf8");
    import_fs5.default.writeFileSync(
      fullFilePath,
      await resolvedPrettier.format(input, { ...config, filepath: fullFilePath }),
      "utf8"
    );
    import_npmlog42.default.silly("version", `Successfully applied prettier to updated file: ${filePath}`);
  } catch {
    import_npmlog42.default.silly("version", `Failed to apply prettier to updated file: ${filePath}`);
  }
}
async function gitAdd(changedFiles, gitOpts, execOpts) {
  let files = [];
  for (const file of changedFiles) {
    const filePath = (0, import_slash2.default)(import_path20.default.relative(execOpts.cwd, import_path20.default.resolve(execOpts.cwd, file)));
    await maybeFormatFile(filePath);
    if (gitOpts.granularPathspec) {
      files.push(filePath);
    }
  }
  if (!gitOpts.granularPathspec) {
    files = ".";
  }
  import_npmlog42.default.silly("gitAdd", files);
  return childProcess15.exec("git", ["add", "--", ...files], execOpts);
}
var import_devkit6, import_fs5, import_npmlog42, import_path20, import_slash2, childProcess15, resolvedPrettier;
var init_git_add = __esm({
  "libs/commands/version/src/lib/git-add.ts"() {
    "use strict";
    import_devkit6 = require("@nx/devkit");
    import_fs5 = __toESM(require("fs"));
    import_npmlog42 = __toESM(require("npmlog"));
    import_path20 = __toESM(require("path"));
    import_slash2 = __toESM(require("slash"));
    childProcess15 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/git-commit.ts
function gitCommit(message, { amend, commitHooks, signGitCommit, signoffGitCommit }, opts) {
  import_npmlog43.default.silly("gitCommit", message);
  const args = ["commit"];
  if (commitHooks === false) {
    args.push("--no-verify");
  }
  if (signGitCommit) {
    args.push("--gpg-sign");
  }
  if (signoffGitCommit) {
    args.push("--signoff");
  }
  if (amend) {
    args.push("--amend", "--no-edit");
  } else if (message.indexOf(import_os4.EOL) > -1) {
    args.push("-F", temp_write_default.sync(message, "lerna-commit.txt"));
  } else {
    args.push("-m", message);
  }
  import_npmlog43.default.verbose("git", args);
  return childProcess16.exec("git", args, opts);
}
var import_npmlog43, import_os4, childProcess16;
var init_git_commit = __esm({
  "libs/commands/version/src/lib/git-commit.ts"() {
    "use strict";
    init_src2();
    import_npmlog43 = __toESM(require("npmlog"));
    import_os4 = require("os");
    childProcess16 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/git-push.ts
function gitPush(remote, branch, opts) {
  import_npmlog44.default.silly("gitPush", remote, branch);
  return childProcess17.exec("git", ["push", "--follow-tags", "--no-verify", "--atomic", remote, branch], opts).catch((error) => {
    if (/atomic/.test(error.stderr) || process.env.GIT_REDIRECT_STDERR === "2>&1" && /atomic/.test(error.stdout)) {
      import_npmlog44.default.warn("gitPush", error.stderr);
      import_npmlog44.default.info("gitPush", "--atomic failed, attempting non-atomic push");
      return childProcess17.exec("git", ["push", "--follow-tags", "--no-verify", remote, branch], opts);
    }
    throw error;
  });
}
var import_npmlog44, childProcess17;
var init_git_push = __esm({
  "libs/commands/version/src/lib/git-push.ts"() {
    "use strict";
    import_npmlog44 = __toESM(require("npmlog"));
    childProcess17 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/git-tag.ts
function gitTag(tag, { forceGitTag, signGitTag }, opts, command = "git tag %s -m %s") {
  import_npmlog45.default.silly("gitTag", tag, command);
  const [cmd, ...args] = command.split(" ");
  const interpolatedArgs = args.map((arg) => arg.replace(/%s/, tag));
  if (forceGitTag) {
    interpolatedArgs.push("--force");
  }
  if (signGitTag) {
    interpolatedArgs.push("--sign");
  }
  import_npmlog45.default.verbose(cmd, interpolatedArgs);
  return childProcess18.exec(cmd, interpolatedArgs, opts);
}
var import_npmlog45, childProcess18;
var init_git_tag = __esm({
  "libs/commands/version/src/lib/git-tag.ts"() {
    "use strict";
    import_npmlog45 = __toESM(require("npmlog"));
    childProcess18 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/is-anything-committed.ts
function isAnythingCommitted(opts) {
  import_npmlog46.default.silly("isAnythingCommitted", "");
  const anyCommits = childProcess19.execSync("git", ["rev-list", "--count", "--all", "--max-count=1"], opts);
  import_npmlog46.default.verbose("isAnythingCommitted", anyCommits);
  return Boolean(parseInt(anyCommits, 10));
}
var import_npmlog46, childProcess19;
var init_is_anything_committed = __esm({
  "libs/commands/version/src/lib/is-anything-committed.ts"() {
    "use strict";
    import_npmlog46 = __toESM(require("npmlog"));
    childProcess19 = (init_src(), __toCommonJS(src_exports));
    module.exports.isAnythingCommitted = isAnythingCommitted;
  }
});

// libs/commands/version/src/lib/is-behind-upstream.ts
function isBehindUpstream(gitRemote, branch, opts) {
  import_npmlog47.default.silly("isBehindUpstream", "");
  updateRemote(opts);
  const remoteBranch = `${gitRemote}/${branch}`;
  const [behind, ahead] = countLeftRight(`${remoteBranch}...${branch}`, opts);
  import_npmlog47.default.silly(
    "isBehindUpstream",
    `${branch} is behind ${remoteBranch} by ${behind} commit(s) and ahead by ${ahead}`
  );
  return Boolean(behind);
}
function updateRemote(opts) {
  childProcess20.execSync("git", ["remote", "update"], opts);
}
function countLeftRight(symmetricDifference, opts) {
  const stdout = childProcess20.execSync(
    "git",
    ["rev-list", "--left-right", "--count", symmetricDifference],
    opts
  );
  return stdout.split("	").map((val) => parseInt(val, 10));
}
var import_npmlog47, childProcess20;
var init_is_behind_upstream = __esm({
  "libs/commands/version/src/lib/is-behind-upstream.ts"() {
    "use strict";
    import_npmlog47 = __toESM(require("npmlog"));
    childProcess20 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/is-breaking-change.ts
function isBreakingChange(currentVersion, nextVersion) {
  const releaseType = import_semver6.default.diff(currentVersion, nextVersion);
  let breaking;
  if (releaseType === "major") {
    breaking = true;
  } else if (releaseType === "minor") {
    breaking = import_semver6.default.lt(currentVersion, "1.0.0");
  } else if (releaseType === "patch") {
    breaking = import_semver6.default.lt(currentVersion, "0.1.0");
  } else {
    breaking = false;
  }
  return breaking;
}
var import_semver6;
var init_is_breaking_change = __esm({
  "libs/commands/version/src/lib/is-breaking-change.ts"() {
    "use strict";
    import_semver6 = __toESM(require("semver"));
  }
});

// libs/commands/version/src/lib/prompt-version.ts
function makePromptVersion(resolvePrereleaseId, buildMetadata) {
  return (node) => promptVersion(node.version, node.name, resolvePrereleaseId(node.prereleaseId), buildMetadata);
}
function promptVersion(currentVersion, name, prereleaseId, buildMetadata) {
  const patch = applyBuildMetadata(import_semver7.default.inc(currentVersion, "patch"), buildMetadata);
  const minor = applyBuildMetadata(import_semver7.default.inc(currentVersion, "minor"), buildMetadata);
  const major = applyBuildMetadata(import_semver7.default.inc(currentVersion, "major"), buildMetadata);
  const prepatch = applyBuildMetadata(import_semver7.default.inc(currentVersion, "prepatch", prereleaseId), buildMetadata);
  const preminor = applyBuildMetadata(import_semver7.default.inc(currentVersion, "preminor", prereleaseId), buildMetadata);
  const premajor = applyBuildMetadata(import_semver7.default.inc(currentVersion, "premajor", prereleaseId), buildMetadata);
  const message = `Select a new version ${name ? `for ${name} ` : ""}(currently ${currentVersion})`;
  return promptSelectOne(message, {
    choices: [
      { value: patch, name: `Patch (${patch})` },
      { value: minor, name: `Minor (${minor})` },
      { value: major, name: `Major (${major})` },
      { value: prepatch, name: `Prepatch (${prepatch})` },
      { value: preminor, name: `Preminor (${preminor})` },
      { value: premajor, name: `Premajor (${premajor})` },
      { value: "PRERELEASE", name: "Custom Prerelease" },
      { value: "CUSTOM", name: "Custom Version" }
    ]
  }).then((choice) => {
    if (choice === "CUSTOM") {
      return promptTextInput("Enter a custom version", {
        filter: import_semver7.default.valid,
        // semver.valid() always returns null with invalid input
        validate: (v) => v !== null || "Must be a valid semver version"
      });
    }
    if (choice === "PRERELEASE") {
      const defaultVersion = import_semver7.default.inc(currentVersion, "prerelease", prereleaseId);
      const prompt = `(default: "${prereleaseId}", yielding ${defaultVersion})`;
      return promptTextInput(`Enter a prerelease identifier ${prompt}`, {
        filter: (v) => applyBuildMetadata(import_semver7.default.inc(currentVersion, "prerelease", v || prereleaseId), buildMetadata)
      });
    }
    return choice;
  });
}
var import_semver7;
var init_prompt_version = __esm({
  "libs/commands/version/src/lib/prompt-version.ts"() {
    "use strict";
    init_src2();
    import_semver7 = __toESM(require("semver"));
  }
});

// libs/commands/version/src/lib/remote-branch-exists.ts
function remoteBranchExists(gitRemote, branch, opts) {
  import_npmlog48.default.silly("remoteBranchExists", "");
  const remoteBranch = `${gitRemote}/${branch}`;
  try {
    childProcess21.execSync("git", ["show-ref", "--verify", `refs/remotes/${remoteBranch}`], opts);
    return true;
  } catch (e) {
    return false;
  }
}
var import_npmlog48, childProcess21;
var init_remote_branch_exists = __esm({
  "libs/commands/version/src/lib/remote-branch-exists.ts"() {
    "use strict";
    import_npmlog48 = __toESM(require("npmlog"));
    childProcess21 = (init_src(), __toCommonJS(src_exports));
  }
});

// libs/commands/version/src/lib/update-lockfile-version.ts
async function updateLockfileVersion(pkg) {
  const lockfilePath = import_path21.default.join(pkg.location, "package-lock.json");
  const obj = await (0, import_load_json_file3.default)(lockfilePath).catch(() => {
    import_npmlog49.default.verbose("version", `${pkg.name} has no lockfile. Skipping lockfile update.`);
  });
  if (!obj) {
    return;
  }
  obj.version = pkg.version;
  if (obj.packages && obj.packages[""]) {
    obj.packages[""].version = pkg.version;
    if (obj.packages[""].dependencies) {
      const updatedPkgDependencies = Object.keys(obj.packages[""].dependencies).reduce(
        (prev, next) => ({ ...prev, [next]: pkg.dependencies?.[next] }),
        {}
      );
      obj.packages[""].dependencies = updatedPkgDependencies;
    }
    if (obj.packages[""].devDependencies) {
      const updatedPkgDevDependencies = Object.keys(obj.packages[""].devDependencies).reduce(
        (prev, next) => ({ ...prev, [next]: pkg.devDependencies?.[next] }),
        {}
      );
      obj.packages[""].devDependencies = updatedPkgDevDependencies;
    }
  }
  (0, import_devkit7.writeJsonFile)(lockfilePath, obj, {
    spaces: 2
  });
  return lockfilePath;
}
var import_devkit7, import_load_json_file3, import_npmlog49, import_path21;
var init_update_lockfile_version = __esm({
  "libs/commands/version/src/lib/update-lockfile-version.ts"() {
    "use strict";
    import_devkit7 = require("@nx/devkit");
    import_load_json_file3 = __toESM(require("load-json-file"));
    import_npmlog49 = __toESM(require("npmlog"));
    import_path21 = __toESM(require("path"));
  }
});

// libs/commands/version/src/index.ts
var require_src = __commonJS({
  "libs/commands/version/src/index.ts"(exports2, module2) {
    "use strict";
    init_src2();
    var import_chalk4 = __toESM(require("chalk"));
    var import_dedent5 = __toESM(require("dedent"));
    var import_execa3 = __toESM(require("execa"));
    var import_fs6 = __toESM(require("fs"));
    var import_minimatch3 = __toESM(require("minimatch"));
    var import_os5 = __toESM(require("os"));
    var import_p_map6 = __toESM(require("p-map"));
    var import_p_pipe = __toESM(require("p-pipe"));
    var import_p_reduce = __toESM(require("p-reduce"));
    var import_p_waterfall = __toESM(require("p-waterfall"));
    var import_path22 = __toESM(require("path"));
    var import_semver8 = __toESM(require("semver"));
    init_create_release();
    init_get_current_branch();
    init_git_add();
    init_git_commit();
    init_git_push();
    init_git_tag();
    init_is_anything_committed();
    init_is_behind_upstream();
    init_is_breaking_change();
    init_prompt_version();
    init_remote_branch_exists();
    init_update_lockfile_version();
    var childProcess22 = (init_src(), __toCommonJS(src_exports));
    module2.exports = function factory(argv, preInitializedProjectData) {
      return new VersionCommand(argv, preInitializedProjectData);
    };
    var VersionCommand = class extends Command {
      /**
       * Due to lerna publish's legacy of being backwards compatible with running versioning and publishing
       * in a single step, we need to be able to receive any project data which might already exist from the
       * publish command (in the case that it invokes the version command from within its implementation details).
       */
      constructor(argv, preInitializedProjectData) {
        super(argv, { skipValidations: false, preInitializedProjectData });
        this.updates = [];
        this.projectsWithPackage = [];
      }
      get otherCommandConfigs() {
        return ["publish"];
      }
      get requiresGit() {
        return !!(this.commitAndTag || this.pushToRemote || this.options.allowBranch || this.options.conventionalCommits);
      }
      configureProperties() {
        super.configureProperties();
        const {
          amend,
          commitHooks = true,
          gitRemote = "origin",
          gitTagVersion = true,
          granularPathspec = true,
          push = true,
          signGitCommit,
          signoffGitCommit,
          signGitTag,
          forceGitTag,
          tagVersionPrefix = "v",
          premajorVersionBump = "default"
        } = this.options;
        this.gitRemote = gitRemote;
        this.tagPrefix = tagVersionPrefix;
        this.commitAndTag = gitTagVersion;
        this.pushToRemote = gitTagVersion && amend !== true && push;
        this.premajorVersionBump = premajorVersionBump;
        this.releaseClient = this.pushToRemote && this.options.createRelease && createReleaseClient(this.options.createRelease);
        this.releaseNotes = [];
        if (this.releaseClient && this.options.conventionalCommits !== true) {
          throw new ValidationError("ERELEASE", "To create a release, you must enable --conventional-commits");
        }
        if (this.releaseClient && this.options.changelog === false) {
          throw new ValidationError("ERELEASE", "To create a release, you cannot pass --no-changelog");
        }
        this.gitOpts = {
          amend,
          commitHooks,
          granularPathspec,
          signGitCommit,
          signoffGitCommit,
          signGitTag,
          forceGitTag
        };
        this.savePrefix = this.options.exact ? "" : "^";
      }
      async initialize() {
        if (!this.project.isIndependent()) {
          this.logger.info("current version", this.project.version);
        }
        if (this.requiresGit) {
          if (!isAnythingCommitted(this.execOpts)) {
            throw new ValidationError(
              "ENOCOMMIT",
              "No commits in this repository. Please commit something before using version."
            );
          }
          this.currentBranch = getCurrentBranch(this.execOpts);
          if (this.currentBranch === "HEAD") {
            throw new ValidationError(
              "ENOGIT",
              "Detached git HEAD, please checkout a branch to choose versions."
            );
          }
          if (this.pushToRemote && !remoteBranchExists(this.gitRemote, this.currentBranch, this.execOpts)) {
            throw new ValidationError(
              "ENOREMOTEBRANCH",
              import_dedent5.default`
            Branch '${this.currentBranch}' doesn't exist in remote '${this.gitRemote}'.
            If this is a new branch, please make sure you push it to the remote first.
          `
            );
          }
          if (this.options.allowBranch && ![].concat(this.options.allowBranch).some((x) => (0, import_minimatch3.default)(this.currentBranch, x))) {
            throw new ValidationError(
              "ENOTALLOWED",
              import_dedent5.default`
            Branch '${this.currentBranch}' is restricted from versioning due to allowBranch config.
            Please consider the reasons for this restriction before overriding the option.
          `
            );
          }
          if (this.commitAndTag && this.pushToRemote && isBehindUpstream(this.gitRemote, this.currentBranch, this.execOpts)) {
            const message = `Local branch '${this.currentBranch}' is behind remote upstream ${this.gitRemote}/${this.currentBranch}`;
            if (!this.options.ci) {
              throw new ValidationError(
                "EBEHIND",
                import_dedent5.default`
              ${message}
              Please merge remote changes into '${this.currentBranch}' with 'git pull'
            `
              );
            }
            this.logger.warn("EBEHIND", `${message}, exiting`);
            return false;
          }
        } else {
          this.logger.notice(
            "FYI",
            "git repository validation has been skipped, please ensure your version bumps are correct"
          );
        }
        if (this.options.conventionalPrerelease && this.options.conventionalGraduate) {
          throw new ValidationError(
            "ENOTALLOWED",
            import_dedent5.default`
          --conventional-prerelease cannot be combined with --conventional-graduate.
        `
          );
        }
        this.projectsWithPackage = Object.values(this.projectGraph.nodes).filter((node) => !!node.package);
        this.updates = collectProjectUpdates(
          this.projectsWithPackage,
          this.projectGraph,
          this.execOpts,
          this.options
        ).filter((node) => {
          const pkg = getPackage(node);
          if (pkg.private && this.options.private === false) {
            return false;
          }
          if (!pkg.version) {
            if (pkg.private) {
              this.logger.info("version", "Skipping unversioned private package %j", pkg.name);
            } else {
              throw new ValidationError(
                "ENOVERSION",
                import_dedent5.default`
              A version field is required in ${pkg.name}'s package.json file.
              If you wish to keep the package unversioned, it must be made private.
            `
              );
            }
          }
          return !!pkg.version;
        });
        if (!this.updates.length) {
          this.logger.success("", `No changed packages to ${this.composed ? "publish" : "version"}`);
          return false;
        }
        this.hasRootedLeaf = !!this.projectGraph.nodes[this.project.manifest.name];
        if (this.hasRootedLeaf && !this.composed) {
          this.logger.info("version", "rooted leaf detected, skipping synthetic root lifecycles");
        }
        this.runPackageLifecycle = createRunner({ ...this.options, stdio: "inherit" });
        this.runRootLifecycle = /^(pre|post)?version$/.test(process.env.npm_lifecycle_event) ? (stage) => {
          this.logger.warn("lifecycle", "Skipping root %j because it has already been called", stage);
        } : (stage) => this.runPackageLifecycle(this.project.manifest, stage);
        if (this.commitAndTag && this.gitOpts.amend !== true) {
          const { forcePublish, conventionalCommits, conventionalGraduate } = this.options;
          const checkUncommittedOnly = forcePublish || conventionalCommits && conventionalGraduate;
          const check = checkUncommittedOnly ? throwIfUncommitted : checkWorkingTree;
          await check(this.execOpts);
        } else {
          this.logger.warn("version", "Skipping working tree validation, proceed at your own risk");
        }
        const versions = await this.getVersionsForUpdates();
        this.setUpdatesForVersions(versions);
        return this.confirmVersions();
      }
      execute() {
        const tasks = [() => this.updatePackageVersions()];
        if (this.commitAndTag) {
          tasks.push(() => this.commitAndTagUpdates());
        } else {
          this.logger.info("execute", "Skipping git tag/commit");
        }
        if (this.pushToRemote) {
          tasks.push(() => this.gitPushToRemote());
        } else {
          this.logger.info("execute", "Skipping git push");
        }
        if (this.releaseClient) {
          this.logger.info("execute", "Creating releases...");
          tasks.push(
            () => createRelease(
              this.releaseClient,
              { tags: this.tags, releaseNotes: this.releaseNotes },
              { gitRemote: this.options.gitRemote, execOpts: this.execOpts }
            )
          );
        } else {
          this.logger.info("execute", "Skipping releases");
        }
        return (0, import_p_waterfall.default)(tasks).then(() => {
          if (!this.composed) {
            this.logger.success("version", "finished");
          }
          return {
            updates: this.updates,
            updatesVersions: this.updatesVersions
          };
        });
      }
      /**
       * Gets a mapping of project names to their package's new version.
       * @returns {Promise<Record<string, string>>} A map of project names to their package's new versions
       */
      getVersionsForUpdates() {
        const independentVersions = this.project.isIndependent();
        const { bump, conventionalCommits, preid } = this.options;
        const repoVersion = bump ? import_semver8.default.clean(bump) : "";
        const increment = bump && !import_semver8.default.valid(bump) ? bump : "";
        const resolvePrereleaseId = (existingPreid) => preid || existingPreid || "alpha";
        const makeGlobalVersionPredicate = (nextVersion) => {
          this.globalVersion = nextVersion;
          return () => nextVersion;
        };
        let predicate;
        if (repoVersion) {
          predicate = makeGlobalVersionPredicate(applyBuildMetadata(repoVersion, this.options.buildMetadata));
        } else if (increment && independentVersions) {
          predicate = (node) => applyBuildMetadata(
            import_semver8.default.inc(node.version, increment, resolvePrereleaseId(node.prereleaseId)),
            this.options.buildMetadata
          );
        } else if (increment) {
          const baseVersion = this.project.version;
          const prereleaseId = prereleaseIdFromVersion(baseVersion);
          const nextVersion = applyBuildMetadata(
            import_semver8.default.inc(baseVersion, increment, resolvePrereleaseId(prereleaseId)),
            this.options.buildMetadata
          );
          predicate = makeGlobalVersionPredicate(nextVersion);
        } else if (conventionalCommits) {
          return this.recommendVersions(resolvePrereleaseId);
        } else if (independentVersions) {
          predicate = makePromptVersion(resolvePrereleaseId, this.options.buildMetadata);
        } else {
          const baseVersion = this.project.version;
          const prereleaseId = prereleaseIdFromVersion(baseVersion);
          const node = { version: baseVersion, prereleaseId };
          const prompt = makePromptVersion(resolvePrereleaseId, this.options.buildMetadata);
          predicate = prompt(node).then(makeGlobalVersionPredicate);
        }
        return Promise.resolve(predicate).then(
          (getVersion) => this.reduceVersions((node) => {
            const pkg = getPackage(node);
            return getVersion({
              version: pkg.version,
              name: pkg.name,
              prereleaseId: prereleaseIdFromVersion(pkg.version)
            });
          })
        );
      }
      reduceVersions(getVersion) {
        const iterator = (versionMap, node) => Promise.resolve(getVersion(node)).then((version) => versionMap.set(node.name, version));
        return (0, import_p_reduce.default)(this.updates, iterator, /* @__PURE__ */ new Map());
      }
      getPrereleasePackageNames() {
        const prereleasePackageNames = getPackagesForOption(this.options.conventionalPrerelease);
        const isCandidate = prereleasePackageNames.has("*") ? () => true : (node, name) => prereleasePackageNames.has(name);
        return collectProjects(this.projectsWithPackage, this.projectGraph, { isCandidate }).map(
          (pkg) => pkg.name
        );
      }
      async recommendVersions(resolvePrereleaseId) {
        const independentVersions = this.project.isIndependent();
        const { buildMetadata, changelogPreset, conventionalGraduate, conventionalBumpPrerelease } = this.options;
        const rootPath = this.project.manifest.location;
        const type = independentVersions ? "independent" : "fixed";
        const prereleasePackageNames = this.getPrereleasePackageNames();
        const graduatePackageNames = Array.from(getPackagesForOption(conventionalGraduate));
        const shouldPrerelease = (name) => prereleasePackageNames && prereleasePackageNames.includes(name);
        const shouldGraduate = (name) => graduatePackageNames.includes("*") || graduatePackageNames.includes(name);
        const getPrereleaseId = (node) => {
          if (!shouldGraduate(node.name) && (shouldPrerelease(node.name) || node.prereleaseId)) {
            return resolvePrereleaseId(node.prereleaseId);
          }
        };
        if (type === "fixed") {
          this.setGlobalVersionFloor();
        }
        const versions = await this.reduceVersions((node) => {
          const pkg = getPackage(node);
          return recommendVersion(
            pkg,
            type,
            {
              changelogPreset,
              rootPath,
              tagPrefix: this.tagPrefix,
              prereleaseId: getPrereleaseId({
                name: node.name,
                prereleaseId: prereleaseIdFromVersion(pkg.version)
              }),
              conventionalBumpPrerelease,
              buildMetadata
            },
            this.premajorVersionBump
          );
        });
        if (type === "fixed") {
          this.globalVersion = await this.setGlobalVersionCeiling(versions);
        }
        return versions;
      }
      setGlobalVersionFloor() {
        const globalVersion = this.project.version;
        for (const node of this.updates) {
          const pkg = getPackage(node);
          if (import_semver8.default.lt(pkg.version, globalVersion)) {
            this.logger.verbose(
              "version",
              `Overriding version of ${pkg.name} from ${pkg.version} to ${globalVersion}`
            );
            pkg.set("version", globalVersion);
          }
        }
      }
      setGlobalVersionCeiling(versions) {
        let highestVersion = this.project.version;
        versions.forEach((bump) => {
          if (bump && import_semver8.default.gt(bump, highestVersion)) {
            highestVersion = bump;
          }
        });
        versions.forEach((_, name) => versions.set(name, highestVersion));
        return highestVersion;
      }
      setUpdatesForVersions(versions) {
        if (this.project.isIndependent() || versions.size === this.projectsWithPackage.length) {
          this.updatesVersions = versions;
        } else {
          let hasBreakingChange;
          for (const [name, bump] of versions) {
            const pkg = getPackage(this.projectGraph.nodes[name]);
            hasBreakingChange = hasBreakingChange || isBreakingChange(pkg.version, bump);
          }
          if (hasBreakingChange) {
            this.updates = this.projectsWithPackage;
            if (this.options.private === false) {
              this.updates = this.updates.filter((node) => !getPackage(node).private);
            }
            this.updatesVersions = new Map(this.updates.map((node) => [node.name, this.globalVersion]));
          } else {
            this.updatesVersions = versions;
          }
        }
        this.packagesToVersion = this.updates.map((node) => getPackage(node));
      }
      confirmVersions() {
        if (this.options.json) {
          const updatedProjectsJson = formatJSON(this.updates, ({ name }) => ({
            newVersion: this.updatesVersions.get(name)
          }));
          output(updatedProjectsJson);
        } else {
          const changes = this.updates.map((node) => {
            const pkg = getPackage(node);
            let line = ` - ${pkg.name}: ${pkg.version} => ${this.updatesVersions.get(node.name)}`;
            if (pkg.private) {
              line += ` (${import_chalk4.default.red("private")})`;
            }
            return line;
          });
          output("");
          output("Changes:");
          output(changes.join(import_os5.default.EOL));
          output("");
        }
        if (this.options.yes) {
          this.logger.info("auto-confirmed", "");
          return true;
        }
        const message = this.composed ? "Are you sure you want to publish these packages?" : "Are you sure you want to create these versions?";
        return promptConfirmation(message);
      }
      async updatePackageVersions() {
        const {
          conventionalCommits,
          changelogPreset,
          changelogEntryAdditionalMarkdown,
          changelog = true,
          runScriptsOnLockfileUpdate = false,
          syncDistVersion = false
        } = this.options;
        const independentVersions = this.project.isIndependent();
        const rootPath = this.project.manifest.location;
        const changedFiles = /* @__PURE__ */ new Set();
        if (!this.hasRootedLeaf) {
          await this.runRootLifecycle("preversion");
        }
        const actions = [
          (node) => this.runPackageLifecycle(getPackage(node), "preversion").then(() => node),
          // manifest may be mutated by any previous lifecycle
          (node) => getPackage(node).refresh().then(() => node),
          (node) => {
            const pkg = getPackage(node);
            pkg.version = this.updatesVersions.get(node.name);
            this.updateDependencies(node);
            return Promise.all([
              updateLockfileVersion(pkg),
              pkg.serialize(),
              pkg.syncDistVersion(syncDistVersion)
            ]).then(([lockfilePath]) => {
              changedFiles.add(pkg.manifestLocation);
              if (lockfilePath) {
                changedFiles.add(lockfilePath);
              }
              return node;
            });
          },
          (node) => this.runPackageLifecycle(getPackage(node), "version").then(() => node)
        ];
        if (conventionalCommits && changelog) {
          const type = independentVersions ? "independent" : "fixed";
          actions.push(
            (node) => updateChangelog(getPackage(node), type, {
              changelogPreset,
              changelogEntryAdditionalMarkdown,
              rootPath,
              tagPrefix: this.tagPrefix
            }).then(({ logPath, newEntry }) => {
              changedFiles.add(logPath);
              if (independentVersions) {
                this.releaseNotes.push({
                  name: getPackage(node).name,
                  notes: newEntry
                });
              }
              return node;
            })
          );
        }
        const mapUpdate = (0, import_p_pipe.default)(...actions);
        await runProjectsTopologically(this.updates, this.projectGraph, mapUpdate, {
          concurrency: this.concurrency,
          rejectCycles: this.options.rejectCycles
        });
        if (!independentVersions) {
          this.project.version = this.globalVersion;
          if (conventionalCommits && changelog) {
            const { logPath, newEntry } = await updateChangelog(this.project.manifest, "root", {
              changelogPreset,
              changelogEntryAdditionalMarkdown,
              rootPath,
              tagPrefix: this.tagPrefix,
              version: this.globalVersion
            });
            changedFiles.add(logPath);
            this.releaseNotes.push({
              name: "fixed",
              notes: newEntry
            });
          }
          const lernaConfigLocation = await Promise.resolve(this.project.serializeConfig());
          changedFiles.add(lernaConfigLocation);
        }
        const npmClientArgsRaw = this.options.npmClientArgs || [];
        const npmClientArgs = npmClientArgsRaw.reduce((args, arg) => args.concat(arg.split(/\s|,/)), []);
        if (!this.hasRootedLeaf) {
          await this.runRootLifecycle("version");
        }
        if (this.options.npmClient === "pnpm") {
          this.logger.verbose("version", "Updating root pnpm-lock.yaml");
          await execPackageManager(
            "pnpm",
            [
              "install",
              "--lockfile-only",
              !runScriptsOnLockfileUpdate ? "--ignore-scripts" : "",
              ...npmClientArgs
            ].filter(Boolean),
            this.execOpts
          );
          const lockfilePath = import_path22.default.join(this.project.rootPath, "pnpm-lock.yaml");
          changedFiles.add(lockfilePath);
        }
        if (this.options.npmClient === "yarn") {
          const yarnVersion = execPackageManagerSync("yarn", ["--version"], this.execOpts);
          this.logger.verbose("version", `Detected yarn version ${yarnVersion}`);
          if (import_semver8.default.gte(yarnVersion, "2.0.0")) {
            this.logger.verbose("version", "Updating root yarn.lock");
            await execPackageManager("yarn", ["install", "--mode", "update-lockfile", ...npmClientArgs], {
              ...this.execOpts,
              env: {
                ...process.env,
                YARN_ENABLE_SCRIPTS: "false"
              }
            });
            const lockfilePath = import_path22.default.join(this.project.rootPath, "yarn.lock");
            changedFiles.add(lockfilePath);
          }
        }
        if (this.options.npmClient === "npm" || !this.options.npmClient) {
          const lockfilePath = import_path22.default.join(this.project.rootPath, "package-lock.json");
          if (import_fs6.default.existsSync(lockfilePath)) {
            this.logger.verbose("version", "Updating root package-lock.json");
            await childProcess22.exec(
              "npm",
              [
                "install",
                "--package-lock-only",
                !runScriptsOnLockfileUpdate ? "--ignore-scripts" : "",
                ...npmClientArgs
              ].filter(Boolean),
              this.execOpts
            );
            changedFiles.add(lockfilePath);
          }
        }
        if (this.commitAndTag) {
          await gitAdd(Array.from(changedFiles), this.gitOpts, this.execOpts);
        }
      }
      updateDependencies(node) {
        const dependencies = this.projectGraph.localPackageDependencies[node.name] || [];
        const pkg = getPackage(node);
        dependencies.forEach((dep) => {
          const depVersion = this.updatesVersions.get(dep.target);
          if (
            // only update if the dependency version is being changed
            depVersion && // don't overwrite local file: specifiers, they only change during publish
            dep.targetResolvedNpaResult.type !== "directory"
          ) {
            pkg.updateLocalDependency(dep.targetResolvedNpaResult, depVersion, this.savePrefix);
          }
        });
      }
      async commitAndTagUpdates() {
        let tags = [];
        if (this.project.isIndependent()) {
          tags = await this.gitCommitAndTagVersionForUpdates();
        } else {
          tags = await this.gitCommitAndTagVersion();
        }
        this.tags = tags;
        await (0, import_p_map6.default)(this.packagesToVersion, (pkg) => this.runPackageLifecycle(pkg, "postversion"));
        if (!this.hasRootedLeaf) {
          await this.runRootLifecycle("postversion");
        }
      }
      async gitCommitAndTagVersionForUpdates() {
        const tags = this.updates.map((node) => {
          const pkg = getPackage(node);
          return `${pkg.name}@${this.updatesVersions.get(node.name)}`;
        });
        const subject = this.options.message || "Publish";
        const message = tags.reduce((msg, tag) => `${msg}${import_os5.default.EOL} - ${tag}`, `${subject}${import_os5.default.EOL}`);
        if (await this.hasChanges()) {
          await gitCommit(message, this.gitOpts, this.execOpts);
        }
        if (this.gitOpts.signGitTag) {
          for (const tag of tags)
            await gitTag(tag, this.gitOpts, this.execOpts, this.options.gitTagCommand);
        } else {
          await Promise.all(
            tags.map((tag) => gitTag(tag, this.gitOpts, this.execOpts, this.options.gitTagCommand))
          );
        }
        return tags;
      }
      async gitCommitAndTagVersion() {
        const version = this.globalVersion;
        const tag = `${this.tagPrefix}${version}`;
        const message = this.options.message ? this.options.message.replace(/%s/g, tag).replace(/%v/g, version) : tag;
        if (await this.hasChanges()) {
          await gitCommit(message, this.gitOpts, this.execOpts);
        }
        await gitTag(tag, this.gitOpts, this.execOpts, this.options.gitTagCommand);
        return [tag];
      }
      gitPushToRemote() {
        this.logger.info("git", "Pushing tags...");
        return gitPush(this.gitRemote, this.currentBranch, this.execOpts);
      }
      async hasChanges() {
        try {
          await (0, import_execa3.default)("git", ["diff", "--staged", "--quiet"], {
            stdio: "pipe",
            ...this.execOpts,
            cwd: this.execOpts.cwd
            // force it to a string
          });
        } catch (e) {
          return true;
        }
      }
    };
    module2.exports.VersionCommand = VersionCommand;
  }
});

// libs/commands/publish/src/index.ts
var require_src2 = __commonJS({
  "libs/commands/publish/src/index.ts"(exports2, module2) {
    "use strict";
    init_src2();
    var import_devkit8 = require("@nx/devkit");
    var import_crypto = __toESM(require("crypto"));
    var import_fs6 = __toESM(require("fs"));
    var import_os5 = __toESM(require("os"));
    var import_p_map6 = __toESM(require("p-map"));
    var import_p_pipe = __toESM(require("p-pipe"));
    var import_path22 = __toESM(require("path"));
    var import_semver8 = __toESM(require("semver"));
    var import_fs_extra10 = require("fs-extra");
    var import_globby3 = __toESM(require("globby"));
    var import_npm_package_arg8 = __toESM(require("npm-package-arg"));
    init_create_temp_licenses();
    init_get_current_sha();
    init_get_current_tags();
    init_get_npm_username();
    init_get_packages_without_license();
    init_get_projects_with_tagged_packages();
    init_get_projects_with_unpublished_packages();
    init_get_two_factor_auth_required();
    init_git_checkout2();
    init_interpolate();
    init_remove_temp_licenses();
    init_verify_npm_package_access();
    var versionCommand = require_src();
    module2.exports = function factory(argv) {
      return new PublishCommand(argv);
    };
    var PublishCommand = class extends Command {
      constructor() {
        super(...arguments);
        this.uniqueProvenanceUrls = /* @__PURE__ */ new Set();
      }
      get otherCommandConfigs() {
        return ["version"];
      }
      get requiresGit() {
        return this.options.bump !== "from-package";
      }
      configureProperties() {
        super.configureProperties();
        this.toposort = this.options.sort !== false;
        const {
          // prettier-ignore
          exact,
          gitHead,
          gitReset,
          tagVersionPrefix = "v",
          verifyAccess
        } = this.options;
        if (this.requiresGit && gitHead) {
          throw new ValidationError("EGITHEAD", "--git-head is only allowed with 'from-package' positional");
        }
        this.savePrefix = exact ? "" : "^";
        this.tagPrefix = tagVersionPrefix;
        this.gitReset = gitReset !== false;
        this.npmSession = import_crypto.default.randomBytes(8).toString("hex");
        this.verifyAccess = verifyAccess;
      }
      get userAgent() {
        return `lerna/${this.options.lernaVersion}/node@${process.version}+${process.arch} (${process.platform})`;
      }
      async initialize() {
        if (this.options.verifyAccess === false) {
          this.logger.warn(
            "verify-access",
            "--verify-access=false and --no-verify-access are no longer needed, because the legacy preemptive access verification is now disabled by default. Requests will fail with appropriate errors when not authorized correctly."
          );
        }
        if (this.options.includePrivate) {
          if (this.options.includePrivate.length === 0) {
            throw new ValidationError(
              "EINCLPRIV",
              "Must specify at least one private package to include with --include-private."
            );
          }
          this.logger.info("publish", `Including private packages %j`, this.options.includePrivate);
        }
        if (this.options.skipNpm) {
          this.logger.warn("deprecated", "Instead of --skip-npm, call `lerna version` directly");
          return versionCommand(this.argv).then(() => false);
        }
        if (this.options.buildMetadata && this.options.canary) {
          throw new ValidationError(
            "ENOTSATISFIED",
            "Cannot use --build-metadata in conjunction with --canary option."
          );
        } else if (this.options.canary) {
          this.logger.info("canary", "enabled");
        }
        if (this.options.requireScripts) {
          this.logger.info("require-scripts", "enabled");
        }
        this.logger.verbose("session", this.npmSession);
        this.logger.verbose("user-agent", this.userAgent);
        this.conf = npmConf2({
          lernaCommand: "publish",
          _auth: this.options.legacyAuth,
          npmSession: this.npmSession,
          npmVersion: this.userAgent,
          otp: this.options.otp,
          registry: this.options.registry,
          "ignore-prepublish": this.options.ignorePrepublish,
          "ignore-scripts": this.options.ignoreScripts
        });
        this.otpCache = { otp: this.conf.get("otp") };
        this.conf.set("user-agent", this.userAgent, "cli");
        if (this.conf.get("registry") === "https://registry.yarnpkg.com") {
          this.logger.warn("", "Yarn's registry proxy is broken, replacing with public npm registry");
          this.logger.warn("", "If you don't have an npm token, you should exit and run `npm login`");
          this.conf.set("registry", "https://registry.npmjs.org/", "cli");
        }
        const distTag = this.getDistTag();
        if (distTag) {
          this.conf.set("tag", distTag.trim(), "cli");
        }
        this.hasRootedLeaf = !!this.projectGraph.nodes[this.project.manifest.name];
        if (this.hasRootedLeaf) {
          this.logger.info("publish", "rooted leaf detected, skipping synthetic root lifecycles");
        }
        this.runPackageLifecycle = createRunner(this.options);
        this.runRootLifecycle = /^(pre|post)?publish$/.test(process.env.npm_lifecycle_event) ? (stage) => {
          this.logger.warn("lifecycle", "Skipping root %j because it has already been called", stage);
        } : (stage) => this.runPackageLifecycle(this.project.manifest, stage);
        this.projectsWithPackage = Object.values(this.projectGraph.nodes).filter((node) => !!node.package);
        this.projectsWithPackage.map((node) => {
          const interpolateStr = (str) => {
            const res = interpolate(str, {
              projectRoot: node.data.root,
              projectName: node.name,
              workspaceRoot: this.project.rootPath
            });
            this.logger.verbose(
              "silly",
              `Interpolated string "%s" for node "%s" to produce "%s"`,
              str,
              node.name,
              res
            );
            return res;
          };
          const pkg = getPackage(node);
          if (this.options.contents) {
            pkg.contents = this.options.contents;
          }
          if (pkg.lernaConfig?.command?.publish?.directory) {
            pkg.contents = interpolateStr(pkg.lernaConfig.command.publish.directory);
          } else if (this.project.config.command?.publish?.["directory"]) {
            pkg.contents = interpolateStr(this.project.config.command.publish["directory"]);
          }
          if (pkg.lernaConfig?.command?.publish?.assets) {
            pkg.lernaConfig.command.publish.assets = pkg.lernaConfig.command.publish.assets.map(
              (asset) => interpolateAsset(asset, interpolateStr)
            );
          } else if (this.project.config.command?.publish?.["assets"]) {
            const assets = this.project.config.command?.publish?.["assets"].map(
              (asset) => interpolateAsset(asset, interpolateStr)
            );
            pkg.lernaConfig = pkg.lernaConfig || {};
            pkg.lernaConfig.command = pkg.lernaConfig.command || {};
            pkg.lernaConfig.command.publish = pkg.lernaConfig.command.publish || {};
            pkg.lernaConfig.command.publish.assets = assets;
          }
        });
        let result;
        if (this.options.bump === "from-git") {
          result = await this.detectFromGit();
        } else if (this.options.bump === "from-package") {
          result = await this.detectFromPackage();
        } else if (this.options.canary) {
          result = await this.detectCanaryVersions();
        } else {
          result = await versionCommand(this.argv, {
            projectFileMap: this.projectFileMap,
            projectGraph: this.projectGraph
          });
        }
        if (!result) {
          return false;
        }
        if (!result.updates.length) {
          this.logger.success("", "No changed packages to publish");
          return false;
        }
        this.updates = this.filterPrivatePkgUpdates(result.updates);
        this.updatesVersions = new Map(result.updatesVersions);
        function interpolateAsset(asset, interpolationFn) {
          if (typeof asset === "string") {
            return interpolationFn(asset);
          }
          if (asset.from) {
            asset.from = interpolationFn(asset.from);
          }
          if (asset.to) {
            asset.to = interpolationFn(asset.to);
          }
          return asset;
        }
        this.packagesToPublish = this.updates.map((node) => getPackage(node));
        if (result.needsConfirmation) {
          return this.confirmPublish();
        }
        return true;
      }
      async execute() {
        this.enableProgressBar();
        this.logger.info("publish", "Publishing packages to npm...");
        await this.prepareRegistryActions();
        await this.prepareLicenseActions();
        this.preparePrivatePackages();
        if (this.options.canary) {
          await this.updateCanaryVersions();
        }
        await this.resolveLocalDependencyLinks();
        await this.resolveWorkspaceDependencyLinks();
        this.annotateGitHead();
        await this.serializeChanges();
        await this.packUpdated();
        await this.publishPacked();
        this.restorePrivatePackages();
        await this.serializeChanges();
        if (this.gitReset) {
          await this.resetChanges();
        }
        if (this.options.tempTag) {
          await this.npmUpdateAsLatest();
        }
        const count = this.publishedPackages.length;
        const publishedPackagesSorted = this.publishedPackages.sort((a, b) => a.name.localeCompare(b.name));
        if (!count) {
          this.logger.success("", "All packages have already been published.");
          return;
        }
        output("Successfully published:");
        if (this.options.summaryFile !== void 0) {
          const filePath = this.options.summaryFile ? `${this.options.summaryFile}/lerna-publish-summary.json` : "./lerna-publish-summary.json";
          const jsonObject = publishedPackagesSorted.map((pkg) => {
            return {
              packageName: pkg.name,
              version: pkg.version
            };
          });
          output(jsonObject);
          try {
            import_fs6.default.writeFileSync(filePath, JSON.stringify(jsonObject));
            output("Publish summary created: ", filePath);
          } catch (error) {
            output("Failed to create the summary report", error);
          }
        } else {
          const message = publishedPackagesSorted.map((pkg) => ` - ${pkg.name}@${pkg.version}`);
          output(message.join(import_os5.default.EOL));
        }
        this.logger.success("published", "%d %s", count, count === 1 ? "package" : "packages");
        if (this.uniqueProvenanceUrls.size > 0) {
          output("The following provenance transparency log entries were created during publishing:");
          const message = Array.from(this.uniqueProvenanceUrls).map((url2) => ` - ${url2}`);
          output(message.join(import_os5.default.EOL));
        }
      }
      verifyWorkingTreeClean() {
        return describeRef(this.execOpts).then(throwIfUncommitted);
      }
      async detectFromGit() {
        const matchingPattern = this.project.isIndependent() ? "*@*" : `${this.tagPrefix}*.*.*`;
        try {
          await this.verifyWorkingTreeClean();
        } catch (err) {
          if (err.failed && /git describe/.test(err.command)) {
            this.logger.silly("EWORKINGTREE", err.message);
            this.logger.notice("FYI", "Unable to verify working tree, proceed at your own risk");
          } else {
            throw err;
          }
        }
        const taggedPackageNames = await getCurrentTags(this.execOpts, matchingPattern);
        let updates;
        let updatesVersions;
        if (!taggedPackageNames.length) {
          this.logger.notice("from-git", "No tagged release found");
          updates = [];
        } else if (this.project.isIndependent()) {
          updates = [];
          updatesVersions = [];
          taggedPackageNames.forEach((tag) => {
            const npaResult = (0, import_npm_package_arg8.default)(tag);
            const node = this.projectsWithPackage.find((node2) => getPackage(node2).name === npaResult.name);
            updates.push(node);
            updatesVersions.push([node.name, getPackage(node).version || npaResult.rawSpec]);
          });
        } else {
          updates = await getProjectsWithTaggedPackages(
            this.projectsWithPackage,
            this.projectFileMap,
            this.execOpts
          );
          updatesVersions = updates.map((node) => [node.name, getPackage(node).version]);
        }
        updates = this.filterPrivatePkgUpdates(updates);
        return {
          updates,
          updatesVersions,
          needsConfirmation: true
        };
      }
      async detectFromPackage() {
        try {
          await this.verifyWorkingTreeClean();
        } catch (err) {
          if (err.failed && /git describe/.test(err.command)) {
            this.logger.silly("EWORKINGTREE", err.message);
            this.logger.notice("FYI", "Unable to verify working tree, proceed at your own risk");
            process.exitCode = 0;
          } else {
            throw err;
          }
        }
        let updates;
        updates = await getProjectsWithUnpublishedPackages(this.projectsWithPackage, this.conf.snapshot);
        updates = this.filterPrivatePkgUpdates(updates);
        if (!updates.length) {
          this.logger.notice("from-package", "No unpublished release found");
        }
        const updatesVersions = updates.map((node) => [node.name, getPackage(node).version]);
        return {
          updates,
          updatesVersions,
          needsConfirmation: true
        };
      }
      async detectCanaryVersions() {
        const { cwd } = this.execOpts;
        const {
          bump = "prepatch",
          preid = "alpha",
          ignoreChanges,
          forcePublish,
          includeMergedTags
        } = this.options;
        const release = bump.startsWith("pre") ? bump.replace("release", "patch") : `pre${bump}`;
        try {
          await this.verifyWorkingTreeClean();
        } catch (err) {
          if (err.failed && /git describe/.test(err.command)) {
            this.logger.silly("EWORKINGTREE", err.message);
            this.logger.notice("FYI", "Unable to verify working tree, proceed at your own risk");
          } else {
            throw err;
          }
        }
        const updates = this.filterPrivatePkgUpdates(
          collectProjectUpdates(this.projectsWithPackage, this.projectGraph, this.execOpts, {
            bump: "prerelease",
            canary: true,
            ignoreChanges,
            forcePublish,
            includeMergedTags
          })
        );
        const makeVersion = (fallback) => ({ lastVersion = fallback, refCount, sha }) => {
          const nextVersion = import_semver8.default.inc(
            lastVersion.replace(this.tagPrefix, ""),
            release.replace("pre", "")
          );
          return `${nextVersion}-${preid}.${Math.max(0, refCount - 1)}+${sha}`;
        };
        let updatesVersions;
        if (this.project.isIndependent()) {
          updatesVersions = await (0, import_p_map6.default)(
            updates,
            (node) => describeRef(
              {
                match: `${getPackage(node).name}@*`,
                cwd
              },
              includeMergedTags
            ).then(makeVersion(getPackage(node).version)).then((version) => [node.name, version])
          );
        } else {
          updatesVersions = await describeRef(
            {
              match: `${this.tagPrefix}*.*.*`,
              cwd
            },
            includeMergedTags
          ).then(makeVersion(this.project.version)).then((version) => updates.map((node) => [node.name, version]));
        }
        return {
          updates,
          updatesVersions,
          needsConfirmation: true
        };
      }
      confirmPublish() {
        const count = this.updates.length;
        const message = this.updates.map((node) => {
          const pkg = getPackage(node);
          const version = this.updatesVersions.get(node.name);
          return ` - ${pkg.name} => ${version}${pkg.private ? " (private!)" : ""}`;
        });
        output("");
        output(`Found ${count} ${count === 1 ? "package" : "packages"} to publish:`);
        output(message.join(import_os5.default.EOL));
        output("");
        if (this.options.yes) {
          this.logger.info("auto-confirmed", "");
          return true;
        }
        return promptConfirmation("Are you sure you want to publish these packages?");
      }
      preparePrivatePackages() {
        this.privatePackagesToPublish = [];
        this.packagesToPublish.forEach((pkg) => {
          if (pkg.private) {
            pkg.removePrivate();
            this.privatePackagesToPublish.push(pkg);
          }
        });
      }
      restorePrivatePackages() {
        this.privatePackagesToPublish.forEach((pkg) => {
          pkg.private = true;
        });
      }
      async prepareLicenseActions() {
        const packagesWithoutLicense = await getPackagesWithoutLicense(this.project, this.packagesToPublish);
        if (packagesWithoutLicense.length && !this.project.licensePath) {
          this.packagesToBeLicensed = [];
          const names = packagesWithoutLicense.map((pkg) => pkg.name);
          const noun = names.length > 1 ? "Packages" : "Package";
          const verb = names.length > 1 ? "are" : "is";
          const list2 = names.length > 1 ? `${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]}` : names[0];
          this.logger.warn(
            "ENOLICENSE",
            "%s %s %s missing a license.\n%s\n%s",
            noun,
            list2,
            verb,
            "One way to fix this is to add a LICENSE.md file to the root of this repository.",
            "See https://choosealicense.com for additional guidance."
          );
        } else {
          this.packagesToBeLicensed = packagesWithoutLicense;
        }
      }
      async prepareRegistryActions() {
        if (this.conf.get("registry") !== "https://registry.npmjs.org/") {
          this.logger.notice("", "Skipping all user and access validation due to third-party registry");
          this.logger.notice("", "Make sure you're authenticated properly \xAF\\_(\u30C4)_/\xAF");
          return;
        }
        if (process.env.LERNA_INTEGRATION) {
          return;
        }
        if (this.verifyAccess) {
          const username = await getNpmUsername(this.conf.snapshot);
          if (username) {
            await verifyNpmPackageAccess(this.packagesToPublish, username, this.conf.snapshot);
          }
          this.twoFactorAuthRequired = await getTwoFactorAuthRequired(this.conf.snapshot);
        }
      }
      async updateCanaryVersions() {
        await (0, import_p_map6.default)(this.updates, (node) => {
          const pkg = getPackage(node);
          pkg.set("version", this.updatesVersions.get(node.name));
          const dependencies = this.projectGraph.localPackageDependencies[node.name] || [];
          dependencies.forEach((dep) => {
            const depPkg = getPackage(this.projectGraph.nodes[dep.target]);
            const depVersion = this.updatesVersions.get(dep.target) || depPkg.version;
            pkg.updateLocalDependency(dep.targetResolvedNpaResult, depVersion, this.savePrefix);
          });
        });
      }
      async resolveLocalDependencyLinks() {
        const updatesWithLocalLinks = this.updates.filter((node) => {
          const dependencies = this.projectGraph.localPackageDependencies[node.name] || [];
          return dependencies.some((dep) => dep.targetResolvedNpaResult.type === "directory");
        });
        await (0, import_p_map6.default)(updatesWithLocalLinks, (node) => {
          const pkg = getPackage(node);
          const dependencies = this.projectGraph.localPackageDependencies[node.name] || [];
          dependencies.forEach((dep) => {
            const depPkg = getPackage(this.projectGraph.nodes[dep.target]);
            const depVersion = this.updatesVersions.get(dep.target) || depPkg.version;
            pkg.updateLocalDependency(dep.targetResolvedNpaResult, depVersion, this.savePrefix);
          });
        });
      }
      async resolveWorkspaceDependencyLinks() {
        const updatesWithWorkspaceLinks = this.updates.filter((node) => {
          const dependencies = this.projectGraph.localPackageDependencies[node.name] || [];
          return dependencies.some((dep) => !!dep.targetResolvedNpaResult.workspaceSpec);
        });
        await (0, import_p_map6.default)(updatesWithWorkspaceLinks, (node) => {
          const pkg = getPackage(node);
          const dependencies = this.projectGraph.localPackageDependencies[node.name] || [];
          dependencies.forEach((dep) => {
            const depPkg = getPackage(this.projectGraph.nodes[dep.target]);
            const resolved = dep.targetResolvedNpaResult;
            if (resolved.workspaceSpec) {
              let depVersion;
              let savePrefix;
              if (resolved.workspaceAlias) {
                depVersion = this.updatesVersions.get(dep.target) || depPkg.version;
                savePrefix = resolved.workspaceAlias === "*" ? "" : resolved.workspaceAlias;
              } else {
                const specMatch = resolved.workspaceSpec.match(/^workspace:([~^]?)(.*)/);
                savePrefix = specMatch[1];
                depVersion = this.updatesVersions.get(dep.target) || depPkg.version;
              }
              pkg.updateLocalDependency(resolved, depVersion, savePrefix, { retainWorkspacePrefix: false });
            }
          });
        });
      }
      annotateGitHead() {
        try {
          const gitHead = this.options.gitHead || getCurrentSHA(this.execOpts);
          for (const pkg of this.packagesToPublish) {
            pkg.set("gitHead", gitHead);
          }
        } catch (err) {
          this.logger.silly("EGITHEAD", err.message);
          this.logger.notice(
            "FYI",
            "Unable to set temporary gitHead property, it will be missing from registry metadata"
          );
        }
      }
      async serializeChanges() {
        await (0, import_p_map6.default)(this.packagesToPublish, (pkg) => pkg.serialize());
      }
      async resetChanges() {
        const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || import_devkit8.workspaceRoot;
        const gitOpts = {
          granularPathspec: this.options.granularPathspec !== false
        };
        const dirtyManifests = [this.project.manifest].concat(this.packagesToPublish).map((pkg) => import_path22.default.relative(_workspaceRoot, pkg.manifestLocation));
        try {
          await gitCheckout(dirtyManifests, gitOpts, this.execOpts);
        } catch (err) {
          this.logger.silly("EGITCHECKOUT", err.message);
          this.logger.notice("FYI", "Unable to reset working tree changes, this probably isn't a git repo.");
        }
      }
      execScript(pkg, script) {
        const scriptLocation = import_path22.default.join(pkg.location, "scripts", script);
        try {
          require(scriptLocation);
        } catch (ex) {
          this.logger.silly("execScript", `No ${script} script found at ${scriptLocation}`);
        }
        return pkg;
      }
      async removeTempLicensesOnError() {
        await removeTempLicenses(this.packagesToBeLicensed).catch((removeError) => {
          this.logger.error(
            "licenses",
            "error removing temporary license files",
            removeError.stack || removeError
          );
        });
      }
      async requestOneTimePassword() {
        if (this.otpCache.otp) {
          return;
        }
        const otp = await getOneTimePassword("Enter OTP:");
        this.otpCache.otp = otp;
      }
      topoMapPackages(mapper) {
        return runProjectsTopologically(this.updates, this.projectGraph, (node) => mapper(getPackage(node)), {
          concurrency: this.concurrency,
          rejectCycles: this.options.rejectCycles
        });
      }
      async packUpdated() {
        const tracker = this.logger.newItem("npm pack");
        tracker.addWork(this.packagesToPublish.length);
        await createTempLicenses(this.project.licensePath, this.packagesToBeLicensed);
        if (!this.hasRootedLeaf) {
          await this.runRootLifecycle("prepublish");
          await this.runPackageLifecycle(this.project.manifest, "prepare");
          await this.runPackageLifecycle(this.project.manifest, "prepublishOnly");
          await this.runPackageLifecycle(this.project.manifest, "prepack");
        }
        const opts = this.conf.snapshot;
        const mapper = (0, import_p_pipe.default)(
          ...[
            this.options.requireScripts && ((pkg) => this.execScript(pkg, "prepublish")),
            (pkg) => this.copyAssets(pkg).then(() => pkg),
            (pkg) => pulseTillDone(packDirectory(pkg, pkg.location, opts)).then((packed) => {
              tracker.verbose("packed", import_path22.default.relative(this.project.rootPath, pkg.contents));
              tracker.completeWork(1);
              pkg.packed = packed;
              return pkg.refresh();
            })
          ].filter(Boolean)
        );
        if (this.toposort) {
          await this.topoMapPackages(mapper).catch((err) => {
            this.removeTempLicensesOnError();
            throw err;
          });
        } else {
          await (0, import_p_map6.default)(this.packagesToPublish, mapper, { concurrency: this.concurrency });
        }
        await removeTempLicenses(this.packagesToBeLicensed);
        if (!this.hasRootedLeaf) {
          await this.runPackageLifecycle(this.project.manifest, "postpack");
        }
        tracker.finish();
      }
      async publishPacked() {
        this.publishedPackages = [];
        const tracker = this.logger.newItem("publish");
        tracker.addWork(this.packagesToPublish.length);
        let chain = Promise.resolve();
        if (this.twoFactorAuthRequired) {
          chain = chain.then(() => this.requestOneTimePassword());
        }
        const opts = Object.assign(this.conf.snapshot, {
          // distTag defaults to "latest" OR whatever is in pkg.publishConfig.tag
          // if we skip temp tags we should tag with the proper value immediately
          tag: this.options.tempTag ? "lerna-temp" : this.conf.get("tag")
        });
        const logListener = (...args) => {
          const str = args.join(" ");
          if (str.toLowerCase().includes("provenance statement") && str.includes("https://")) {
            const url2 = str.match(/https:\/\/[^ ]+/)[0];
            this.uniqueProvenanceUrls.add(url2);
          }
        };
        process.on("log", logListener);
        const mapper = (0, import_p_pipe.default)(
          ...[
            (pkg) => {
              const preDistTag = this.getPreDistTag(pkg);
              const tag = !this.options.tempTag && preDistTag ? preDistTag : opts.tag;
              const pkgOpts = Object.assign({}, opts, { tag });
              return pulseTillDone(npmPublish(pkg, pkg.packed.tarFilePath, pkgOpts, this.otpCache)).then(() => {
                this.publishedPackages.push(pkg);
                tracker.success("published", pkg.name, pkg.version);
                tracker.completeWork(1);
                logPacked(pkg.packed);
                return pkg;
              }).catch((err) => {
                if (err.code === "EPUBLISHCONFLICT" || err.code === "E403" && err.body?.error?.includes("You cannot publish over the previously published versions")) {
                  tracker.warn("publish", `Package is already published: ${pkg.name}@${pkg.version}`);
                  tracker.completeWork(1);
                  return pkg;
                }
                this.logger.silly("", err);
                this.logger.warn("notice", `Package failed to publish: ${pkg.name}`);
                this.logger.error(err.code, err.body && err.body.error || err.message);
                err.name = "ValidationError";
                if ("errno" in err && typeof err.errno === "number" && Number.isFinite(err.errno)) {
                  process.exitCode = err.errno;
                } else {
                  this.logger.error("", `errno "${err.errno}" is not a valid exit code - exiting with code 1`);
                  process.exitCode = 1;
                }
                throw err;
              });
            },
            this.options.requireScripts && ((pkg) => this.execScript(pkg, "postpublish"))
          ].filter(Boolean)
        );
        chain = chain.then(() => {
          if (this.toposort) {
            return this.topoMapPackages(mapper);
          } else {
            return (0, import_p_map6.default)(this.packagesToPublish, mapper, { concurrency: this.concurrency });
          }
        });
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runRootLifecycle("publish"));
          chain = chain.then(() => this.runRootLifecycle("postpublish"));
        }
        return chain.finally(() => {
          process.removeListener("log", logListener);
          tracker.finish();
        });
      }
      async npmUpdateAsLatest() {
        const tracker = this.logger.newItem("npmUpdateAsLatest");
        tracker.addWork(this.updates.length);
        tracker.showProgress();
        const opts = this.conf.snapshot;
        const getDistTag = (publishConfig) => {
          if (opts.tag === "latest" && publishConfig && publishConfig.tag) {
            return publishConfig.tag;
          }
          return opts.tag;
        };
        const mapper = (pkg) => {
          const spec = `${pkg.name}@${pkg.version}`;
          const preDistTag = this.getPreDistTag(pkg);
          const distTag = preDistTag || getDistTag(pkg.get("publishConfig"));
          return Promise.resolve().then(() => pulseTillDone(npmDistTag.remove(spec, "lerna-temp", opts, this.otpCache))).then(() => pulseTillDone(npmDistTag.add(spec, distTag, opts, this.otpCache))).then(() => {
            tracker.success("dist-tag", "%s@%s => %j", pkg.name, pkg.version, distTag);
            tracker.completeWork(1);
            return pkg;
          });
        };
        if (this.toposort) {
          await this.topoMapPackages(mapper);
        } else {
          await (0, import_p_map6.default)(this.packagesToPublish, mapper, { concurrency: this.concurrency });
        }
        tracker.finish();
      }
      getDistTag() {
        if (this.options.distTag) {
          return this.options.distTag;
        }
        if (this.options.canary) {
          return "canary";
        }
        return void 0;
      }
      getPreDistTag(pkg) {
        if (!this.options.preDistTag) {
          return;
        }
        const isPrerelease = prereleaseIdFromVersion(pkg.version);
        if (isPrerelease) {
          return this.options.preDistTag;
        }
      }
      // filter out private packages, respecting the --include-private option
      filterPrivatePkgUpdates(updates) {
        const privatePackagesToInclude = new Set(this.options.includePrivate || []);
        return updates.filter(
          (node) => !getPackage(node).private || privatePackagesToInclude.has("*") || privatePackagesToInclude.has(getPackage(node).name)
        );
      }
      async copyAssets(pkg) {
        if (!pkg.lernaConfig?.command?.publish?.assets) {
          return;
        }
        if ((0, import_path22.normalize)(pkg.location) === (0, import_path22.normalize)(pkg.contents)) {
          return;
        }
        const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || import_devkit8.workspaceRoot;
        const assets = pkg.lernaConfig?.command?.publish?.assets;
        const filesToCopy = [];
        const getFiles = (glob) => (0, import_globby3.default)(glob, {
          cwd: pkg.location,
          onlyFiles: false,
          expandDirectories: false
        });
        for (const asset of assets) {
          if (typeof asset === "string") {
            const files = await getFiles(asset);
            this.logger.verbose("publish", "Expanded asset glob %s into files %j", asset, files);
            for (const file of files) {
              filesToCopy.push({
                from: (0, import_path22.join)(pkg.location, file),
                to: (0, import_path22.join)(pkg.contents, file)
              });
            }
          } else if (asset.from && typeof asset.from === "string" && asset.to && typeof asset.to === "string") {
            const files = await getFiles(asset.from);
            this.logger.verbose("publish", "Expanded asset glob %s into files %j", asset.from, files);
            for (const file of files) {
              filesToCopy.push({
                from: (0, import_path22.join)(pkg.location, file),
                to: (0, import_path22.join)(pkg.contents, asset.to, (0, import_path22.basename)(file))
              });
            }
          } else {
            throw new ValidationError(
              "EINVALIDASSETS",
              "Asset configuration must be a plain string or object with both `from` and `to` string properties."
            );
          }
        }
        for (const file of filesToCopy) {
          if ((0, import_path22.normalize)(file.from) === (0, import_path22.normalize)(file.to)) {
            this.logger.warn(
              "EPUBLISHASSET",
              "Asset %s is already in package directory",
              file.from.replace(`${_workspaceRoot}/`, "")
            );
          } else if ((0, import_fs6.existsSync)(file.from)) {
            this.logger.verbose(
              "publish",
              "Copying asset %s to %s",
              file.from.replace(`${_workspaceRoot}/`, ""),
              file.to.replace(`${_workspaceRoot}/`, "")
            );
            await (0, import_fs_extra10.copy)(file.from, file.to);
          } else {
            this.logger.warn(
              "EPUBLISHASSET",
              "Asset %s does not exist",
              file.from.replace(`${_workspaceRoot}/`, "")
            );
          }
        }
      }
    };
    module2.exports.PublishCommand = PublishCommand;
  }
});

// packages/lerna/src/commands/publish/index.ts
var publishIndex = require_src2();
module.exports = publishIndex;
module.exports.PublishCommand = publishIndex.PublishCommand;