"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.WorkspaceMain = void 0;
function _pubsub() {
  const data = require("@teambit/pubsub");
  _pubsub = function () {
    return data;
  };
  return data;
}
function _aspectLoader() {
  const data = require("@teambit/aspect-loader");
  _aspectLoader = function () {
    return data;
  };
  return data;
}
function _bundler() {
  const data = require("@teambit/bundler");
  _bundler = function () {
    return data;
  };
  return data;
}
function _cli() {
  const data = require("@teambit/cli");
  _cli = function () {
    return data;
  };
  return data;
}
function _component() {
  const data = require("@teambit/component");
  _component = function () {
    return data;
  };
  return data;
}
function _envs() {
  const data = require("@teambit/envs");
  _envs = function () {
    return data;
  };
  return data;
}
function _graphql() {
  const data = require("@teambit/graphql");
  _graphql = function () {
    return data;
  };
  return data;
}
function _harmony() {
  const data = require("@teambit/harmony");
  _harmony = function () {
    return data;
  };
  return data;
}
function _isolator() {
  const data = require("@teambit/isolator");
  _isolator = function () {
    return data;
  };
  return data;
}
function _logger() {
  const data = require("@teambit/logger");
  _logger = function () {
    return data;
  };
  return data;
}
function _scope() {
  const data = require("@teambit/scope");
  _scope = function () {
    return data;
  };
  return data;
}
function _ui() {
  const data = require("@teambit/ui");
  _ui = function () {
    return data;
  };
  return data;
}
function _variants() {
  const data = require("@teambit/variants");
  _variants = function () {
    return data;
  };
  return data;
}
function _globalConfig() {
  const data = require("@teambit/global-config");
  _globalConfig = function () {
    return data;
  };
  return data;
}
function _dependencyResolver() {
  const data = require("@teambit/dependency-resolver");
  _dependencyResolver = function () {
    return data;
  };
  return data;
}
function _consumer() {
  const data = require("@teambit/legacy/dist/consumer");
  _consumer = function () {
    return data;
  };
  return data;
}
function _component2() {
  const data = _interopRequireDefault(require("@teambit/legacy/dist/consumer/component"));
  _component2 = function () {
    return data;
  };
  return data;
}
function _extensionData() {
  const data = require("@teambit/legacy/dist/consumer/config/extension-data");
  _extensionData = function () {
    return data;
  };
  return data;
}
function _componentLoader() {
  const data = _interopRequireDefault(require("@teambit/legacy/dist/consumer/component/component-loader"));
  _componentLoader = function () {
    return data;
  };
  return data;
}
function _constants() {
  const data = require("./constants");
  _constants = function () {
    return data;
  };
  return data;
}
function _workspace() {
  const data = require("./workspace.aspect");
  _workspace = function () {
    return data;
  };
  return data;
}
function _ejectConf() {
  const data = _interopRequireDefault(require("./eject-conf.cmd"));
  _ejectConf = function () {
    return data;
  };
  return data;
}
function _workspace2() {
  const data = require("./workspace");
  _workspace2 = function () {
    return data;
  };
  return data;
}
function _workspace3() {
  const data = _interopRequireDefault(require("./workspace.graphql"));
  _workspace3 = function () {
    return data;
  };
  return data;
}
function _workspace4() {
  const data = require("./workspace.ui-root");
  _workspace4 = function () {
    return data;
  };
  return data;
}
function _capsule() {
  const data = require("./capsule.cmd");
  _capsule = function () {
    return data;
  };
  return data;
}
function _envsSet() {
  const data = require("./envs-subcommands/envs-set.cmd");
  _envsSet = function () {
    return data;
  };
  return data;
}
function _envsUnset() {
  const data = require("./envs-subcommands/envs-unset.cmd");
  _envsUnset = function () {
    return data;
  };
  return data;
}
function _pattern() {
  const data = require("./pattern.cmd");
  _pattern = function () {
    return data;
  };
  return data;
}
function _envsReplace() {
  const data = require("./envs-subcommands/envs-replace.cmd");
  _envsReplace = function () {
    return data;
  };
  return data;
}
function _scopeSet() {
  const data = require("./scope-subcommands/scope-set.cmd");
  _scopeSet = function () {
    return data;
  };
  return data;
}
function _use() {
  const data = require("./use.cmd");
  _use = function () {
    return data;
  };
  return data;
}
function _envsUpdate() {
  const data = require("./envs-subcommands/envs-update.cmd");
  _envsUpdate = function () {
    return data;
  };
  return data;
}
function _unuse() {
  const data = require("./unuse.cmd");
  _unuse = function () {
    return data;
  };
  return data;
}
function _localOnlyCmd() {
  const data = require("./commands/local-only-cmd");
  _localOnlyCmd = function () {
    return data;
  };
  return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
class WorkspaceMain {
  static async provider([pubsub, cli, scope, component, isolator, dependencyResolver, variants, loggerExt, graphql, ui, bundler, aspectLoader, envs, globalConfig], config, [onComponentLoadSlot, onComponentChangeSlot, onComponentAddSlot, onComponentRemoveSlot, onAspectsResolveSlot, onRootAspectAddedSlot, onBitmapChangeSlot, onWorkspaceConfigChangeSlot], harmony) {
    const currentCmd = process.argv[2];
    if (currentCmd === 'init') {
      // avoid loading the consumer/workspace for "bit init". otherwise, "bit init --reset" can't fix corrupted .bitmap
      return undefined;
    }
    const bitConfig = harmony.config.get('teambit.harmony/bit');
    const consumer = await getConsumer(bitConfig.cwd);
    if (!consumer) {
      const capsuleCmd = getCapsulesCommands(isolator, scope, undefined);
      cli.register(capsuleCmd);
      return undefined;
    }
    // TODO: get the 'workspace' name in a better way
    const logger = loggerExt.createLogger(_constants().EXT_NAME);
    const workspace = new (_workspace2().Workspace)(pubsub, config, consumer, scope, component, dependencyResolver, variants, aspectLoader, logger, undefined, harmony, onComponentLoadSlot, onComponentChangeSlot, envs, globalConfig, onComponentAddSlot, onComponentRemoveSlot, onAspectsResolveSlot, onRootAspectAddedSlot, graphql, onBitmapChangeSlot, onWorkspaceConfigChangeSlot);
    const configMergeFile = workspace.getConflictMergeFile();
    await configMergeFile.loadIfNeeded();
    const getWorkspacePolicyFromPackageJson = () => {
      const packageJson = workspace.consumer.packageJson?.packageJsonObject || {};
      const policyFromPackageJson = dependencyResolver.getWorkspacePolicyFromPackageJson(packageJson);
      return policyFromPackageJson;
    };

    /**
     * @deprecated
     * see workspace.getWorkspaceJsonConflictFromMergeConfig
     */
    const getWorkspacePolicyFromMergeConfig = () => {
      const wsConfigMerge = workspace.getWorkspaceJsonConflictFromMergeConfig();
      const policy = wsConfigMerge.data?.[_dependencyResolver().DependencyResolverAspect.id]?.policy || {};
      ['dependencies', 'peerDependencies'].forEach(depField => {
        if (!policy[depField]) return;
        policy[depField] = policy[depField].reduce((acc, current) => {
          acc[current.name] = current.version;
          return acc;
        }, {});
      });
      const wsPolicy = dependencyResolver.getWorkspacePolicyFromConfigObject(policy);
      return wsPolicy;
    };
    const getRootPolicy = () => {
      const pkgJsonPolicy = getWorkspacePolicyFromPackageJson();
      const configMergePolicy = getWorkspacePolicyFromMergeConfig();
      return dependencyResolver.mergeWorkspacePolices([pkgJsonPolicy, configMergePolicy]);
    };
    dependencyResolver.registerRootPolicy(getRootPolicy());
    consumer.onCacheClear.push(() => workspace.clearCache());
    _componentLoader().default.registerOnComponentLoadSubscriber(async (legacyComponent, opts) => {
      if (opts?.originatedFromHarmony) return legacyComponent;
      const id = legacyComponent.id;
      const newComponent = await workspace.get(id, legacyComponent, true, true, opts);
      return newComponent.state._consumer;
    });
    _component2().default.registerOnComponentConfigLoading(_constants().EXT_NAME, async (id, loadOpts) => {
      const componentId = await workspace.resolveComponentId(id);
      // We call here directly workspace.scope.get instead of workspace.get because part of the workspace get is loading consumer component
      // which in turn run this event, which will make an infinite loop
      // This component from scope here are only used for merging the extensions with the workspace components
      const componentFromScope = await workspace.scope.get(componentId);
      const {
        extensions
      } = await workspace.componentExtensions(componentId, componentFromScope, undefined, loadOpts);
      const defaultScope = await workspace.componentDefaultScope(componentId);
      const extensionsWithLegacyIdsP = extensions.map(async extension => {
        const legacyEntry = extension.clone();
        if (legacyEntry.extensionId) {
          legacyEntry.newExtensionId = legacyEntry.extensionId;
        }
        return legacyEntry;
      });
      const extensionsWithLegacyIds = await Promise.all(extensionsWithLegacyIdsP);
      return {
        defaultScope,
        extensions: _extensionData().ExtensionDataList.fromArray(extensionsWithLegacyIds)
      };
    });
    const workspaceSchema = (0, _workspace3().default)(workspace, graphql);
    ui.registerUiRoot(new (_workspace4().WorkspaceUIRoot)(workspace, bundler));
    ui.registerPreStart(async () => {
      return workspace.setComponentPathsRegExps();
    });
    graphql.register(workspaceSchema);
    const capsuleCmd = getCapsulesCommands(isolator, scope, workspace);
    const commands = [new (_ejectConf().default)(workspace), capsuleCmd, new (_use().UseCmd)(workspace), new (_unuse().UnuseCmd)(workspace)];
    commands.push(new (_pattern().PatternCommand)(workspace));
    const localOnlyCmd = new (_localOnlyCmd().LocalOnlyCmd)();
    localOnlyCmd.commands = [new (_localOnlyCmd().LocalOnlySetCmd)(workspace), new (_localOnlyCmd().LocalOnlyUnsetCmd)(workspace), new (_localOnlyCmd().LocalOnlyListCmd)(workspace)];
    commands.push(localOnlyCmd);
    cli.register(...commands);
    component.registerHost(workspace);
    cli.registerOnStart(async (_hasWorkspace, currentCommand, commandObject) => {
      const hasSafeModeFlag = process.argv.includes('--safe-mode');
      if (hasSafeModeFlag || commandObject && !commandObject.loadAspects) {
        return;
      }
      if (currentCommand === 'install') {
        workspace.inInstallContext = true;
      }
      await workspace.importCurrentLaneIfMissing();
      logger.profile('workspace.registerOnStart');
      const loadAspectsOpts = {
        runSubscribers: false,
        skipDeps: !config.autoLoadAspectsDeps
      };
      const aspects = await workspace.loadAspects(aspectLoader.getNotLoadedConfiguredExtensions(), undefined, 'teambit.workspace/workspace (cli.registerOnStart)', loadAspectsOpts);
      // clear aspect cache.
      const componentIds = await workspace.resolveMultipleComponentIds(aspects);
      componentIds.forEach(id => {
        workspace.clearComponentCache(id);
      });
      logger.profile('workspace.registerOnStart');
    });

    // add sub-commands "set" and "unset" to envs command.
    const envsCommand = cli.getCommand('envs');
    envsCommand?.commands?.push(new (_envsSet().EnvsSetCmd)(workspace)); // bit envs set
    envsCommand?.commands?.push(new (_envsUnset().EnvsUnsetCmd)(workspace)); // bit envs unset
    envsCommand?.commands?.push(new (_envsReplace().EnvsReplaceCmd)(workspace)); // bit envs replace
    envsCommand?.commands?.push(new (_envsUpdate().EnvsUpdateCmd)(workspace)); // bit envs replace

    // add sub-command "set" to scope command.
    const scopeCommand = cli.getCommand('scope');
    scopeCommand?.commands?.push(new (_scopeSet().ScopeSetCmd)(workspace));
    return workspace;
  }
}
exports.WorkspaceMain = WorkspaceMain;
_defineProperty(WorkspaceMain, "runtime", _cli().MainRuntime);
_defineProperty(WorkspaceMain, "dependencies", [_pubsub().PubsubAspect, _cli().CLIAspect, _scope().ScopeAspect, _component().ComponentAspect, _isolator().IsolatorAspect, _dependencyResolver().DependencyResolverAspect, _variants().VariantsAspect, _logger().LoggerAspect, _graphql().GraphqlAspect, _ui().UIAspect, _bundler().BundlerAspect, _aspectLoader().AspectLoaderAspect, _envs().EnvsAspect, _globalConfig().GlobalConfigAspect]);
_defineProperty(WorkspaceMain, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType()]);
_defineProperty(WorkspaceMain, "defineRuntime", 'browser');
function getCapsulesCommands(isolator, scope, workspace) {
  const capsuleCmd = new (_capsule().CapsuleCmd)(isolator, workspace, scope);
  capsuleCmd.commands = [new (_capsule().CapsuleListCmd)(isolator, workspace, scope), new (_capsule().CapsuleCreateCmd)(workspace, scope, isolator), new (_capsule().CapsuleDeleteCmd)(isolator, scope, workspace)];
  return capsuleCmd;
}

/**
 * don't use loadConsumer() here, which throws ConsumerNotFound because some commands don't require
 * the consumer to be available. such as, `bit init` or `bit list --remote`.
 * most of the commands do need the consumer. the legacy commands that need the consumer throw an
 * error when is missing. in the new/Harmony commands, such as `bis compile`, the workspace object
 * is passed to the provider, so before using it, make sure it exists.
 * keep in mind that you can't verify it in the provider itself, because the provider is running
 * always for all commands before anything else is happening.
 */
async function getConsumer(path) {
  return (0, _consumer().loadConsumerIfExist)(path);
}
_workspace().WorkspaceAspect.addRuntime(WorkspaceMain);
var _default = exports.default = WorkspaceMain;

//# sourceMappingURL=workspace.main.runtime.js.map