'use strict';

var chalk = require('chalk');
var path = require('path');
var createDistWorkspace = require('./createDistWorkspace-CLrZPAfL.cjs.js');
var index = require('./index-CCLafGQH.cjs.js');
var cliNode = require('@backstage/cli-node');
var parallel = require('./parallel-BszNaKyc.cjs.js');
var buildBackend = require('./buildBackend-Cv6N14cB.cjs.js');
require('fs-extra');
require('p-limit');
require('os');
require('tar');
require('lodash/partition');
require('./run-BcxUFacd.cjs.js');
require('child_process');
require('util');
require('@backstage/errors');
require('rollup');
require('@rollup/plugin-commonjs');
require('@rollup/plugin-node-resolve');
require('rollup-plugin-postcss');
require('rollup-plugin-esbuild');
require('@svgr/rollup');
require('rollup-plugin-dts');
require('@rollup/plugin-json');
require('@rollup/plugin-yaml');
require('rollup-pluginutils');
require('./svgrTemplate-BTjBQ3by.cjs.js');
require('./entryPoints-CoHH4lBA.cjs.js');
require('./productionPack-DotlEIE2.cjs.js');
require('npm-packlist');
require('commander');
require('semver');
require('@backstage/cli-common');
require('worker_threads');
require('webpack');
require('eslint-webpack-plugin');
require('fork-ts-checker-webpack-plugin');
require('html-webpack-plugin');
require('react-dev-utils/ModuleScopePlugin');
require('run-script-webpack-plugin');
require('@manypkg/get-packages');
require('webpack-node-externals');
require('./packageDetection-C__AGK-g.cjs.js');
require('lodash/pickBy');
require('mini-css-extract-plugin');
require('@pmmmwh/react-refresh-webpack-plugin');
require('yn');
require('@backstage/config');
require('chokidar');
require('p-queue');
require('react-dev-utils/FileSizeReporter');
require('react-dev-utils/formatWebpackMessages');
require('lodash/uniq');
require('react-dev-utils/openBrowser');
require('webpack-dev-server');
require('@yarnpkg/parsers');
require('@yarnpkg/lockfile');
require('minimatch');
require('./yarn-BDZCENk5.cjs.js');
require('./config-OeQcmdz6.cjs.js');
require('@backstage/config-loader');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }

var chalk__default = /*#__PURE__*/_interopDefaultCompat(chalk);

function createScriptOptionsParser(anyCmd, commandPath) {
  let rootCmd = anyCmd;
  while (rootCmd.parent) {
    rootCmd = rootCmd.parent;
  }
  let targetCmd = rootCmd;
  for (const name of commandPath) {
    targetCmd = targetCmd == null ? void 0 : targetCmd.commands.find((c) => c.name() === name);
  }
  if (!targetCmd) {
    throw new Error(
      `Could not find package command '${commandPath.join(" ")}'`
    );
  }
  const cmd = targetCmd;
  const expectedScript = `backstage-cli ${commandPath.join(" ")}`;
  return (scriptStr) => {
    if (!scriptStr || !scriptStr.startsWith(expectedScript)) {
      return void 0;
    }
    const argsStr = scriptStr.slice(expectedScript.length).trim();
    const currentOpts = cmd._optionValues;
    const currentStore = cmd._storeOptionsAsProperties;
    const result = {};
    cmd._storeOptionsAsProperties = false;
    cmd._optionValues = result;
    cmd.parseOptions(argsStr.split(" "));
    cmd._storeOptionsAsProperties = currentOpts;
    cmd._optionValues = currentStore;
    return result;
  };
}
async function command(opts, cmd) {
  let packages = await cliNode.PackageGraph.listTargetPackages();
  if (opts.since) {
    const graph = cliNode.PackageGraph.fromPackages(packages);
    const changedPackages = await graph.listChangedPackages({
      ref: opts.since,
      analyzeLockfile: true
    });
    const withDevDependents = graph.collectPackageNames(
      changedPackages.map((pkg) => pkg.name),
      (pkg) => pkg.localDevDependents.keys()
    );
    packages = Array.from(withDevDependents).map((name) => graph.get(name));
  }
  const apps = new Array();
  const backends = new Array();
  const parseBuildScript = createScriptOptionsParser(cmd, ["package", "build"]);
  const options = packages.flatMap((pkg) => {
    var _a, _b, _c;
    const role = (_b = (_a = pkg.packageJson.backstage) == null ? void 0 : _a.role) != null ? _b : cliNode.PackageRoles.detectRoleFromPackage(pkg.packageJson);
    if (!role) {
      console.warn(`Ignored ${pkg.packageJson.name} because it has no role`);
      return [];
    }
    if (role === "frontend") {
      apps.push(pkg);
      return [];
    } else if (role === "backend") {
      backends.push(pkg);
      return [];
    }
    const outputs = createDistWorkspace.getOutputsForRole(role);
    if (outputs.size === 0) {
      console.warn(`Ignored ${pkg.packageJson.name} because it has no output`);
      return [];
    }
    const buildOptions = parseBuildScript((_c = pkg.packageJson.scripts) == null ? void 0 : _c.build);
    if (!buildOptions) {
      console.warn(
        `Ignored ${pkg.packageJson.name} because it does not have a matching build script`
      );
      return [];
    }
    return {
      targetDir: pkg.dir,
      packageJson: pkg.packageJson,
      outputs,
      logPrefix: `${chalk__default.default.cyan(path.relative(index.paths.targetRoot, pkg.dir))}: `,
      minify: buildOptions.minify
    };
  });
  console.log("Building packages");
  await createDistWorkspace.buildPackages(options);
  if (opts.all) {
    console.log("Building apps");
    await parallel.runParallelWorkers({
      items: apps,
      parallelismFactor: 1 / 2,
      worker: async (pkg) => {
        var _a, _b;
        const buildOptions = parseBuildScript((_a = pkg.packageJson.scripts) == null ? void 0 : _a.build);
        if (!buildOptions) {
          console.warn(
            `Ignored ${pkg.packageJson.name} because it does not have a matching build script`
          );
          return;
        }
        await buildBackend.buildFrontend({
          targetDir: pkg.dir,
          configPaths: (_b = buildOptions.config) != null ? _b : [],
          writeStats: Boolean(buildOptions.stats)
        });
      }
    });
    console.log("Building backends");
    await parallel.runParallelWorkers({
      items: backends,
      parallelismFactor: 1 / 2,
      worker: async (pkg) => {
        var _a;
        const buildOptions = parseBuildScript((_a = pkg.packageJson.scripts) == null ? void 0 : _a.build);
        if (!buildOptions) {
          console.warn(
            `Ignored ${pkg.packageJson.name} because it does not have a matching build script`
          );
          return;
        }
        await buildBackend.buildBackend({
          targetDir: pkg.dir,
          skipBuildDependencies: true,
          minify: buildOptions.minify
        });
      }
    });
  }
}

exports.command = command;
//# sourceMappingURL=build-utVvLEah.cjs.js.map
