import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  useTunnel
} from "./chunk-SVSXYROI.js";
import {
  useWixCliAppBi
} from "./chunk-RDXUYCUV.js";
import {
  LinkClickTip,
  RedirectLink,
  looseComponentSchema,
  parseLooseAppManifest,
  useDevCenterOverridesClient,
  useUpdateDeploymentTopologyForApp,
  useUpdateDeploymentTopologyForSite
} from "./chunk-4LXQCSMI.js";
import {
  PlatformLink
} from "./chunk-VKQEX5GC.js";
import {
  OnboardingState,
  useVeloClient
} from "./chunk-ZY7YHRZR.js";
import "./chunk-DLEBD2WZ.js";
import "./chunk-RTNIG6ZW.js";
import "./chunk-O6HC4AYN.js";
import "./chunk-QRGKMYDD.js";
import {
  ComponentType,
  useDevCenterClient
} from "./chunk-M6WJXTS4.js";
import {
  createPackageManager,
  getRepoType
} from "./chunk-RF4NA2OH.js";
import {
  execa
} from "./chunk-NMCF7XG5.js";
import "./chunk-MHV22UIU.js";
import {
  ASTRO_APP_CONFIG_PATH,
  astroAppConfigSchema,
  devMetadataSchema,
  getAstroAppConfigPath,
  getDebugLogPath,
  useProjectModel,
  useSiteConfig
} from "./chunk-RDF2RA4E.js";
import {
  useHttpClient
} from "./chunk-WFQIXGJV.js";
import {
  usePanoramaMethodLogger
} from "./chunk-ECBO3UFC.js";
import "./chunk-YNEGRO3E.js";
import {
  BiProvider,
  ErrorViewer,
  TimeoutError,
  getHttpErrorInfo,
  openBrowser,
  pRetry,
  pWaitFor,
  resolveUrl,
  serializer,
  toURLSearchParams,
  useBiLogger,
  useDebugLog,
  useErrorReporter
} from "./chunk-HWT3LUJJ.js";
import {
  extractHttpError,
  wixCliAction,
  wixCliAppFlowStepsAnswers
} from "./chunk-TOBTRYZF.js";
import {
  I18nProvider,
  Trans,
  useTranslation
} from "./chunk-7WVNO7VU.js";
import "./chunk-RPTAJN5Y.js";
import {
  Alert,
  Badge,
  Box_default,
  ConfirmInput,
  Key,
  PointerIcon,
  SelectInput,
  SelectOptionAvailability,
  Spinner,
  Text,
  createRendererToString,
  useAsync,
  useAsyncCallback,
  useExit,
  use_input_default
} from "./chunk-YL4347CI.js";
import {
  require_react
} from "./chunk-TODKQSCF.js";
import {
  stripAnsi
} from "./chunk-AFPDHQYI.js";
import "./chunk-HYKBBZLS.js";
import "./chunk-C5RTKQVL.js";
import {
  readUserConfig,
  updateUserConfig
} from "./chunk-SVUXJRFD.js";
import "./chunk-YT5BPQDJ.js";
import "./chunk-LU3R3EBR.js";
import {
  getTestOverrides
} from "./chunk-XZUGLEBK.js";
import {
  outputDir,
  pathExists,
  readJson,
  writeJson
} from "./chunk-VASURI4S.js";
import {
  external_exports
} from "./chunk-SDLCFZRL.js";
import {
  CliError,
  CliErrorCode,
  normalizeError,
  require_lib
} from "./chunk-MTT3QXBC.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-EXLZF52D.js";

// ../cli-astro-commands/src/components/DevCommand/index.ts
init_esm_shims();

// ../cli-astro-commands/src/components/DevCommand/DevCommand.tsx
init_esm_shims();
var import_react33 = __toESM(require_react(), 1);
var import_variant14 = __toESM(require_lib(), 1);

// ../cli-astro-commands/src/components/DevCommand/utils/runAstroDev.ts
init_esm_shims();
var EVENT_LINE = "line";
var EVENT_SERVER_ADDRESS = "server_address";
function runAstroDev({
  packageManager,
  projectFolder,
  port,
  allowedHosts
}) {
  const binaryArgs = ["astro", "dev"];
  if (port) {
    binaryArgs.push("--port", `${port}`);
  }
  if (allowedHosts) {
    binaryArgs.push("--allowed-hosts", allowedHosts);
  }
  const { file, args } = packageManager.getRunBinaryCmd(binaryArgs);
  const result = execa(file, args, {
    cwd: projectFolder,
    stdio: "pipe",
    env: { FORCE_COLOR: "1" },
    cleanup: true,
    windowsHide: false
  });
  let stdoutBuffer = "";
  result.stdout?.on("data", (chunk) => {
    stdoutBuffer += chunk.toString();
    const lines = stdoutBuffer.split("\n");
    stdoutBuffer = lines.pop() ?? "";
    for (const line of lines) {
      result.stdout?.emit(EVENT_LINE, line);
      if (line.includes("http://")) {
        const match11 = /(http:\/\/[^\s]+)/.exec(line);
        if (match11?.[1]) {
          const address = stripAnsi(match11[1]).trim();
          result.stdout?.emit(EVENT_SERVER_ADDRESS, address);
        }
      }
    }
  });
  let stdErrBuffer = "";
  result.stderr?.on("data", (chunk) => {
    stdErrBuffer += chunk.toString();
    const lines = stdErrBuffer.split("\n");
    stdErrBuffer = lines.pop() ?? "";
    for (const line of lines) {
      result.stderr?.emit(EVENT_LINE, line);
    }
  });
  return result;
}

// ../cli-astro-commands/src/components/DevCommand/utils/useAstroLogger.tsx
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);

// ../cli-astro-commands/src/components/DevCommand/utils/createAstroLogger.tsx
init_esm_shims();
var import_react = __toESM(require_react(), 1);
var dateTimeFormat = new Intl.DateTimeFormat([], {
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hour12: false
});
function createAstroLogger(options) {
  const { isPrefixed, onLog, onError } = options;
  const renderer = createRendererToString({ stripAnsi: false });
  const renderPrefix = () => {
    return renderer.render(
      /* @__PURE__ */ import_react.default.createElement(Text, null, /* @__PURE__ */ import_react.default.createElement(Text, null, dateTimeFormat.format(/* @__PURE__ */ new Date()), " "), /* @__PURE__ */ import_react.default.createElement(Text, { skin: "info" }, "[wix] "))
    );
  };
  const formatMessage2 = (prefixed, msg) => {
    const prefix = prefixed ? renderPrefix() : "";
    const suffix = typeof msg === "string" ? msg : renderer.render(msg);
    return `${prefix}${suffix}`;
  };
  const log = (msg) => {
    const stringToLog = formatMessage2(isPrefixed, msg);
    onLog?.(stringToLog);
    setTimeout(() => console.log(stringToLog), 0);
  };
  const error = (msg) => {
    const stringToLog = formatMessage2(isPrefixed, msg);
    onError?.(stringToLog);
    setTimeout(() => console.error(stringToLog), 0);
  };
  return { log, error };
}

// ../cli-astro-commands/src/components/DevCommand/utils/devLogStream.tsx
init_esm_shims();
import { EOL } from "node:os";
import { createWriteStream } from "node:fs";
import { PassThrough } from "node:stream";
import { pipeline } from "node:stream/promises";
import { dirname } from "node:path";
var streamCache = /* @__PURE__ */ new Map();
var createNoopStream = () => ({
  write: () => {
  },
  close: () => {
  },
  isClosed: () => true
});
var getDevLogStream = async (options) => {
  const { filePath } = options;
  const entry = streamCache.get(filePath);
  if (entry && !entry.stream.isClosed()) {
    entry.refCount++;
    return {
      write: (msg) => entry.stream.write(msg),
      release: () => {
        entry.refCount--;
        if (entry.refCount === 0) {
          entry.stream.close();
          streamCache.delete(filePath);
        }
      }
    };
  }
  let stream;
  try {
    stream = await createDevLogStream(options);
  } catch {
    stream = createNoopStream();
  }
  const newEntry = { stream, refCount: 1 };
  streamCache.set(filePath, newEntry);
  return {
    write: (msg) => newEntry.stream.write(msg),
    release: () => {
      newEntry.refCount--;
      if (newEntry.refCount === 0) {
        newEntry.stream.close();
        streamCache.delete(filePath);
      }
    }
  };
};
var createDevLogStream = async ({ filePath }) => {
  await outputDir(dirname(filePath));
  const source = new PassThrough();
  const fileStream = createWriteStream(filePath, { flags: "w" });
  let closed = false;
  const isClosed = () => closed;
  pipeline(source, fileStream).catch(() => {
    if (!closed) {
      closed = true;
    }
  });
  const write = (msg) => {
    if (closed) {
      return;
    }
    source.write(stripAnsi(msg).concat(EOL));
  };
  const close = () => {
    if (closed) {
      return;
    }
    closed = true;
    source.end();
  };
  return {
    write,
    close,
    isClosed
  };
};

// ../cli-astro-commands/src/components/DevCommand/utils/useAstroLogger.tsx
var FORMAT_REGEXP = /^\d{1,2}:\d{1,2}:\d{1,2}\s*/;
var formatMessage = (msg, type = "info") => `[${(/* @__PURE__ */ new Date()).toISOString()}] [cli] [${type}] ${stripAnsi(msg).replace(FORMAT_REGEXP, "")}`;
var useAstroLogger = ({
  isPrefixed = true
} = {}) => {
  const {
    model: { projectFolder }
  } = useProjectModel();
  const streamRef = (0, import_react2.useRef)();
  const logger = (0, import_react2.useMemo)(
    () => createAstroLogger({
      isPrefixed,
      onLog: (msg) => {
        streamRef.current?.write(formatMessage(msg));
      },
      onError: (msg) => {
        streamRef.current?.write(formatMessage(msg, "error"));
      }
    }),
    [isPrefixed]
  );
  (0, import_react2.useEffect)(() => {
    let shouldCleanStream = false;
    void getDevLogStream({
      filePath: getDebugLogPath(projectFolder)
    }).then((devLogStream) => {
      if (shouldCleanStream) {
        devLogStream.release();
        return;
      }
      streamRef.current = devLogStream;
    });
    return () => {
      shouldCleanStream = true;
      streamRef.current?.release();
    };
  }, [projectFolder]);
  return logger;
};

// ../cli-astro-commands/src/components/DevCommand/hooks/useFetchDevMetadata.ts
init_esm_shims();
function useFetchDevMetadata() {
  const http = useHttpClient({ type: "standalone" });
  return useAsyncCallback(async (_, serverLocalUrl) => {
    const url = new URL("/_wix/dev-metadata.json", serverLocalUrl);
    try {
      const { data } = await http.get(url.toString());
      return {
        devMetadata: devMetadataSchema.parse(data),
        serverLocalUrl
      };
    } catch {
      return {
        devMetadata: null,
        serverLocalUrl
      };
    }
  });
}

