import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  readAppManifestFile
} from "./chunk-VJAMKDBT.js";
import {
  ArmTagProvider,
  ExtensionDataProvider,
  SiteOverrideProvider,
  SiteProvider,
  createSiteOverrides,
  useARMClient,
  useBlocksServicesClient,
  usePlatform,
  useResolveDashboardExtensionUrl,
  useResolvePlatformUrl,
  useSite,
  useSiteOverrideClient
} from "./chunk-PSN6WZCB.js";
import {
  useBackendComponents
} from "./chunk-MK5OQBNN.js";
import {
  getMonitoringProvider,
  updateAppManifestComponents,
  updateMonitoring,
  updateTopology
} from "./chunk-OSDDOY2U.js";
import {
  Alert,
  BROWSER_STATICS_FOLDER,
  Box_default,
  CliError,
  CliErrorCode,
  ComponentType,
  Link,
  PlatformType,
  PointerIcon,
  PointerSmallIcon,
  SSR_STATICS_FOLDER,
  Spinner,
  Text,
  Trans,
  WORKER_STATICS_FOLDER,
  getAppBuildFolder,
  getAppManifestPath,
  pathExists,
  require_lib,
  require_react,
  saveAppConfig,
  uploadApplication,
  useAsync,
  useAsyncCallback,
  useBiLogger,
  useDevCenterClient,
  useExtensions,
  useHttpClient,
  useProjectModel,
  useTranslation
} from "./chunk-VCFM6SMQ.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-4EFJZ3GQ.js";

// src/components/PreviewCommand/index.ts
init_esm_shims();

// src/components/PreviewCommand/PreviewCommand.tsx
init_esm_shims();
var import_react4 = __toESM(require_react(), 1);

// src/components/PreviewCommand/Preview.tsx
init_esm_shims();
var import_react3 = __toESM(require_react(), 1);
var import_variant2 = __toESM(require_lib(), 1);

// src/preview/create-preview-tag.ts
init_esm_shims();
var createPreviewTag = async ({
  model,
  arm,
  serveUrl,
  backendServerUrl,
  blocksComponents,
  topologyComponentId,
  monitoringData,
  monitoringComponentId
}) => {
  const manifest = await readAppManifestFile(model.projectFolder);
  const workerBaseUrl = new URL(WORKER_STATICS_FOLDER, serveUrl).toString();
  const browserBaseUrl = new URL(BROWSER_STATICS_FOLDER, serveUrl).toString();
  const ssrBaseUrl = new URL(SSR_STATICS_FOLDER, serveUrl).toString();
  const updatedManifest = updateMonitoring(
    updateTopology(
      updateAppManifestComponents({
        manifest,
        blocksComponents,
        backendServerUrl,
        browserBaseUrl,
        workerBaseUrl,
        ssrBaseUrl
      }),
      {
        id: topologyComponentId,
        baseApiUrl: backendServerUrl
      }
    ),
    {
      id: monitoringComponentId,
      monitoring: monitoringData
    }
  );
  return arm.createAppRelease(updatedManifest, model.config.projectId);
};

// src/files/assert-build-output-exists.ts
init_esm_shims();
async function assertBuildOutputExists(projectFolder) {
  const buildFolder = getAppBuildFolder(projectFolder);
  const manifestPath = getAppManifestPath(projectFolder);
  if (!await pathExists(buildFolder) || !await pathExists(manifestPath)) {
    throw new CliError({
      code: CliErrorCode.BuiltProjectNeeded(),
      cause: null
    });
  }
}

// src/components/PreviewCommand/ActionStatus.tsx
init_esm_shims();
var import_react = __toESM(require_react(), 1);
var import_variant = __toESM(require_lib(), 1);
var ActionStatus = ({ status, loadingText, successText }) => (0, import_variant.match)(status, {
  NotRequested: () => null,
  Loading: () => /* @__PURE__ */ import_react.default.createElement(Spinner, { text: loadingText }),
  Error: () => null,
  Success: () => /* @__PURE__ */ import_react.default.createElement(Alert, { type: "success" }, successText)
});

