"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UIROOT_ASPECT_IDS = exports.BundleUiTask = exports.BUNDLE_UI_TASK_NAME = exports.BUNDLE_UI_HASH_FILENAME = exports.BUNDLE_UI_DIR = exports.BUNDLE_UIROOT_DIR = void 0;
exports.getUiRootEntryName = getUiRootEntryName;
exports.getUiRootHtmlFilename = getUiRootHtmlFilename;
function _path() {
  const data = require("path");
  _path = function () {
    return data;
  };
  return data;
}
function _pMapSeries() {
  const data = _interopRequireDefault(require("p-map-series"));
  _pMapSeries = function () {
    return data;
  };
  return data;
}
function _fs() {
  const data = require("fs");
  _fs = function () {
    return data;
  };
  return data;
}
function _ui() {
  const data = require("./ui.aspect");
  _ui = 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); }
const BUNDLE_UI_TASK_NAME = exports.BUNDLE_UI_TASK_NAME = 'BundleUI';
const BUNDLE_UI_DIR = exports.BUNDLE_UI_DIR = 'ui-bundle';
const UIROOT_ASPECT_IDS = exports.UIROOT_ASPECT_IDS = {
  SCOPE: 'teambit.scope/scope',
  WORKSPACE: 'teambit.workspace/workspace'
};
const BUNDLE_UIROOT_DIR = exports.BUNDLE_UIROOT_DIR = {
  [UIROOT_ASPECT_IDS.SCOPE]: 'scope',
  [UIROOT_ASPECT_IDS.WORKSPACE]: 'workspace'
};
const BUNDLE_UI_HASH_FILENAME = exports.BUNDLE_UI_HASH_FILENAME = '.hash';

/**
 * Both UI roots are bundled by a single rspack compilation, one entry each, so the roots share
 * every chunk they have in common instead of each shipping a full copy of the app. The entry name
 * is the root's short name, and each entry gets its own html naming the chunks only it needs.
 */
function getUiRootEntryName(uiRootAspectId) {
  // a root outside the two bit ships still gets a usable entry name rather than failing the build.
  return BUNDLE_UIROOT_DIR[uiRootAspectId] || uiRootAspectId.replace(/[^a-zA-Z0-9-]+/g, '-');
}
function getUiRootHtmlFilename(uiRootAspectId) {
  return `${getUiRootEntryName(uiRootAspectId)}.html`;
}
class BundleUiTask {
  constructor(ui, logger) {
    this.ui = ui;
    this.logger = logger;
    _defineProperty(this, "aspectId", 'teambit.ui-foundation/ui');
    _defineProperty(this, "name", BUNDLE_UI_TASK_NAME);
    _defineProperty(this, "location", 'end');
  }
  async execute(context) {
    const capsule = context.capsuleNetwork.seedersCapsules.find(c => c.component.id.toStringWithoutVersion() === _ui().UIAspect.id);
    if (!capsule) {
      return {
        componentsResults: []
      };
    }
    const outputPath = (0, _path().join)(capsule.path, BundleUiTask.getArtifactDirectory());
    this.logger.info(`Generating UI bundle at ${outputPath}...`);
    // one call, one compilation: `build()` turns every registered UI root into an entry of the same
    // rspack build, so the chunks the roots share are emitted once. there is no second compilation
    // to keep alive, so nothing here has to defer closing it.
    await this.ui.build(undefined, outputPath);
    await this.generateHash(outputPath);
    return {
      componentsResults: [],
      artifacts: BundleUiTask.getArtifactDef()
    };
  }

  /**
   * One hash file for the whole bundle, mapping each root aspect id to the hash of the aspects that
   * root resolved. `bit start` looks up the root it is about to serve; a root missing from the map
   * (or a bundle built before this layout) reads as "no pre-bundle" and falls back to a local build.
   */
  async generateHash(outputPath) {
    const hashes = {};
    await (0, _pMapSeries().default)(Object.values(UIROOT_ASPECT_IDS), async uiRootAspectId => {
      const maybeUiRoot = this.ui.getUi(uiRootAspectId);
      if (!maybeUiRoot) throw new Error(`no uiRoot found for ${uiRootAspectId}`);
      const [, uiRoot] = maybeUiRoot;
      hashes[uiRootAspectId] = await this.ui.createBundleUiHash(uiRoot);
    });
    if (!(0, _fs().existsSync)(outputPath)) (0, _fs().mkdirSync)(outputPath, {
      recursive: true
    });
    (0, _fs().writeFileSync)((0, _path().join)(outputPath, BUNDLE_UI_HASH_FILENAME), JSON.stringify(hashes, null, 2));
  }
  static getArtifactDirectory() {
    return (0, _path().join)('artifacts', BUNDLE_UI_DIR);
  }
  static getArtifactDef() {
    return [{
      name: BUNDLE_UI_DIR,
      globPatterns: [`${BundleUiTask.getArtifactDirectory()}/**`]
    }];
  }
}
exports.BundleUiTask = BundleUiTask;

//# sourceMappingURL=bundle-ui.task.js.map