// ../cli-astro-commands/src/components/DevCommand/DevEnvironment.tsx
init_esm_shims();
var import_react6 = __toESM(require_react(), 1);

// ../cli-astro-commands/src/components/DevCommand/hooks/useDevCenterUpdater.tsx
init_esm_shims();
var import_react4 = __toESM(require_react(), 1);
var import_variant2 = __toESM(require_lib(), 1);

// ../cli-astro-commands/src/files/app.config.ts
init_esm_shims();
async function readAppConfig(projectFolder, writeDebugLog) {
  const configPath = getAstroAppConfigPath(projectFolder);
  const isConfigExist = await pathExists(configPath);
  if (!isConfigExist) {
    return null;
  }
  try {
    const json = await readJson(configPath);
    const appConfig = await astroAppConfigSchema.safeParseAsync(json);
    if (!appConfig.success) {
      return null;
    }
    return appConfig.data;
  } catch (e) {
    writeDebugLog?.(e);
    return null;
  }
}
async function saveAppConfig(projectFolder, config) {
  const currentConfig = await readAppConfig(projectFolder) ?? {};
  const newConfig = {
    ...currentConfig,
    ...config
  };
  await writeJson(getAstroAppConfigPath(projectFolder), newConfig);
}

// ../cli-astro-commands/src/components/DevCommand/hooks/useFetchAppManifest.ts
init_esm_shims();
var import_react3 = __toESM(require_react(), 1);

// ../cli-astro-commands/src/components/DevCommand/utils/isTunnelRequired.ts
init_esm_shims();
function isTunnelRequired(appManifest) {
  for (const extension of appManifest.components) {
    const knownAppManifest = parseKnownExtensionManifest(extension);
    if (knownAppManifest != null && knownAppManifest.compType === ComponentType.WEBHOOK) {
      return !URL.canParse(knownAppManifest.compData.webhook.callbackUrl);
    }
  }
  return false;
}
function parseKnownExtensionManifest(extensionManifest) {
  const appManifestResult = looseComponentSchema.safeParse(extensionManifest);
  if (appManifestResult.error) {
    return null;
  }
  return appManifestResult.data;
}

// ../cli-astro-commands/src/components/DevCommand/hooks/useFetchAppManifest.ts
function useFetchAppManifest() {
  const http = useHttpClient({ type: "standalone" });
  return (0, import_react3.useCallback)(
    async (serverLocalUrl, devMetadata, baseUrl, tunnelUrl) => {
      const url = new URL("/_wix/app-manifest.json", serverLocalUrl);
      const { data: text } = await http.get(url.toString(), {
        responseType: "text",
        transitional: {
          silentJSONParsing: true,
          forcedJSONParsing: false,
          clarifyTimeoutError: false
        },
        disableWixHeaders: true
      });
      if (devMetadata != null) {
        const placeholders = /* @__PURE__ */ new Map();
        placeholders.set(devMetadata.staticsUrlPlaceholder, baseUrl);
        placeholders.set(devMetadata.serverUrlPlaceholder, tunnelUrl);
        return {
          manifest: parseLooseAppManifest(text, placeholders),
          isTunnelRequired: text.includes(devMetadata.serverUrlPlaceholder)
        };
      }
      const manifestV1 = parseLooseAppManifest(text);
      return {
        manifest: manifestV1,
        isTunnelRequired: isTunnelRequired(manifestV1)
      };
    },
    [http]
  );
}

// ../cli-astro-commands/src/components/DevCommand/utils/DevCenterWatcher.ts
init_esm_shims();
import EventEmitter from "node:events";
var DevCenterWatcher = class extends EventEmitter {
  onManifestUpdated(listener) {
    this.on("manifestUpdated", listener);
    return () => this.off("manifestUpdated", listener);
  }
};

// ../cli-astro-commands/src/components/DevCommand/hooks/checkManifestForChanges.ts
init_esm_shims();
var import_variant = __toESM(require_lib(), 1);
import { isDeepStrictEqual } from "node:util";
var ManifestUpdateResult = (0, import_variant.variant)({
  Changed: (0, import_variant.fields)(),
  Unchanged: {}
});
function checkManifestForChanges(previous, latest) {
  if (previous == null) {
    return ManifestUpdateResult.Changed({ updatedComponents: [] });
  }
  if (isDeepStrictEqual(previous, latest)) {
    return ManifestUpdateResult.Unchanged();
  }
  const oldComponentsMap = new Map(
    previous.components.map((comp) => [comp.compId, comp])
  );
  const changedComponents = latest.components.filter((newComp) => {
    const oldComp = oldComponentsMap.get(newComp.compId);
    return !isDeepStrictEqual(newComp, oldComp);
  });
  return ManifestUpdateResult.Changed({ updatedComponents: changedComponents });
}

// ../cli-astro-commands/src/components/DevCommand/hooks/useDevCenterUpdater.tsx
var { pollInterval } = getTestOverrides();
var useDevCenterUpdater = ({
  serverLocalUrl,
  serverExposedUrl,
  devMetadata
}) => {
  const devCenterWatcher = (0, import_react4.useMemo)(() => new DevCenterWatcher(), []);
  const [devArmTag, setDevArmTag] = (0, import_react4.useState)();
  const [manifest, setManifest] = (0, import_react4.useState)(null);
  const { reportError } = useErrorReporter();
  const writeToDebugLog = useDebugLog();
  const exit = useExit();
  const {
    model: { projectFolder, releaseAppId }
  } = useProjectModel();
  const logger = useAstroLogger({ isPrefixed: true });
  const devCenterOverrides = useDevCenterOverridesClient();
  const openTunnel = useTunnel();
  const tunnelUrl = (0, import_react4.useRef)();
  const [tunnelRequired, setTunnelRequired] = (0, import_react4.useState)(false);
  const fetchAppManifest = useFetchAppManifest();
  const baseUrl = serverExposedUrl ?? serverLocalUrl;
  const updateDevCenter = (0, import_react4.useCallback)(
    async (latestManifest, isTunnelRequired2) => {
      const manifestUpdateResult = checkManifestForChanges(
        manifest,
        latestManifest
      );
      if ((0, import_variant2.isType)(manifestUpdateResult, "Unchanged")) {
        return manifestUpdateResult;
      }
      if (!serverExposedUrl && !tunnelUrl.current && isTunnelRequired2) {
        const config = await readUserConfig();
        if (!config.tunneling) {
          setTunnelRequired(true);
          return ManifestUpdateResult.Unchanged();
        }
        const serverLocalPort = parseInt(new URL(serverLocalUrl).port, 10);
        const tunnel = await openTunnel(serverLocalPort);
        tunnelUrl.current = tunnel.url;
        return ManifestUpdateResult.Unchanged();
      }
      const appConfig = await readAppConfig(projectFolder, writeToDebugLog);
      let updatedDevArmTag = appConfig?.devArmTag;
      if (!updatedDevArmTag) {
        updatedDevArmTag = await devCenterOverrides.createLooseAppRelease(
          latestManifest,
          releaseAppId
        );
      } else {
        const updateState = await devCenterOverrides.updateLooseAppRelease(
          latestManifest,
          updatedDevArmTag
        );
        if (!(0, import_variant2.isType)(updateState, "TagUpdated")) {
          updatedDevArmTag = await devCenterOverrides.createLooseAppRelease(
            latestManifest,
            releaseAppId
          );
        }
      }
      if (updatedDevArmTag !== appConfig?.devArmTag) {
        await saveAppConfig(projectFolder, { devArmTag: updatedDevArmTag });
      }
      setManifest(latestManifest);
      setDevArmTag(updatedDevArmTag);
      devCenterWatcher.emit("manifestUpdated", {
        armTag: updatedDevArmTag,
        updatedComponents: manifestUpdateResult.updatedComponents
      });
      return manifestUpdateResult;
    },
    [
      releaseAppId,
      manifest,
      serverLocalUrl,
      serverExposedUrl,
      devCenterOverrides,
      projectFolder,
      openTunnel,
      devCenterWatcher,
      writeToDebugLog
    ]
  );
  const [timer, setTimer] = (0, import_react4.useState)(Date.now());
  (0, import_react4.useEffect)(() => {
    let disposed = false;
    async function fetchAndUpdate() {
      const { manifest: manifest2, isTunnelRequired: isTunnelRequired2 } = await fetchAppManifest(
        serverLocalUrl,
        devMetadata,
        baseUrl,
        tunnelUrl.current ?? baseUrl
      );
      try {
        const result = await updateDevCenter(manifest2, isTunnelRequired2);
        if ((0, import_variant2.isType)(result, "Changed")) {
          logger.log(
            "App manifest updated. Refresh existing browser tabs to view the latest changes."
          );
          if (process.env.REMOTE_MACHINE_TASK_EVENTS_URL) {
            const eventData = {
              type: "manifest_update",
              appId: manifest2.appId,
              overrideId: devArmTag,
              result: "SUCCESS"
            };
            void fetch(process.env.REMOTE_MACHINE_TASK_EVENTS_URL, {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                eventName: "manifest-update",
                taskId: process.env.REMOTE_MACHINE_TASK_ID,
                executionId: process.env.REMOTE_MACHINE_EXECUTION_ID,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                eventData
              })
            });
          }
        }
      } catch (error) {
        setManifest(manifest2);
        logger.error(/* @__PURE__ */ import_react4.default.createElement(ErrorViewer, { error }));
        writeToDebugLog(error);
        reportError(error);
        if (process.env.REMOTE_MACHINE_TASK_EVENTS_URL) {
          const normalizedError = normalizeError(error);
          const httpError = extractHttpError(normalizedError);
          if (httpError) {
            const errorInfo = getHttpErrorInfo(httpError);
            const eventData = {
              type: "manifest_update",
              appId: manifest2.appId,
              overrideId: devArmTag ?? "",
              result: "FAILURE",
              code: errorInfo.response.status,
              message: errorInfo.response.data.message
            };
            void fetch(process.env.REMOTE_MACHINE_TASK_EVENTS_URL, {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                eventName: "manifest-update",
                taskId: process.env.REMOTE_MACHINE_TASK_ID,
                executionId: process.env.REMOTE_MACHINE_EXECUTION_ID,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                eventData
              })
            });
          }
        }
        throw error;
      }
    }
    void fetchAndUpdate().catch((error) => {
      if (error instanceof Error && error.name === "TrustedAppIsNotMarkedAsInternal") {
        exit(error);
      }
    }).finally(() => {
      if (!disposed) {
        setTimeout(() => setTimer(Date.now()), pollInterval ?? 1e3);
      }
    });
    return () => {
      disposed = true;
    };
  }, [timer]);
  return { baseUrl, tunnelRequired, devArmTag, devCenterWatcher };
};