// src/components/Platform/PlatformViewer.tsx
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);
var PlatformLink = ({
  url,
  label,
  withPointer = true
}) => {
  return /* @__PURE__ */ import_react2.default.createElement(Box_default, null, /* @__PURE__ */ import_react2.default.createElement(Box_default, { marginRight: 1 }, withPointer && /* @__PURE__ */ import_react2.default.createElement(PointerSmallIcon, null), /* @__PURE__ */ import_react2.default.createElement(Box_default, { marginLeft: 1 }, /* @__PURE__ */ import_react2.default.createElement(Link, { url }, label))));
};
var PlatformViewer = () => {
  const { t } = useTranslation();
  const { isPlatformExists, hasSinglePlatform } = usePlatform();
  const { dashboardExtensions } = useExtensions();
  const { site } = useSite();
  const resolvePlatformUrl = useResolvePlatformUrl();
  const resolveDashboardExtensionUrl = useResolveDashboardExtensionUrl();
  return /* @__PURE__ */ import_react2.default.createElement(import_react2.default.Fragment, null, hasSinglePlatform(PlatformType.Dashboard()) ? dashboardExtensions[0] && /* @__PURE__ */ import_react2.default.createElement(Box_default, { flexDirection: "row" }, /* @__PURE__ */ import_react2.default.createElement(Trans, { i18nKey: "general.open_preview.title_single" }), /* @__PURE__ */ import_react2.default.createElement(
    PlatformLink,
    {
      withPointer: false,
      url: resolveDashboardExtensionUrl(dashboardExtensions[0]),
      label: t("general.platform.dashboard")
    }
  )) : /* @__PURE__ */ import_react2.default.createElement(Box_default, { flexDirection: "column" }, /* @__PURE__ */ import_react2.default.createElement(Trans, { i18nKey: "general.open_preview.title_multiple" }), /* @__PURE__ */ import_react2.default.createElement(Box_default, { paddingLeft: 2, flexDirection: "column" }, isPlatformExists(PlatformType.Site()) && (site.viewUrl ? /* @__PURE__ */ import_react2.default.createElement(
    PlatformLink,
    {
      url: resolvePlatformUrl(PlatformType.Site()),
      label: t("general.platform.site")
    }
  ) : /* @__PURE__ */ import_react2.default.createElement(Box_default, { marginRight: 1 }, /* @__PURE__ */ import_react2.default.createElement(PointerSmallIcon, null), /* @__PURE__ */ import_react2.default.createElement(Box_default, { marginLeft: 1 }, /* @__PURE__ */ import_react2.default.createElement(Text, { skin: "secondary", underline: true }, t("general.platform.unpublished_site"))))), isPlatformExists(PlatformType.Editor()) && /* @__PURE__ */ import_react2.default.createElement(
    PlatformLink,
    {
      url: resolvePlatformUrl(PlatformType.Editor()),
      label: t("general.platform.editor")
    }
  ), isPlatformExists(PlatformType.Dashboard()) && /* @__PURE__ */ import_react2.default.createElement(
    PlatformLink,
    {
      url: resolveDashboardExtensionUrl(dashboardExtensions[0]),
      label: t("general.platform.dashboard")
    }
  ))));
};

