import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  DeploymentStatus,
  useDocumentManagementClient
} from "./chunk-Y6GHMYGK.js";
import {
  createSiteFsManager
} from "./chunk-RGLNHNAS.js";
import {
  loadProjectRootFiles
} from "./chunk-3N5KS75V.js";
import {
  useProjectModel
} from "./chunk-VRIBQKXZ.js";
import {
  useVeloClient
} from "./chunk-R5WNFZTS.js";
import {
  GridAppLayout
} from "./chunk-QRGKMYDD.js";
import {
  useHttpClient
} from "./chunk-BRX4HWJE.js";
import {
  require_react
} from "./chunk-TODKQSCF.js";
import {
  getTestOverrides
} from "./chunk-XZUGLEBK.js";
import {
  CliError,
  CliErrorCode
} from "./chunk-WGV2XQSB.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-EXLZF52D.js";

// ../cli-site/src/components/PreviewCommand/useCreatePreview.ts
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);

// ../../node_modules/@wix/anyide-document-deployment/dist/src/index.js
init_esm_shims();

// ../../node_modules/@wix/anyide-document-deployment/dist/src/apis/updateSite.js
init_esm_shims();
import { promisify } from "node:util";
import { brotliCompress } from "node:zlib";

// ../../node_modules/@wix/anyide-document-deployment/dist/src/apis/urls.js
init_esm_shims();
var serverlessUrl = () => "https://editor.wix.com/_serverless/dm-anyide-site-deployment";
var getBaseUrl = () => `${serverlessUrl()}/getBase`;
var updateSiteUrl = () => `${serverlessUrl()}/updateSite`;
var getUpdateSiteStatusUrl = (updateSiteTaskId) => `${serverlessUrl()}/getUpdateSiteStatus/${updateSiteTaskId}`;

// ../../node_modules/@wix/anyide-document-deployment/dist/src/apis/updateSite.js
var brotliCompressAsync = promisify(brotliCompress);
var sendUpdateSiteRequest = async (httpClient, request) => {
  const { data } = await httpClient.post(updateSiteUrl(), request);
  return data;
};
var updateSite = async (httpClient, documentUpdate, branchId, revision) => {
  const stringifiedDocumentUpdate = JSON.stringify(documentUpdate);
  const compressedWmlSite = (await brotliCompressAsync(stringifiedDocumentUpdate)).toString("base64");
  const { updateSiteTaskId } = await sendUpdateSiteRequest(httpClient, {
    compressedWmlSite,
    branchId,
    revision
  });
  return updateSiteTaskId;
};

// ../../node_modules/@wix/anyide-document-deployment/dist/src/utils/filterDocumentPagesByHashes.js
init_esm_shims();

// ../../node_modules/@wix/anyide-document-deployment/dist/src/utils/hashWml.js
init_esm_shims();
import crypto from "node:crypto";
var md5 = (str) => crypto.createHash("md5").update(str).digest("hex");
var stringifyWmlFile = ({ content }) => content;
var hashWml = ({ structure, style, data, version }) => {
  const wmlString = version + stringifyWmlFile(structure) + stringifyWmlFile(data) + stringifyWmlFile(style);
  return md5(wmlString);
};

// ../../node_modules/@wix/anyide-document-deployment/dist/src/utils/filterDocumentPagesByHashes.js
var filterDocumentPagesByHashes = (hashes, document) => {
  const filteredDocument = { pages: {} };
  for (const pageId in document.pages) {
    if (hashes[pageId] === void 0) {
      filteredDocument.pages[pageId] = document.pages[pageId];
    }
  }
  for (const pageId in hashes) {
    const documentPage = document.pages[pageId];
    if (documentPage) {
      const pageHash = hashWml(documentPage.data);
      if (pageHash !== hashes[pageId]) {
        filteredDocument.pages[pageId] = documentPage;
      }
    } else {
      filteredDocument.pages[pageId] = null;
    }
  }
  return filteredDocument;
};

// ../../node_modules/@wix/anyide-document-deployment/dist/src/status.js
init_esm_shims();

// ../../node_modules/@wix/anyide-document-deployment/dist/src/apis/getTaskStatus.js
init_esm_shims();
var getTaskStatus = async (httpClient, taskId) => {
  const { data } = await httpClient.get(getUpdateSiteStatusUrl(taskId));
  return data;
};