// ../cli-astro-commands/src/components/DevCommand/TunnelingConsent.tsx
init_esm_shims();
var import_react5 = __toESM(require_react(), 1);
var import_variant3 = __toESM(require_lib(), 1);
var TunnelingConsent = ({ required, children }) => {
  const exit = useExit();
  const [approved, setApproved] = (0, import_react5.useState)();
  const { status } = useAsync(async () => {
    const config = await readUserConfig();
    if (config.tunneling) {
      setApproved(true);
    }
    return config;
  }, []);
  if (!required || approved) {
    return children;
  }
  return /* @__PURE__ */ import_react5.default.createElement(import_react5.default.Fragment, null, (0, import_variant3.match)(status, {
    Success: () => /* @__PURE__ */ import_react5.default.createElement(
      ConfirmInput,
      {
        label: "To continue, a secure tunnel will be set up from your machine for development purposes.",
        initialValue: true,
        onSubmit: async (approved2) => {
          setApproved(approved2);
          await updateUserConfig({ tunneling: approved2 });
          if (!approved2) {
            exit();
          }
        }
      }
    ),
    Error: () => null,
    Loading: () => null
  }), approved === false && /* @__PURE__ */ import_react5.default.createElement(Text, { skin: "error" }, "Operation aborted. Tunneling is necessary to run your application."));
};

// ../cli-astro-commands/src/components/DevCommand/DevEnvironment.tsx
var DevEnvironmentContext = (0, import_react6.createContext)(null);
var DevEnvironmentProvider = ({
  serverLocalUrl,
  serverExposedUrl,
  devMetadata,
  children
}) => {
  const { baseUrl, tunnelRequired, devArmTag, devCenterWatcher } = useDevCenterUpdater({
    serverLocalUrl,
    serverExposedUrl,
    devMetadata
  });
  return /* @__PURE__ */ import_react6.default.createElement(TunnelingConsent, { required: tunnelRequired }, devArmTag == null ? /* @__PURE__ */ import_react6.default.createElement(Spinner, { text: "Preparing your dashboard..." }) : /* @__PURE__ */ import_react6.default.createElement(
    DevEnvironmentContext.Provider,
    {
      value: { baseUrl, devArmTag, devCenterWatcher }
    },
    children
  ));
};
var useDevEnvironment = () => {
  const ctx = (0, import_react6.useContext)(DevEnvironmentContext);
  if (!ctx) {
    throw new Error(
      "useDevEnvironment must be used inside DevEnvironmentProvider"
    );
  }
  return ctx;
};

// ../cli-astro-commands/src/components/DevCommand/DevScreenBorder.tsx
init_esm_shims();
var import_react7 = __toESM(require_react(), 1);
var DevScreenBorder = ({ children }) => {
  return /* @__PURE__ */ import_react7.default.createElement(
    Box_default,
    {
      flexDirection: "column",
      borderTop: true,
      borderLeft: false,
      borderBottom: false,
      borderRight: false,
      borderStyle: "round",
      borderColor: "blueBright",
      width: "95%"
    },
    children
  );
};

// ../cli-astro-commands/src/components/DevCommand/SiteDevFlow.tsx
init_esm_shims();
var import_react10 = __toESM(require_react(), 1);

// ../cli-astro-commands/src/components/DevCommand/site-flow/SiteDev.tsx
init_esm_shims();
var import_react9 = __toESM(require_react(), 1);
var import_variant4 = __toESM(require_lib(), 1);

// ../cli-astro-commands/src/components/DevCommand/site-flow/useSiteDeploymentTopologyUpdater.tsx
init_esm_shims();
var import_react8 = __toESM(require_react(), 1);
function useSiteDeploymentTopologyUpdater() {
  const { baseUrl, devArmTag } = useDevEnvironment();
  const { siteId } = useSiteConfig();
  const updateTopology = useUpdateDeploymentTopologyForSite(siteId);
  const exit = useExit();
  (0, import_react8.useEffect)(() => {
    updateTopology({
      armTag: devArmTag,
      siteUrl: baseUrl,
      environment: "development"
    }).catch(exit);
  }, [devArmTag, baseUrl, updateTopology, exit]);
}

// ../cli-astro-commands/src/components/DevCommand/site-flow/SiteDev.tsx
var SiteDev = () => {
  const { appId, siteId } = useSiteConfig();
  const { baseUrl, devArmTag } = useDevEnvironment();
  const veloClient = useVeloClient();
  const { status: gitHubOnboardingStatus } = useAsync(
    () => veloClient.getGitHubOnboardingStatus(appId),
    [appId]
  );
  useSiteDeploymentTopologyUpdater();
  return /* @__PURE__ */ import_react9.default.createElement(import_react9.default.Fragment, null, /* @__PURE__ */ import_react9.default.createElement(Text, null, "Development environment ready"), /* @__PURE__ */ import_react9.default.createElement(Box_default, { marginY: 1, flexDirection: "column", gap: 1 }, /* @__PURE__ */ import_react9.default.createElement(Text, null, "Open the preview on:"), /* @__PURE__ */ import_react9.default.createElement(Box_default, { paddingLeft: 2, flexDirection: "column" }, /* @__PURE__ */ import_react9.default.createElement(PlatformLink, { url: baseUrl, platform: "site" }), /* @__PURE__ */ import_react9.default.createElement(
    PlatformLink,
    {
      url: `https://manage.wix.com/dashboard/${siteId}?apps-override=${devArmTag}`,
      platform: "dashboard"
    }
  ), (0, import_variant4.match)(gitHubOnboardingStatus, {
    Success: ({ result }) => result?.status === OnboardingState.GITHUB_ENABLED && /* @__PURE__ */ import_react9.default.createElement(
      PlatformLink,
      {
        url: `https://vibe.wix.com/projects/${siteId}`,
        platform: "editor"
      }
    ),
    Error: () => null,
    Loading: () => null
  })), /* @__PURE__ */ import_react9.default.createElement(LinkClickTip, null)));
};

// ../cli-astro-commands/src/components/DevCommand/SiteDevFlow.tsx
var SiteDevFlow = () => {
  return /* @__PURE__ */ import_react10.default.createElement(SiteDev, null);
};

// ../cli-astro-commands/src/components/DevCommand/AppDevFlow.tsx
init_esm_shims();
var import_react32 = __toESM(require_react(), 1);

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/index.ts
init_esm_shims();

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/SiteProvider.tsx
init_esm_shims();
var import_react22 = __toESM(require_react(), 1);
var import_variant11 = __toESM(require_lib(), 1);

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/ResolveSite.tsx
init_esm_shims();
var import_react20 = __toESM(require_react(), 1);

// ../cli-site-selector/src/index.ts
init_esm_shims();

// ../cli-site-selector/src/SiteSelector.tsx
init_esm_shims();
var import_react19 = __toESM(require_react(), 1);
var import_variant9 = __toESM(require_lib(), 1);

// ../site-list-client/src/index.ts
init_esm_shims();

// ../site-list-client/src/site-list-client.ts
init_esm_shims();

// ../../node_modules/@wix/ambassador-site-list-v2-site/build/es/http.impl.js
init_esm_shims();
var _querySitesRequest = {};
var _querySitesResponse = { sites: "_site" };
var _site = {
  createdDate: "google.protobuf.Timestamp",
  updatedDate: "google.protobuf.Timestamp",
  trashedDate: "google.protobuf.Timestamp"
};
function resolveComWixpressSitelistApiSiteListServiceV2Url(opts) {
  var domainToMappings = {
    "www._base_domain_": [
      {
        srcPath: "/_api/sites-list",
        destPath: "/api"
      },
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "feedback._base_domain_": [
      {
        srcPath: "/_api/sites-list",
        destPath: "/api"
      }
    ],
    "manage._base_domain_": [
      {
        srcPath: "/_api/sites-list",
        destPath: "/api"
      },
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      },
      {
        srcPath: "/_api/sites-list-data",
        destPath: "/api/sites-list-data"
      }
    ],
    "www.wixapis.com": [
      {
        srcPath: "/site-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "api._api_base_domain_": [
      {
        srcPath: "/sites-list",
        destPath: ""
      }
    ],
    "bo._base_domain_": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "wixbo.ai": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "wix-bo.com": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "dev._base_domain_": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "editor._base_domain_": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "blocks._base_domain_": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "create.editorx": [
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "online.codux.com": [
      {
        srcPath: "/_api/sites-list",
        destPath: ""
      },
      {
        srcPath: "/_api/sites-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "*.dev.wix-code.com": [
      {
        srcPath: "/site-list/v2/sites",
        destPath: "/v2/sites"
      }
    ],
    "vibe._base_domain_": [
      {
        srcPath: "/_api/sites-list",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function querySites(payload) {
  var _a = serializer(_querySitesRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_querySitesResponse, { _site }).fromJSON;
  function __querySites(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.site_list.v2.site",
      method: "POST",
      methodFqn: "com.wixpress.sitelist.api.SiteListServiceV2.QuerySites",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveComWixpressSitelistApiSiteListServiceV2Url({
        protoPath: "/v2/sites/query",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __querySites.fromReq = fromReq;
  __querySites.__isAmbassador = true;
  return __querySites;
}

// ../site-list-client/src/schemas.ts
init_esm_shims();
var siteSchema = external_exports.object({
  id: external_exports.string(),
  displayName: external_exports.string(),
  viewUrl: external_exports.union([external_exports.string().url(), external_exports.literal("")]).optional()
});
var querySitesSchema = external_exports.object({
  sites: external_exports.array(siteSchema)
});

// ../site-list-client/src/site-list-client.ts
var SiteListClient = class {
  constructor(httpClient) {
    this.httpClient = httpClient;
    const { minRetryTimeout } = getTestOverrides();
    this.retryOptions = {
      retries: 3,
      minTimeout: minRetryTimeout,
      maxTimeout: 3 * 1e3
    };
  }
  retryOptions;
  querySites = async (opts = {}) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(querySites(opts)),
        this.retryOptions
      );
      return querySitesSchema.parse(data).sites;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToQuerySites(),
        cause: e,
        info: { ...opts }
      });
    }
  };
  getSite = async (id, inclHeadless) => {
    const queryPayload = {
      query: {
        filter: {
          id: { $in: [id] },
          ...inclHeadless ? {
            namespace: { $in: ["WIX", "HEADLESS"] }
          } : {}
        }
      }
    };
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(querySites(queryPayload)),
        this.retryOptions
      );
      const { sites } = querySitesSchema.parse(data);
      return sites.at(0) ?? null;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToGetSite(),
        cause: e,
        info: { id }
      });
    }
  };
};

// ../site-list-client/src/useSiteListClient.ts
init_esm_shims();
var import_react11 = __toESM(require_react(), 1);
function useSiteListClient() {
  const httpClient = useHttpClient({ type: "backoffice" });
  const client = (0, import_react11.useMemo)(() => new SiteListClient(httpClient), [httpClient]);
  return usePanoramaMethodLogger(client);
}

// ../cli-site-selector/src/SiteTypeSelect.tsx
init_esm_shims();
var import_react13 = __toESM(require_react(), 1);
var import_variant5 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/bi.ts
init_esm_shims();
var import_react12 = __toESM(require_react(), 1);
function siteSelectorBiEvents(biLogger) {
  return {
    cliAction: ({
      question,
      action,
      key,
      additionalInfo
    }) => {
      void biLogger.report(
        wixCliAction({
          question,
          action,
          key,
          additionalInfo: JSON.stringify(additionalInfo)
        })
      );
    },
    cliFlowStepAnswered: ({
      question,
      answer,
      additionalInfo
    }) => {
      void biLogger.report(
        wixCliAppFlowStepsAnswers({
          question,
          answer,
          additionalInfo: JSON.stringify(additionalInfo)
        })
      );
    }
  };
}
function useSiteSelectorBi() {
  const biLogger = useBiLogger();
  return (0, import_react12.useMemo)(() => siteSelectorBiEvents(biLogger), [biLogger]);
}

// ../cli-site-selector/src/SiteTypeSelect.tsx
var SiteTypeSelect = ({ onSubmit, onError, sites }) => {
  const bi = useSiteSelectorBi();
  const { t } = useTranslation();
  const { getDevSitesCount, getDevSitesLimit } = useDevCenterClient();
  const { status } = useAsync(
    () => Promise.all([getDevSitesCount(), getDevSitesLimit()]),
    [],
    { onError }
  );
  const handleSubmit = (option) => {
    void bi.cliFlowStepAnswered({
      question: t("site_type_select.label"),
      answer: option.title
    });
    onSubmit(option.value);
  };
  return (0, import_variant5.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react13.default.createElement(Spinner, { text: t("general.loading") }),
    Success: ({ result: [devSitesCount, devSitesLimit] }) => {
      const isDevSitesLimitReached = devSitesCount >= devSitesLimit;
      const userHasNoSites = sites.length === 0;
      return /* @__PURE__ */ import_react13.default.createElement(
        SelectInput,
        {
          label: t("site_type_select.label"),
          options: [
            {
              availability: userHasNoSites ? SelectOptionAvailability.Disabled({
                reason: t("site_type_select.no_sites")
              }) : SelectOptionAvailability.Enabled(),
              title: t("site_type_select.pick_existing_site"),
              value: "select-existing-site"
            },
            {
              title: t("site_type_select.create_new_dev_site"),
              value: "create-dev-site",
              availability: isDevSitesLimitReached ? SelectOptionAvailability.Disabled({
                reason: t("site_type_select.create_new_dev_site.disabled", {
                  limit: devSitesLimit
                })
              }) : SelectOptionAvailability.Enabled()
            },
            {
              title: t("site_type_select.create_new_harmony_site"),
              value: "create-harmony-site",
              availability: isDevSitesLimitReached ? SelectOptionAvailability.Disabled({
                reason: t("site_type_select.create_new_dev_site.disabled", {
                  limit: devSitesLimit
                })
              }) : SelectOptionAvailability.Enabled()
            }
          ],
          onSubmit: handleSubmit
        }
      );
    }
  });
};