// src/components/PreviewCommand/Preview.tsx
var Preview = ({ baseUrl, onPreviewCreated }) => {
  const { site } = useSite();
  const { t } = useTranslation();
  const { model } = useProjectModel();
  const { backendComponents } = useBackendComponents();
  const arm = useARMClient();
  const biLogger = useBiLogger();
  const { getAppByVersion } = useDevCenterClient();
  const { createOverride } = useSiteOverrideClient();
  const httpClient = useHttpClient({ type: "backoffice" });
  const blocksServicesClient = useBlocksServicesClient();
  const uploadApplicationAction = useAsyncCallback(
    () => uploadApplication(
      model.config.appId,
      model.projectFolder,
      biLogger,
      httpClient,
      backendComponents.length > 0
    )
  );
  const createSiteOverrideIdAction = useAsyncCallback(
    (_, overrides) => createOverride({
      appId: model.config.appId,
      siteId: site.id,
      overrides
    })
  );
  const createPreviewAction = useAsyncCallback(
    async (_, serveUrl, backendServerUrl) => {
      const {
        data: { components }
      } = await getAppByVersion({
        appId: model.config.appId
      });
      const topologyComponent = components.find((component) => {
        return component.compType === ComponentType.TOPOLOGY;
      });
      const monitoringComponent = components.find((component) => {
        return component.compType === ComponentType.MONITORING;
      });
      const overrides = createSiteOverrides(model);
      const { id: siteOverrideId } = overrides ? await createSiteOverrideIdAction.execute(overrides) : await Promise.resolve({ id: void 0 });
      const blocksComponentsData = await blocksServicesClient.prepareBlocksComponentsData(model);
      const monitoringComponentData = model.config.monitoring && getMonitoringProvider(model.config.monitoring);
      const armTag = await createPreviewTag({
        model,
        arm,
        serveUrl,
        backendServerUrl,
        blocksComponents: blocksComponentsData,
        topologyComponentId: topologyComponent?.compId,
        monitoringData: monitoringComponentData,
        monitoringComponentId: monitoringComponent?.compId
      });
      if (topologyComponent || monitoringComponent) {
        await saveAppConfig(model.projectFolder, {
          ...topologyComponent ? { topologyComponentId: topologyComponent.compId } : {},
          ...monitoringComponent ? { monitoringComponentId: monitoringComponent.compId } : {}
        });
      }
      return { armTag, siteOverrideId };
    }
  );
  const { status: createPreviewStatus } = useAsync(async () => {
    await assertBuildOutputExists(model.projectFolder);
    const { serveUrl, backendServerUrl } = baseUrl ? { serveUrl: baseUrl, backendServerUrl: void 0 } : await uploadApplicationAction.execute();
    const data = await createPreviewAction.execute(serveUrl, backendServerUrl);
    onPreviewCreated?.(data);
    return data;
  }, []);
  return /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement(
    ActionStatus,
    {
      status: uploadApplicationAction.status,
      loadingText: t("preview_command.uploading_files"),
      successText: t("preview_command.uploading_files_success")
    }
  ), /* @__PURE__ */ import_react3.default.createElement(
    ActionStatus,
    {
      status: createPreviewAction.status,
      loadingText: t("preview_command.creating_preview"),
      successText: t("preview_command.creating_preview_success")
    }
  ), (0, import_variant2.match)(createPreviewStatus, {
    Error: () => null,
    Loading: () => null,
    Success: ({ result: { armTag, siteOverrideId } }) => /* @__PURE__ */ import_react3.default.createElement(SiteOverrideProvider, { siteOverrideId }, /* @__PURE__ */ import_react3.default.createElement(ArmTagProvider, { armTag }, /* @__PURE__ */ import_react3.default.createElement(Box_default, { rowGap: 1, marginY: 1, flexDirection: "column" }, /* @__PURE__ */ import_react3.default.createElement(Box_default, { gap: 1 }, /* @__PURE__ */ import_react3.default.createElement(PointerIcon, null), /* @__PURE__ */ import_react3.default.createElement(
      Trans,
      {
        i18nKey: "general.dev_site.current",
        values: { name: site.displayName }
      }
    )), /* @__PURE__ */ import_react3.default.createElement(Box_default, { rowGap: 1 }, /* @__PURE__ */ import_react3.default.createElement(PlatformViewer, null)), /* @__PURE__ */ import_react3.default.createElement(Text, { skin: "info" }, t("preview_command.note_about_temporary_backend")))))
  }));
};

// src/components/PreviewCommand/PreviewCommand.tsx
var PreviewCommand = ({ baseUrl, siteIdOverride, onPreviewCreated }) => {
  return /* @__PURE__ */ import_react4.default.createElement(SiteProvider, { siteId: siteIdOverride }, /* @__PURE__ */ import_react4.default.createElement(ExtensionDataProvider, null, /* @__PURE__ */ import_react4.default.createElement(Preview, { baseUrl, onPreviewCreated })));
};

export {
  assertBuildOutputExists,
  PreviewCommand
};
//# sourceMappingURL=chunk-6X7N6N75.js.map