// ../../node_modules/@wix/anyide-document-deployment/dist/src/status.js
var subscribeToUpdateSiteTaskStatus = (httpClient, updateSiteTaskId, options = {}) => {
  const { onStatusChange, pollInterval: pollInterval2 = 1e3, timeout = 1e3 * 60 * 5 } = options;
  return new Promise((resolve, reject) => {
    const cleanup = () => {
      clearInterval(intervalId);
      clearTimeout(timeoutId);
    };
    const timeoutId = setTimeout(() => {
      cleanup();
      reject(new Error("deployDocument timeout exceeded"));
    }, timeout);
    const intervalId = setInterval(async () => {
      try {
        const taskStatus = await getTaskStatus(httpClient, updateSiteTaskId);
        onStatusChange?.(taskStatus);
        if (taskStatus.state === "FAILED") {
          cleanup();
          reject(new Error(`Action ${taskStatus.action} failed with error: ${taskStatus.extras?.error}`));
        }
        if (taskStatus.action === "CREATE_REVISION" && taskStatus.state === "DONE") {
          cleanup();
          resolve(taskStatus.extras);
        }
      } catch (error) {
        cleanup();
        reject(error);
      }
    }, pollInterval2);
  });
};

// ../../node_modules/@wix/anyide-document-deployment/dist/src/apis/getBase.js
init_esm_shims();
var getBase = async (httpClient) => {
  const { data } = await httpClient.get(getBaseUrl());
  return data;
};

// ../../node_modules/@wix/anyide-document-deployment/dist/src/index.js
var deployDocument = async (document, options) => {
  const { branchId, revision, hashes } = await getBase(options.httpClient);
  const { httpClient, onStatusChange, pollInterval: pollInterval2, timeout } = options;
  const documentUpdate = filterDocumentPagesByHashes(hashes, document);
  if (Object.keys(documentUpdate.pages).length === 0) {
    return {
      branchId,
      revision
    };
  }
  const updateSiteTaskId = await updateSite(httpClient, documentUpdate, branchId, revision);
  return subscribeToUpdateSiteTaskStatus(httpClient, updateSiteTaskId, { onStatusChange, pollInterval: pollInterval2, timeout });
};

// ../cli-site/src/components/PreviewCommand/useDeploySitePreview.ts
init_esm_shims();
var import_react = __toESM(require_react(), 1);
function useDeploySitePreview() {
  const { model } = useProjectModel();
  const { deploySitePreview } = useVeloClient();
  return (0, import_react.useCallback)(
    async ({ branchId, revision, code }) => {
      const rootFiles = await loadProjectRootFiles(model.projectFolder);
      return deploySitePreview({
        deploymentData: {
          branchId,
          revision: String(revision),
          content: {
            ...code,
            files: code.files.concat(rootFiles),
            layout: GridAppLayout[code.layout]
          }
        }
      });
    },
    [deploySitePreview, model.projectFolder]
  );
}

// ../cli-site/src/components/PreviewCommand/useCreatePreview.ts
var { pollInterval } = getTestOverrides();
function toSiteUrl(deploymentUrl) {
  const url = new URL(deploymentUrl);
  url.search = "";
  return url.toString();
}
function useCreatePreview() {
  const dmClient = useDocumentManagementClient();
  const { model } = useProjectModel();
  const httpClient = useHttpClient({ type: "editor" });
  const deploySitePreview = useDeploySitePreview();
  return (0, import_react2.useCallback)(async () => {
    const siteFsManager = await createSiteFsManager(model.projectFolder);
    const [code, document] = await Promise.all([
      siteFsManager.getCode(),
      siteFsManager.getDocument()
    ]);
    const { branchId, revision } = await deployDocument(document, {
      httpClient,
      pollInterval
    }).catch((error) => {
      throw new CliError({
        code: CliErrorCode.FailedToDeployDocument(),
        cause: error
      });
    });
    const preview = await deploySitePreview({ branchId, revision, code });
    return {
      deploymentId: preview.deploymentId,
      previewUrl: preview.deploymentShortUrl ?? preview.deploymentUrl,
      siteUrl: toSiteUrl(preview.deploymentUrl),
      deploymentStatus: preview.isPublishPipelineDeployment ? await dmClient.getDeploymentDetails(preview.deploymentId) : DeploymentStatus.Success()
    };
  }, [model.projectFolder, httpClient, deploySitePreview, dmClient]);
}

export {
  useCreatePreview
};
//# sourceMappingURL=chunk-OXWISUKT.js.map