// ../cli-site-selector/src/CreateDevSite.tsx
init_esm_shims();
var import_react16 = __toESM(require_react(), 1);
var import_variant7 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/WaitForAppToBeInstalled.tsx
init_esm_shims();
var import_react15 = __toESM(require_react(), 1);
var import_variant6 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/OpenBrowser.tsx
init_esm_shims();
var import_react14 = __toESM(require_react(), 1);
var OpenBrowser = ({ siteId, appId }) => {
  const { t } = useTranslation();
  const bi = useSiteSelectorBi();
  use_input_default(async (input, key) => {
    if (key.return) {
      bi.cliAction({
        question: t("install_app_on_site.warning.instructions"),
        key: "enter",
        action: "install_app_on_site"
      });
      await openBrowser(
        `https://manage.wix.com/installer/install?metaSiteId=${siteId}&appId=${appId}&platform=cli&version=latest`
      );
    }
  });
  return /* @__PURE__ */ import_react14.default.createElement(import_react14.default.Fragment, null, /* @__PURE__ */ import_react14.default.createElement(Trans, { i18nKey: "install_app_on_site.warning" }), /* @__PURE__ */ import_react14.default.createElement(
    Trans,
    {
      i18nKey: "install_app_on_site.warning.instructions",
      components: [/* @__PURE__ */ import_react14.default.createElement(Key, { value: "Enter" })]
    }
  ));
};

// ../cli-site-selector/src/WaitForAppToBeInstalled.tsx
var AppInstallData = (0, import_variant6.variant)({
  Success: {},
  Canceled: {}
});
function isAbortError(error) {
  return error && typeof error === "object" && "name" in error && error.name === "AbortError";
}
var WaitForAppToBeInstalled = ({
  appId,
  site,
  onSubmit,
  onError
}) => {
  const { isAppInstalled } = useDevCenterClient({ siteId: site.id });
  const { status } = useAsync(
    async ({ signal }) => {
      const { pollInterval: pollInterval2 } = getTestOverrides();
      try {
        await pWaitFor(() => isAppInstalled(appId), {
          // Polling interval is set to 6.5 seconds to avoid rate limiting (429)
          interval: pollInterval2 ?? 6500,
          timeout: {
            milliseconds: 60 * 1e3 * 2,
            signal
          }
        });
        return AppInstallData.Success();
      } catch (error) {
        if (error instanceof TimeoutError) {
          throw new CliError({
            code: CliErrorCode.SiteSelectorTimedout(),
            cause: error
          });
        }
        if (isAbortError(error)) {
          return AppInstallData.Canceled();
        }
        throw error;
      }
    },
    [],
    {
      onError,
      onSuccess: (result) => {
        if ((0, import_variant6.isType)(result, AppInstallData.Success)) {
          onSubmit();
        }
      }
    }
  );
  return (0, import_variant6.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react15.default.createElement(OpenBrowser, { siteId: site.id, appId }),
    Success: () => /* @__PURE__ */ import_react15.default.createElement(Alert, { type: "success" }, /* @__PURE__ */ import_react15.default.createElement(Badge, { skin: "success" }, /* @__PURE__ */ import_react15.default.createElement(Trans, { i18nKey: "general.success" })), " ", /* @__PURE__ */ import_react15.default.createElement(Trans, { i18nKey: "install_app_on_site.finished_successfully" }))
  });
};

// ../cli-site-selector/src/CreateDevSite.tsx
var CreateDevSite = ({
  status,
  appId,
  onSubmit,
  onError
}) => {
  const { t } = useTranslation();
  return (0, import_variant7.match)(status, {
    NotRequested: () => null,
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react16.default.createElement(Spinner, { text: t("create_dev_site.loading") }),
    Success: ({ result }) => /* @__PURE__ */ import_react16.default.createElement(import_react16.default.Fragment, null, /* @__PURE__ */ import_react16.default.createElement(
      Trans,
      {
        i18nKey: "create_dev_site.success",
        components: [/* @__PURE__ */ import_react16.default.createElement(Text, { skin: "success", bold: true })],
        values: { name: result.displayName }
      }
    ), /* @__PURE__ */ import_react16.default.createElement(
      WaitForAppToBeInstalled,
      {
        appId,
        site: result,
        onSubmit: () => onSubmit(result),
        onError
      }
    ))
  });
};

// ../cli-site-selector/src/SelectExistingSite.tsx
init_esm_shims();
var import_react18 = __toESM(require_react(), 1);
var import_variant8 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/SiteListSelect.tsx
init_esm_shims();
var import_react17 = __toESM(require_react(), 1);
var SiteListSelect = ({ onSubmit, sites }) => {
  const { t } = useTranslation();
  const bi = useSiteSelectorBi();
  const handleSubmit = (0, import_react17.useCallback)(
    (option) => {
      bi.cliFlowStepAnswered({
        question: t("site_list_select.label"),
        answer: option.title
      });
      onSubmit(option.value);
    },
    [bi, onSubmit, t]
  );
  return /* @__PURE__ */ import_react17.default.createElement(
    SelectInput,
    {
      label: t("site_list_select.label"),
      options: sites.map((site) => ({
        key: site.id,
        title: site.displayName,
        description: site.viewUrl,
        value: site
      })),
      onSubmit: handleSubmit
    }
  );
};

// ../cli-site-selector/src/SelectExistingSite.tsx
var CheckAppInstalledOnSite = ({ appId, site, onSubmit, onError }) => {
  const { t } = useTranslation();
  const { isAppInstalled } = useDevCenterClient({ siteId: site.id });
  const { status } = useAsync(async () => isAppInstalled(appId), [], {
    onError,
    onSuccess: (isInstalled) => {
      if (isInstalled) {
        onSubmit(site);
      }
    }
  });
  return (0, import_variant8.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react18.default.createElement(Spinner, { text: t("general.loading") }),
    Success: ({ result: isInstalled }) => {
      if (isInstalled) {
        return null;
      }
      return /* @__PURE__ */ import_react18.default.createElement(
        WaitForAppToBeInstalled,
        {
          appId,
          site,
          onSubmit: () => onSubmit(site),
          onError
        }
      );
    }
  });
};
var SelectExistingSite = ({
  sites,
  appId,
  onSubmit,
  onError
}) => {
  const [siteToInstallAppOn, setSiteToInstallAppOn] = (0, import_react18.useState)(
    null
  );
  return /* @__PURE__ */ import_react18.default.createElement(import_react18.default.Fragment, null, /* @__PURE__ */ import_react18.default.createElement(
    SiteListSelect,
    {
      onSubmit: (site) => setSiteToInstallAppOn(site),
      sites
    }
  ), siteToInstallAppOn && /* @__PURE__ */ import_react18.default.createElement(
    CheckAppInstalledOnSite,
    {
      appId,
      site: siteToInstallAppOn,
      onSubmit: () => onSubmit(siteToInstallAppOn),
      onError
    }
  ));
};

// ../cli-site-selector/src/messages.json
var messages_default = {
  "general.loading": "Loading...",
  "general.success": "Done",
  "site_type_select.label": "Select development site:",
  "site_type_select.pick_existing_site": "Select an existing site:",
  "site_type_select.create_new_dev_site": "Create a new development site",
  "site_type_select.create_new_dev_site.disabled": "You have reached the maximum number of {limit} development sites.",
  "site_type_select.create_new_harmony_site": "Create a new Harmony Development Site",
  "site_type_select.no_sites": "No sites found.",
  "create_dev_site.loading": "Creating your new development site...",
  "create_dev_site.success": "Development site <0>{name}</0> created.",
  "site_list_select.label": "Select Site:",
  "install_app_on_site.warning": "Your new app needs to be installed on the selected development site.",
  "install_app_on_site.warning.instructions": "Press <0/> to install the app in your browser.",
  "install_app_on_site.finished_successfully": "App installed."
};

// ../cli-site-selector/src/SiteSelector.tsx
var HARMONY_SITE_TEMPLATE = "91532250-8835-46ac-9666-e4db8770b275";
var SiteSelector = ({
  appId,
  biLogger,
  onSubmit,
  onError
}) => {
  const [siteType, setSiteType] = (0, import_react19.useState)(null);
  const { createDevSite } = useDevCenterClient();
  const siteListClient = useSiteListClient();
  const { status } = useAsync(
    () => siteListClient.querySites({
      query: {
        cursorPaging: {
          limit: 100
        }
      }
    }),
    [],
    {
      onError
    }
  );
  const createSite = useAsyncCallback(
    (_, siteType2) => siteType2 === "create-harmony-site" ? createDevSite({ templateId: HARMONY_SITE_TEMPLATE }) : createDevSite(),
    {
      onError
    }
  );
  function handleSelectSiteType(siteType2) {
    setSiteType(siteType2);
    if (siteType2 !== "select-existing-site") {
      void createSite.execute(siteType2);
    }
  }
  return /* @__PURE__ */ import_react19.default.createElement(BiProvider, { value: biLogger }, /* @__PURE__ */ import_react19.default.createElement(I18nProvider, { messages: messages_default }, (0, import_variant9.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react19.default.createElement(Spinner, { text: /* @__PURE__ */ import_react19.default.createElement(Trans, { i18nKey: "general.loading" }) }),
    Success: ({ result: sites }) => /* @__PURE__ */ import_react19.default.createElement(import_react19.default.Fragment, null, /* @__PURE__ */ import_react19.default.createElement(
      SiteTypeSelect,
      {
        onSubmit: handleSelectSiteType,
        onError,
        sites
      }
    ), siteType === "select-existing-site" ? /* @__PURE__ */ import_react19.default.createElement(
      SelectExistingSite,
      {
        sites,
        appId,
        onSubmit,
        onError
      }
    ) : /* @__PURE__ */ import_react19.default.createElement(
      CreateDevSite,
      {
        status: createSite.status,
        appId,
        onSubmit,
        onError
      }
    ))
  })));
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/ResolveSite.tsx
var ResolveSite = ({ onSubmit }) => {
  const exit = useExit();
  const { model } = useProjectModel();
  const biLogger = useBiLogger();
  return /* @__PURE__ */ import_react20.default.createElement(import_react20.default.Fragment, null, /* @__PURE__ */ import_react20.default.createElement(Alert, { type: "insight" }, "You don't have a development site currently configured."), /* @__PURE__ */ import_react20.default.createElement(
    SiteSelector,
    {
      appId: model.config.appId,
      biLogger,
      onSubmit: (site) => onSubmit(site.id),
      onError: exit
    }
  ));
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/context.ts
init_esm_shims();
var import_react21 = __toESM(require_react(), 1);
var SiteContext = (0, import_react21.createContext)(null);

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/site-value.ts
init_esm_shims();
var import_variant10 = __toESM(require_lib(), 1);
var SiteValue = (0, import_variant10.variant)({
  NotConfigured: {},
  Resolved: (0, import_variant10.fields)()
});

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/SiteProvider.tsx
var SiteProvider = ({ children }) => {
  const exit = useExit();
  const { model } = useProjectModel();
  const { projectFolder, env } = model;
  const userDefinedSiteId = env.WIX_SITE_ID;
  const writeDebugLog = useDebugLog();
  const { status, merge } = useAsync(async () => {
    if (userDefinedSiteId) {
      return SiteValue.Resolved({ siteId: userDefinedSiteId });
    }
    const siteId = (await readAppConfig(projectFolder, writeDebugLog))?.siteId;
    return siteId ? SiteValue.Resolved({ siteId }) : SiteValue.NotConfigured();
  }, []);
  const setSiteId = (0, import_react22.useCallback)(
    async (siteId) => {
      if (userDefinedSiteId) {
        throw new Error("Cannot change site: siteId is user-defined");
      }
      try {
        await saveAppConfig(projectFolder, { siteId });
        merge({ result: SiteValue.Resolved({ siteId }) });
      } catch (e) {
        throw new CliError({
          code: CliErrorCode.FailedToSaveDevelopmentSite({
            path: ASTRO_APP_CONFIG_PATH
          }),
          cause: e
        });
      }
    },
    [merge, projectFolder, userDefinedSiteId]
  );
  const handleResolveSite = (0, import_react22.useCallback)(
    (siteId) => setSiteId(siteId).catch(exit),
    [exit, setSiteId]
  );
  return (0, import_variant11.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react22.default.createElement(Spinner, { text: "Resolving development site..." }),
    Success: ({ result: state }) => {
      return (0, import_variant11.match)(state, {
        NotConfigured: () => /* @__PURE__ */ import_react22.default.createElement(ResolveSite, { onSubmit: handleResolveSite }),
        Resolved: ({ siteId }) => /* @__PURE__ */ import_react22.default.createElement(
          SiteContext.Provider,
          {
            value: {
              siteId,
              setSiteId,
              canChangeSite: !userDefinedSiteId
            }
          },
          children
        )
      });
    }
  });
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/site/useSite.ts
init_esm_shims();
var import_react23 = __toESM(require_react(), 1);
function useSite() {
  const context = (0, import_react23.useContext)(SiteContext);
  if (context == null) {
    throw new Error("useSite() cannot be used without an <SiteProvider>");
  }
  return context;
}

// ../cli-astro-commands/src/components/DevCommand/app-flow/AppDev.tsx
init_esm_shims();
var import_react31 = __toESM(require_react(), 1);
var import_variant13 = __toESM(require_lib(), 1);

// ../cli-astro-commands/src/components/DevCommand/app-flow/useAppDeploymentTopologyUpdater.tsx
init_esm_shims();
var import_react24 = __toESM(require_react(), 1);
function useAppDeploymentTopologyUpdater() {
  const { devArmTag } = useDevEnvironment();
  const { siteId } = useSite();
  const updateTopology = useUpdateDeploymentTopologyForApp(siteId);
  const exit = useExit();
  (0, import_react24.useEffect)(() => {
    updateTopology({ armTag: devArmTag, environment: "development" }).catch(
      exit
    );
  }, [devArmTag, updateTopology, exit]);
}

// ../cli-astro-commands/src/components/DevCommand/app-flow/useERCManifestUpdateNotifier.ts
init_esm_shims();
var import_react26 = __toESM(require_react(), 1);

// ../metasite-manager-client/src/index.ts
init_esm_shims();

// ../metasite-manager-client/src/useMetasiteManagerClient.ts
init_esm_shims();
var import_react25 = __toESM(require_react(), 1);

// ../metasite-manager-client/src/metasite-manager-client.ts
init_esm_shims();

// ../../node_modules/@wix/ambassador-metasite-api-v1-meta-site/build/es/http.impl.js
init_esm_shims();
var _createMetaSiteFromTemplateRequest = {};
var _createMetaSiteFromTemplateResponse = { metaSite: "_metaSite" };
var _getUrlRequest = {};
var _getUrlResponse = {};
var _metaSite = {
  dateCreated: "google.protobuf.Timestamp",
  dateUpdated: "google.protobuf.Timestamp",
  accountCreatedDate: "google.protobuf.Timestamp"
};
function resolveComWixpressMetasiteApiV1MetaSiteReadApiUrl(opts) {
  var domainToMappings = {
    "www._base_domain_": [
      {
        srcPath: "/_api/msm-server",
        destPath: ""
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get",
        destPath: "/v1/meta-site/get"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/is-site-name-free",
        destPath: "/v1/meta-site/is-site-name-free"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/has-sites",
        destPath: "/v1/meta-site/has-sites"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get-url",
        destPath: "/v1/meta-site/get-url"
      }
    ],
    "manage._base_domain_": [
      {
        srcPath: "/_api/msm-server",
        destPath: ""
      },
      {
        srcPath: "/_api/msm/v1/meta-site/is-site-name-free",
        destPath: "/v1/meta-site/is-site-name-free"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/has-sites",
        destPath: "/v1/meta-site/has-sites"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get-url",
        destPath: "/v1/meta-site/get-url"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get",
        destPath: "/v1/meta-site/get"
      }
    ],
    "editor-flow.wixapps.net": [
      {
        srcPath: "/_api/msm/v1/meta-site/get",
        destPath: "/v1/meta-site/get"
      }
    ],
    "editor._base_domain_": [
      {
        srcPath: "/_api/msm/v1/meta-site/get",
        destPath: "/v1/meta-site/get"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get-url",
        destPath: "/v1/meta-site/get-url"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/has-sites",
        destPath: "/v1/meta-site/has-sites"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/is-site-name-free",
        destPath: "/v1/meta-site/is-site-name-free"
      }
    ],
    "blocks._base_domain_": [
      {
        srcPath: "/_api/msm/v1/meta-site/get",
        destPath: "/v1/meta-site/get"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get-url",
        destPath: "/v1/meta-site/get-url"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/has-sites",
        destPath: "/v1/meta-site/has-sites"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/is-site-name-free",
        destPath: "/v1/meta-site/is-site-name-free"
      }
    ],
    "create.editorx": [
      {
        srcPath: "/_api/msm/v1/meta-site/get",
        destPath: "/v1/meta-site/get"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/get-url",
        destPath: "/v1/meta-site/get-url"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/has-sites",
        destPath: "/v1/meta-site/has-sites"
      },
      {
        srcPath: "/_api/msm/v1/meta-site/is-site-name-free",
        destPath: "/v1/meta-site/is-site-name-free"
      }
    ],
    "www.wixgateway.com": [
      {
        srcPath: "/v1/meta-site/session-token",
        destPath: "/v1/meta-site/session-token"
      }
    ],
    "api._api_base_domain_": [
      {
        srcPath: "/msm-server",
        destPath: ""
      }
    ],
    "dev._base_domain_": [
      {
        srcPath: "/_api/msm/v1/meta-site/has-sites",
        destPath: "/v1/meta-site/has-sites"
      }
    ],
    "online.codux.com": [
      {
        srcPath: "/_api/msm/v1/meta-site",
        destPath: "/v1/meta-site"
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function resolveComWixpressMetasiteApiV1MetaSiteLifecycleUrl(opts) {
  var domainToMappings = {
    "www._base_domain_": [
      {
        srcPath: "/_api/msm-writer",
        destPath: ""
      },
      {
        srcPath: "/_api/msm",
        destPath: ""
      }
    ],
    "manage._base_domain_": [
      {
        srcPath: "/_api/msm-writer",
        destPath: ""
      },
      {
        srcPath: "/_api/msm",
        destPath: ""
      }
    ],
    "www.wixapis.com": [
      {
        srcPath: "/msm",
        destPath: ""
      }
    ],
    "editor._base_domain_": [
      {
        srcPath: "/_api/msm-writer",
        destPath: ""
      }
    ],
    "blocks._base_domain_": [
      {
        srcPath: "/_api/msm-writer",
        destPath: ""
      }
    ],
    "create.editorx": [
      {
        srcPath: "/_api/msm-writer",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function createMetaSiteFromTemplate(payload) {
  var _a = serializer(_createMetaSiteFromTemplateRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_createMetaSiteFromTemplateResponse, { _metaSite }).fromJSON;
  function __createMetaSiteFromTemplate(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.metasite.api.v1.meta_site",
      method: "POST",
      methodFqn: "com.wixpress.metasite.api.v1.MetaSiteLifecycle.CreateMetaSiteFromTemplate",
      url: resolveComWixpressMetasiteApiV1MetaSiteLifecycleUrl({
        protoPath: "/v1/meta-site/create-from-template",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __createMetaSiteFromTemplate.fromReq = fromReq;
  __createMetaSiteFromTemplate.__isAmbassador = true;
  return __createMetaSiteFromTemplate;
}
function getUrl(payload) {
  var _a = serializer(_getUrlRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_getUrlResponse, {}).fromJSON;
  function __getUrl(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.metasite.api.v1.meta_site",
      method: "GET",
      methodFqn: "com.wixpress.metasite.api.v1.MetaSiteReadApi.GetUrl",
      url: resolveComWixpressMetasiteApiV1MetaSiteReadApiUrl({
        protoPath: "/v1/meta-site/get-url",
        data: serializedData,
        host
      }),
      params: toURLSearchParams(serializedData),
      transformResponse: fromRes,
      fallback: [
        {
          method: "GET",
          url: resolveComWixpressMetasiteApiV1MetaSiteReadApiUrl({
            protoPath: "/v1/meta-site/get-url",
            data: serializedData,
            host
          }),
          params: toURLSearchParams(serializedData)
        }
      ]
    };
    return metadata;
  }
  __getUrl.fromReq = fromReq;
  __getUrl.__isAmbassador = true;
  return __getUrl;
}

// ../../node_modules/@wix/ambassador-metasite-api-v1-meta-site/build/es/types.impl.js
init_esm_shims();
var State;
(function(State2) {
  State2["UNKNOWN"] = "UNKNOWN";
  State2["ENABLED"] = "ENABLED";
  State2["DISABLED"] = "DISABLED";
  State2["TEMPLATE"] = "TEMPLATE";
  State2["PENDING"] = "PENDING";
})(State || (State = {}));
var Namespace;
(function(Namespace2) {
  Namespace2["UNKNOWN_NAMESPACE"] = "UNKNOWN_NAMESPACE";
  Namespace2["WIX"] = "WIX";
  Namespace2["SHOUT_OUT"] = "SHOUT_OUT";
  Namespace2["ALBUMS"] = "ALBUMS";
  Namespace2["WIX_STORES_TEST_DRIVE"] = "WIX_STORES_TEST_DRIVE";
  Namespace2["HOTELS"] = "HOTELS";
  Namespace2["CLUBS"] = "CLUBS";
  Namespace2["ONBOARDING_DRAFT"] = "ONBOARDING_DRAFT";
  Namespace2["DEV_SITE"] = "DEV_SITE";
  Namespace2["LOGOS"] = "LOGOS";
  Namespace2["VIDEO_MAKER"] = "VIDEO_MAKER";
  Namespace2["PARTNER_DASHBOARD"] = "PARTNER_DASHBOARD";
  Namespace2["DEV_CENTER_COMPANY"] = "DEV_CENTER_COMPANY";
  Namespace2["HTML_DRAFT"] = "HTML_DRAFT";
  Namespace2["SITELESS_BUSINESS"] = "SITELESS_BUSINESS";
  Namespace2["CREATOR_ECONOMY"] = "CREATOR_ECONOMY";
  Namespace2["DASHBOARD_FIRST"] = "DASHBOARD_FIRST";
  Namespace2["ANYWHERE"] = "ANYWHERE";
  Namespace2["HEADLESS"] = "HEADLESS";
  Namespace2["ACCOUNT_MASTER_CMS"] = "ACCOUNT_MASTER_CMS";
  Namespace2["RISE"] = "RISE";
  Namespace2["BRANDED_FIRST"] = "BRANDED_FIRST";
  Namespace2["NOWNIA"] = "NOWNIA";
  Namespace2["UGC_TEMPLATE"] = "UGC_TEMPLATE";
  Namespace2["CODUX"] = "CODUX";
  Namespace2["MEDIA_DESIGN_CREATOR"] = "MEDIA_DESIGN_CREATOR";
  Namespace2["SHARED_BLOG_ENTERPRISE"] = "SHARED_BLOG_ENTERPRISE";
  Namespace2["STANDALONE_FORMS"] = "STANDALONE_FORMS";
  Namespace2["STANDALONE_EVENTS"] = "STANDALONE_EVENTS";
  Namespace2["MIMIR"] = "MIMIR";
  Namespace2["TWINS"] = "TWINS";
  Namespace2["NANO"] = "NANO";
})(Namespace || (Namespace = {}));
var DocumentType;
(function(DocumentType2) {
  DocumentType2["UNKNOWN_DOCUMENT_TYPE"] = "UNKNOWN_DOCUMENT_TYPE";
  DocumentType2["UGC"] = "UGC";
  DocumentType2["TEMPLATE"] = "TEMPLATE";
  DocumentType2["WIX_SITE"] = "WIX_SITE";
})(DocumentType || (DocumentType = {}));
var PremiumFeature;
(function(PremiumFeature2) {
  PremiumFeature2["UNKNOWN_PREMIUM_FEATURE"] = "UNKNOWN_PREMIUM_FEATURE";
  PremiumFeature2["SHOW_WIX_WHILE_LOADING"] = "SHOW_WIX_WHILE_LOADING";
  PremiumFeature2["ADS_FREE"] = "ADS_FREE";
  PremiumFeature2["HAS_ECOMMERCE"] = "HAS_ECOMMERCE";
  PremiumFeature2["HAS_DOMAIN"] = "HAS_DOMAIN";
  PremiumFeature2["ALWAYS_SHOW_FOOTER"] = "ALWAYS_SHOW_FOOTER";
  PremiumFeature2["NO_ADS_IN_SOCIAL_SITES"] = "NO_ADS_IN_SOCIAL_SITES";
})(PremiumFeature || (PremiumFeature = {}));
var ApplicationType;
(function(ApplicationType2) {
  ApplicationType2["UNKNOWN_APPLICATION_TYPE"] = "UNKNOWN_APPLICATION_TYPE";
  ApplicationType2["FLASH"] = "FLASH";
  ApplicationType2["FLASH_FACEBOOK"] = "FLASH_FACEBOOK";
  ApplicationType2["FLASH_WIDGET"] = "FLASH_WIDGET";
  ApplicationType2["FLASH_BANNER"] = "FLASH_BANNER";
  ApplicationType2["HTML_MOBILE"] = "HTML_MOBILE";
  ApplicationType2["HTML_WEB"] = "HTML_WEB";
  ApplicationType2["HTML_FACEBOOK"] = "HTML_FACEBOOK";
  ApplicationType2["BLOG"] = "BLOG";
  ApplicationType2["WIX_LISTS"] = "WIX_LISTS";
  ApplicationType2["STATIC_MOUNT"] = "STATIC_MOUNT";
  ApplicationType2["STATIC_MOUNT_REDIRECT"] = "STATIC_MOUNT_REDIRECT";
  ApplicationType2["AMP_BLOG"] = "AMP_BLOG";
  ApplicationType2["COMMUNITIES_AMP_BLOG"] = "COMMUNITIES_AMP_BLOG";
  ApplicationType2["HTML_ANYWHERE"] = "HTML_ANYWHERE";
  ApplicationType2["HOPP"] = "HOPP";
})(ApplicationType || (ApplicationType = {}));
var Compatibility;
(function(Compatibility2) {
  Compatibility2["UNKNOWN_COMPATIBILITY"] = "UNKNOWN_COMPATIBILITY";
  Compatibility2["WEB"] = "WEB";
  Compatibility2["MOBILE"] = "MOBILE";
  Compatibility2["ALL"] = "ALL";
})(Compatibility || (Compatibility = {}));
var ApiState;
(function(ApiState2) {
  ApiState2["UNKNOWN_STATE"] = "UNKNOWN_STATE";
  ApiState2["TEMPLATE"] = "TEMPLATE";
  ApiState2["STUB"] = "STUB";
  ApiState2["INITIALIZED"] = "INITIALIZED";
})(ApiState || (ApiState = {}));
var Kind;
(function(Kind2) {
  Kind2["OPEN"] = "OPEN";
  Kind2["CLOSED"] = "CLOSED";
  Kind2["APPLY_FOR_MEMBERSHIP"] = "APPLY_FOR_MEMBERSHIP";
})(Kind || (Kind = {}));
var FormFace;
(function(FormFace2) {
  FormFace2["REGISTER"] = "REGISTER";
  FormFace2["LOGIN"] = "LOGIN";
})(FormFace || (FormFace = {}));
var CollectionExposure;
(function(CollectionExposure2) {
  CollectionExposure2["PUBLIC"] = "PUBLIC";
  CollectionExposure2["WIX_INTERNAL"] = "WIX_INTERNAL";
})(CollectionExposure || (CollectionExposure = {}));
var HttpsPolicy;
(function(HttpsPolicy2) {
  HttpsPolicy2["UNKNOWN_HTTPS_POLICY"] = "UNKNOWN_HTTPS_POLICY";
  HttpsPolicy2["DISALLOW"] = "DISALLOW";
  HttpsPolicy2["ALLOW"] = "ALLOW";
  HttpsPolicy2["ENFORCE"] = "ENFORCE";
})(HttpsPolicy || (HttpsPolicy = {}));
var Flag;
(function(Flag2) {
  Flag2["UNKNOWN_FLAG"] = "UNKNOWN_FLAG";
  Flag2["URL_MIGRATED"] = "URL_MIGRATED";
  Flag2["USE_HTTPS"] = "USE_HTTPS";
  Flag2["EDITOR_X"] = "EDITOR_X";
  Flag2["BLOCKED"] = "BLOCKED";
  Flag2["DONT_USE_DEFAULT_ROUTING"] = "DONT_USE_DEFAULT_ROUTING";
  Flag2["STUDIO"] = "STUDIO";
  Flag2["CRITICAL_ASSET"] = "CRITICAL_ASSET";
  Flag2["ODEDITOR"] = "ODEDITOR";
  Flag2["PICASSO"] = "PICASSO";
})(Flag || (Flag = {}));
var PendingReason;
(function(PendingReason2) {
  PendingReason2["UNKNOWN"] = "UNKNOWN";
  PendingReason2["PREMIUM"] = "PREMIUM";
  PendingReason2["APP_MARKET"] = "APP_MARKET";
})(PendingReason || (PendingReason = {}));
var ResolutionMethod;
(function(ResolutionMethod2) {
  ResolutionMethod2["QUERY_PARAM"] = "QUERY_PARAM";
  ResolutionMethod2["SUBDOMAIN"] = "SUBDOMAIN";
  ResolutionMethod2["SUBDIRECTORY"] = "SUBDIRECTORY";
})(ResolutionMethod || (ResolutionMethod = {}));
var DeleteStatus;
(function(DeleteStatus2) {
  DeleteStatus2["UNKNOWN"] = "UNKNOWN";
  DeleteStatus2["TRASH"] = "TRASH";
  DeleteStatus2["DELETED"] = "DELETED";
  DeleteStatus2["PENDING_PURGE"] = "PENDING_PURGE";
  DeleteStatus2["PURGED_EXTERNALLY"] = "PURGED_EXTERNALLY";
})(DeleteStatus || (DeleteStatus = {}));
var Context;
(function(Context2) {
  Context2["UNKNOWN"] = "UNKNOWN";
  Context2["CREATE"] = "CREATE";
  Context2["UPDATE"] = "UPDATE";
  Context2["HARD_DELETE"] = "HARD_DELETE";
  Context2["ARCHIVE"] = "ARCHIVE";
  Context2["RESTORE"] = "RESTORE";
  Context2["UPDATE_DELETED"] = "UPDATE_DELETED";
  Context2["PURGED_EXTERNALLY"] = "PURGED_EXTERNALLY";
})(Context || (Context = {}));
var SiteCreatedContext;
(function(SiteCreatedContext2) {
  SiteCreatedContext2["OTHER"] = "OTHER";
  SiteCreatedContext2["FROM_TEMPLATE"] = "FROM_TEMPLATE";
  SiteCreatedContext2["DUPLICATE_BY_SITE_TRANSFER"] = "DUPLICATE_BY_SITE_TRANSFER";
  SiteCreatedContext2["DUPLICATE"] = "DUPLICATE";
  SiteCreatedContext2["OLD_SITE_TRANSFER"] = "OLD_SITE_TRANSFER";
  SiteCreatedContext2["FLASH"] = "FLASH";
})(SiteCreatedContext || (SiteCreatedContext = {}));
var AssetState;
(function(AssetState2) {
  AssetState2["UNKNOWN"] = "UNKNOWN";
  AssetState2["ENABLED"] = "ENABLED";
  AssetState2["DISABLED"] = "DISABLED";
  AssetState2["PENDING"] = "PENDING";
  AssetState2["DEMO"] = "DEMO";
})(AssetState || (AssetState = {}));
var PlacementType;
(function(PlacementType2) {
  PlacementType2["BEFORE"] = "BEFORE";
  PlacementType2["AFTER"] = "AFTER";
  PlacementType2["REPLACE"] = "REPLACE";
})(PlacementType || (PlacementType = {}));
var DayOfWeek;
(function(DayOfWeek2) {
  DayOfWeek2["MONDAY"] = "MONDAY";
  DayOfWeek2["TUESDAY"] = "TUESDAY";
  DayOfWeek2["WEDNESDAY"] = "WEDNESDAY";
  DayOfWeek2["THURSDAY"] = "THURSDAY";
  DayOfWeek2["FRIDAY"] = "FRIDAY";
  DayOfWeek2["SATURDAY"] = "SATURDAY";
  DayOfWeek2["SUNDAY"] = "SUNDAY";
})(DayOfWeek || (DayOfWeek = {}));
var V4ResolutionMethod;
(function(V4ResolutionMethod2) {
  V4ResolutionMethod2["QUERY_PARAM"] = "QUERY_PARAM";
  V4ResolutionMethod2["SUBDOMAIN"] = "SUBDOMAIN";
  V4ResolutionMethod2["SUBDIRECTORY"] = "SUBDIRECTORY";
})(V4ResolutionMethod || (V4ResolutionMethod = {}));
var WebhookIdentityType;
(function(WebhookIdentityType2) {
  WebhookIdentityType2["UNKNOWN"] = "UNKNOWN";
  WebhookIdentityType2["ANONYMOUS_VISITOR"] = "ANONYMOUS_VISITOR";
  WebhookIdentityType2["MEMBER"] = "MEMBER";
  WebhookIdentityType2["WIX_USER"] = "WIX_USER";
  WebhookIdentityType2["APP"] = "APP";
})(WebhookIdentityType || (WebhookIdentityType = {}));
var Cause;
(function(Cause2) {
  Cause2["EMPTY"] = "EMPTY";
  Cause2["NAMESPACE_LIMIT_REACHED"] = "NAMESPACE_LIMIT_REACHED";
  Cause2["AUTOMATION_USER_LIMIT_REACHED"] = "AUTOMATION_USER_LIMIT_REACHED";
  Cause2["WIX_EMPLOYEE_LIMIT_REACHED"] = "WIX_EMPLOYEE_LIMIT_REACHED";
})(Cause || (Cause = {}));
var UrlFilter;
(function(UrlFilter2) {
  UrlFilter2["NO_URL_TYPE_FILTER"] = "NO_URL_TYPE_FILTER";
  UrlFilter2["FREE"] = "FREE";
})(UrlFilter || (UrlFilter = {}));
var MigrationResult;
(function(MigrationResult2) {
  MigrationResult2["UNKNOWN_FORMAT"] = "UNKNOWN_FORMAT";
  MigrationResult2["OK"] = "OK";
  MigrationResult2["SKIP"] = "SKIP";
})(MigrationResult || (MigrationResult = {}));
var MigrateEmbeddedServiceToTpaResponseMigrationResult;
(function(MigrateEmbeddedServiceToTpaResponseMigrationResult2) {
  MigrateEmbeddedServiceToTpaResponseMigrationResult2["UNKNOWN_FORMAT"] = "UNKNOWN_FORMAT";
  MigrateEmbeddedServiceToTpaResponseMigrationResult2["OK"] = "OK";
  MigrateEmbeddedServiceToTpaResponseMigrationResult2["SKIP"] = "SKIP";
})(MigrateEmbeddedServiceToTpaResponseMigrationResult || (MigrateEmbeddedServiceToTpaResponseMigrationResult = {}));

// ../../node_modules/@wix/ambassador-document-management-document-store-v1-transaction/build/es/http.impl.js
init_esm_shims();
var _distributeRequest = {};
var _distributeResponse = {};
function resolveComWixpressEditorApiDocumentStoreServiceUrl(opts) {
  var domainToMappings = {
    "api._api_base_domain_": [
      {
        srcPath: "/editor-document-store",
        destPath: ""
      }
    ],
    "www._base_domain_": [
      {
        srcPath: "/_api/editor-document-store",
        destPath: ""
      }
    ],
    "editor._base_domain_": [
      {
        srcPath: "/_api/editor-document-store",
        destPath: ""
      }
    ],
    "blocks._base_domain_": [
      {
        srcPath: "/_api/editor-document-store",
        destPath: ""
      }
    ],
    "create.editorx": [
      {
        srcPath: "/_api/editor-document-store",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function distribute(payload) {
  var _a = serializer(_distributeRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_distributeResponse, {}).fromJSON;
  function __distribute(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.document_management.document_store.v1.transaction",
      method: "POST",
      methodFqn: "com.wixpress.editor.api.DocumentStoreService.Distribute",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveComWixpressEditorApiDocumentStoreServiceUrl({
        protoPath: "/v1/distribute",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __distribute.fromReq = fromReq;
  __distribute.__isAmbassador = true;
  return __distribute;
}

// ../metasite-manager-client/src/schemas.ts
init_esm_shims();
var clientSpecMapSchema = external_exports.record(
  external_exports.object({
    appDefinitionId: external_exports.string().optional(),
    permissions: external_exports.object({ revoked: external_exports.boolean() }).optional(),
    instanceId: external_exports.string().optional()
  })
);
var createMetaSiteFromTemplateSchema = external_exports.object({
  metaSite: external_exports.object({
    metaSiteId: external_exports.string()
  })
});
var getMetaSiteUrlSchema = external_exports.object({
  url: external_exports.string(),
  published: external_exports.boolean()
});

// ../metasite-manager-client/src/metasite-manager-client.ts
var MetasiteManagerClient = class {
  constructor(httpClient) {
    this.httpClient = httpClient;
  }
  getClientSpecMap = async (metaSiteId) => {
    try {
      const { data } = await this.httpClient.request({
        url: `/_api/msm/v1/meta-site/editor-client-spec-map/${metaSiteId}`
      });
      return clientSpecMapSchema.parse(data);
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToGetClientSpecMap(),
        cause: e
      });
    }
  };
  createMetaSiteFromTemplate = async (request) => {
    try {
      const { data } = await this.httpClient.request(
        createMetaSiteFromTemplate(request)
      );
      return createMetaSiteFromTemplateSchema.parse(data).metaSite;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToCreateMetaSiteFromTemplate(),
        cause: e
      });
    }
  };
  getSiteInstalledApps = async (metaSiteId) => {
    try {
      const clientSpecMap = await this.getClientSpecMap(metaSiteId);
      return Object.values(clientSpecMap).filter((spec) => spec.appDefinitionId && !spec.permissions?.revoked).map((spec) => spec.appDefinitionId);
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToGetSiteInstalledApps(),
        cause: e
      });
    }
  };
  getInstalledAppInstanceId = async ({
    metaSiteId,
    appId
  }) => {
    try {
      const clientSpecMap = await this.getClientSpecMap(metaSiteId);
      const installedApp = Object.values(clientSpecMap).find(
        (spec) => spec.appDefinitionId === appId
      );
      return installedApp?.instanceId ?? "";
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToGetSiteInstalledAppInstanceId(),
        cause: e
      });
    }
  };
  getMetaSiteUrl = async () => {
    try {
      const { data } = await this.httpClient.request(
        getUrl({ urlFilter: UrlFilter.NO_URL_TYPE_FILTER })
      );
      return getMetaSiteUrlSchema.parse(data);
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToGetUrl(),
        cause: e
      });
    }
  };
  distributeClientUpdate = async (appId) => {
    try {
      await this.httpClient.request(
        distribute({
          payloads: [
            {
              id: appId,
              messageType: "MANIFEST_UPDATE",
              data: {
                appId
              }
            }
          ],
          branchId: "00000000-0000-0000-0000-000000000000"
        })
      );
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToDistributeClientManifestUpdate(),
        cause: e
      });
    }
  };
};

// ../metasite-manager-client/src/useMetasiteManagerClient.ts
function useMetasiteManagerClient({
  siteId
} = {}) {
  const httpClient = useHttpClient({ type: "general", siteId });
  const client = (0, import_react25.useMemo)(
    () => new MetasiteManagerClient(httpClient),
    [httpClient]
  );
  return usePanoramaMethodLogger(client);
}

// ../cli-astro-commands/src/components/DevCommand/app-flow/useERCManifestUpdateNotifier.ts
function useERCManifestUpdateNotifier() {
  const { siteId } = useSite();
  const { devCenterWatcher } = useDevEnvironment();
  const metasiteManagerClient = useMetasiteManagerClient({ siteId });
  const {
    model: {
      config: { appId }
    }
  } = useProjectModel();
  const writeToDebugLog = useDebugLog();
  const errorReporter = useErrorReporter();
  (0, import_react26.useEffect)(() => {
    const unsubscribe = devCenterWatcher.onManifestUpdated(
      ({ updatedComponents }) => {
        const editorComponentsUpdated = updatedComponents.filter(
          (comp) => comp.compType === ComponentType.PANEL || comp.compType === ComponentType.EDITOR_REACT_COMPONENT
        );
        if (editorComponentsUpdated.length > 0) {
          metasiteManagerClient.distributeClientUpdate(appId).catch((error) => {
            errorReporter.reportError(error);
            writeToDebugLog(error);
          });
        }
      }
    );
    return () => {
      unsubscribe();
    };
  }, [
    devCenterWatcher,
    metasiteManagerClient,
    appId,
    writeToDebugLog,
    errorReporter
  ]);
}

// ../cli-astro-commands/src/components/DevCommand/app-flow/screen-state.ts
init_esm_shims();
var import_variant12 = __toESM(require_lib(), 1);
var ScreenState = (0, import_variant12.variant)({
  Home: {},
  SiteSelector: {}
});

// ../cli-astro-commands/src/components/DevCommand/app-flow/SiteSelectorScreen.tsx
init_esm_shims();
var import_react28 = __toESM(require_react(), 1);

// ../cli-astro-commands/src/components/CloseScreen/index.tsx
init_esm_shims();

// ../cli-astro-commands/src/components/CloseScreen/CloseScreen.tsx
init_esm_shims();
var import_react27 = __toESM(require_react(), 1);
var CloseScreen = ({ onClose }) => {
  const bi = useWixCliAppBi();
  use_input_default((_, key) => {
    if (key.escape) {
      bi.cliAction({
        question: "Press to close",
        questionKey: "general.close_screen",
        action: "close",
        key: "esc"
      });
      onClose();
    }
  });
  return /* @__PURE__ */ import_react27.default.createElement(Text, { skin: "secondary" }, "Press ", /* @__PURE__ */ import_react27.default.createElement(Key, { value: "esc", skin: "secondary" }), " to close");
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/SiteSelectorScreen.tsx
var SiteSelectorScreen = ({ onScreenChange }) => {
  const { model } = useProjectModel();
  const biLogger = useBiLogger();
  const { siteId, setSiteId } = useSite();
  const { reportError } = useErrorReporter();
  const [error, setError] = (0, import_react28.useState)(null);
  const handleError = (0, import_react28.useCallback)(
    (error2) => {
      reportError(error2);
      setError(error2);
    },
    [reportError, setError]
  );
  const handleSubmit = (0, import_react28.useCallback)(
    async (site) => {
      try {
        await setSiteId(site.id);
        onScreenChange(ScreenState.Home());
      } catch (e) {
        handleError(e);
      }
    },
    [setSiteId, onScreenChange, handleError]
  );
  return /* @__PURE__ */ import_react28.default.createElement(Box_default, { flexDirection: "column", gap: 1 }, /* @__PURE__ */ import_react28.default.createElement(Box_default, { gap: 1 }, /* @__PURE__ */ import_react28.default.createElement(PointerIcon, null), /* @__PURE__ */ import_react28.default.createElement(Text, null, "Current development site: ", siteId)), /* @__PURE__ */ import_react28.default.createElement(Box_default, { flexDirection: "column" }, /* @__PURE__ */ import_react28.default.createElement(
    SiteSelector,
    {
      appId: model.config.appId,
      biLogger,
      onSubmit: handleSubmit,
      onError: handleError
    }
  ), error ? /* @__PURE__ */ import_react28.default.createElement(
    ErrorViewer,
    {
      error,
      systemErrorOverride: /* @__PURE__ */ import_react28.default.createElement(Alert, { type: "error" }, "Failed to change development site. Try selecting a different site or run the dev command again.")
    }
  ) : null), /* @__PURE__ */ import_react28.default.createElement(CloseScreen, { onClose: () => onScreenChange(ScreenState.Home()) }));
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/HomeScreen.tsx
init_esm_shims();
var import_react30 = __toESM(require_react(), 1);
import process2 from "node:process";

// ../cli-astro-commands/src/components/DevCommand/app-flow/SwitchSite.tsx
init_esm_shims();
var import_react29 = __toESM(require_react(), 1);
var SwitchSite = ({ onScreenChange }) => {
  const bi = useWixCliAppBi();
  use_input_default(async (input) => {
    if (input === "c") {
      bi.cliAction({
        question: "Switch development site",
        questionKey: "dev_command.dev_site.change",
        action: "change_site",
        key: input
      });
      onScreenChange(ScreenState.SiteSelector());
    }
  });
  return /* @__PURE__ */ import_react29.default.createElement(Text, { skin: "secondary" }, "(Press ", /* @__PURE__ */ import_react29.default.createElement(Key, { value: "C", skin: "secondary" }), " to switch)");
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/HomeScreen.tsx
var HomeScreen = ({ onScreenChange }) => {
  const { siteId, canChangeSite } = useSite();
  const { devArmTag } = useDevEnvironment();
  return /* @__PURE__ */ import_react30.default.createElement(import_react30.default.Fragment, null, /* @__PURE__ */ import_react30.default.createElement(Box_default, { gap: 1 }, /* @__PURE__ */ import_react30.default.createElement(Text, null, "Current development site:"), /* @__PURE__ */ import_react30.default.createElement(Text, { bold: true, skin: "info" }, siteId), process2.stdin.isTTY && canChangeSite && /* @__PURE__ */ import_react30.default.createElement(SwitchSite, { onScreenChange })), /* @__PURE__ */ import_react30.default.createElement(Box_default, { paddingTop: 1, paddingBottom: 1, flexDirection: "column", gap: 1 }, /* @__PURE__ */ import_react30.default.createElement(Text, null, "Open the preview on:"), /* @__PURE__ */ import_react30.default.createElement(Box_default, { paddingLeft: 2, flexDirection: "column" }, /* @__PURE__ */ import_react30.default.createElement(
    RedirectLink,
    {
      platform: "site",
      versionOverrideId: devArmTag,
      siteId
    }
  ), /* @__PURE__ */ import_react30.default.createElement(
    RedirectLink,
    {
      platform: "editor",
      versionOverrideId: devArmTag,
      siteId
    }
  ), /* @__PURE__ */ import_react30.default.createElement(
    RedirectLink,
    {
      platform: "dashboard",
      versionOverrideId: devArmTag,
      siteId
    }
  )), /* @__PURE__ */ import_react30.default.createElement(LinkClickTip, null)));
};

// ../cli-astro-commands/src/components/DevCommand/app-flow/AppDev.tsx
var AppDev = () => {
  const [screen, setScreen] = (0, import_react31.useState)(ScreenState.Home());
  useAppDeploymentTopologyUpdater();
  useERCManifestUpdateNotifier();
  return (0, import_variant13.match)(screen, {
    Home: () => /* @__PURE__ */ import_react31.default.createElement(HomeScreen, { onScreenChange: setScreen }),
    SiteSelector: () => /* @__PURE__ */ import_react31.default.createElement(SiteSelectorScreen, { onScreenChange: setScreen })
  });
};

// ../cli-astro-commands/src/components/DevCommand/AppDevFlow.tsx
var AppDevFlow = () => {
  return /* @__PURE__ */ import_react32.default.createElement(SiteProvider, null, /* @__PURE__ */ import_react32.default.createElement(AppDev, null));
};

// ../cli-astro-commands/src/components/DevCommand/DevCommand.tsx
var DevCommand = ({
  port,
  allowedHosts,
  serverExposedUrl
}) => {
  const {
    model: { config, projectFolder }
  } = useProjectModel();
  const exit = useExit();
  const logger = useAstroLogger({ isPrefixed: false });
  const astroProcess = (0, import_react33.useRef)();
  const fetchDevMetadataAction = useFetchDevMetadata();
  useAsync(async () => {
    const repoType = await getRepoType(projectFolder);
    const packageManager = await createPackageManager(repoType);
    const astro = runAstroDev({
      packageManager,
      projectFolder,
      port,
      allowedHosts
    });
    astroProcess.current = astro;
    astro.stdout?.once(EVENT_SERVER_ADDRESS, (address) => {
      void fetchDevMetadataAction.execute(address);
    });
    astro.stdout?.on(EVENT_LINE, (line) => logger.log(line));
    astro.stderr?.on(EVENT_LINE, (line) => logger.error(line));
    void astro.on("exit", () => {
      astroProcess.current?.stdout?.destroy();
      astroProcess.current?.stderr?.destroy();
      astroProcess.current?.stdin?.end();
      astroProcess.current = void 0;
      exit(
        new CliError({
          cause: void 0,
          code: CliErrorCode.DevCommandFailed()
        })
      );
    });
  }, []);
  (0, import_react33.useEffect)(() => {
    return () => {
      if (astroProcess.current?.pid) {
        try {
          astroProcess.current.kill("SIGTERM");
        } catch {
        }
      }
    };
  }, []);
  return (0, import_variant14.match)(fetchDevMetadataAction.status, {
    NotRequested: () => /* @__PURE__ */ import_react33.default.createElement(Spinner, { text: "Starting dev environment..." }),
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react33.default.createElement(Spinner, { text: "Checking dev environment settings..." }),
    Success: ({ result: { devMetadata, serverLocalUrl } }) => /* @__PURE__ */ import_react33.default.createElement(DevScreenBorder, null, /* @__PURE__ */ import_react33.default.createElement(
      DevEnvironmentProvider,
      {
        serverLocalUrl,
        serverExposedUrl,
        devMetadata
      },
      config.projectType === "Site" ? /* @__PURE__ */ import_react33.default.createElement(SiteDevFlow, null) : /* @__PURE__ */ import_react33.default.createElement(AppDevFlow, null)
    ))
  });
};
export {
  DevCommand
};
//# sourceMappingURL=DevCommand-VW6RFNCM.js.map