import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  useHttpClient
} from "./chunk-BRX4HWJE.js";
import {
  usePanoramaMethodLogger
} from "./chunk-ZBFOAJ5H.js";
import {
  isHttpError,
  pRetry,
  resolveUrl,
  serializer,
  toURLSearchParams
} from "./chunk-YHFCDWGT.js";
import {
  require_index_node
} from "./chunk-IVQPYJ5M.js";
import {
  require_react
} from "./chunk-TODKQSCF.js";
import {
  getTestOverrides
} from "./chunk-XZUGLEBK.js";
import {
  external_exports
} from "./chunk-SDLCFZRL.js";
import {
  CliError,
  CliErrorCode
} from "./chunk-WGV2XQSB.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-EXLZF52D.js";

// ../backend-as-a-service-client/src/useBackendAsAServiceClient.ts
init_esm_shims();
var import_react = __toESM(require_react(), 1);

// ../cli-http-client/src/fetch-error.ts
init_esm_shims();
var import_http_client = __toESM(require_index_node(), 1);
async function createHttpErrorFromFetch(originalResponse) {
  const res = originalResponse.clone();
  return (0, import_http_client.createHttpError)({
    name: "Error",
    message: `Request failed with status code ${res.status}`,
    response: {
      config: {},
      data: await res.text(),
      status: res.status,
      statusText: res.statusText,
      headers: Object.fromEntries(res.headers)
    },
    code: res.statusText,
    config: {},
    toJSON: () => res,
    __CANCEL__: false
  });
}

// ../backend-as-a-service-client/src/backend-as-a-service-client.ts
init_esm_shims();
import { randomUUID } from "node:crypto";

// ../../node_modules/@wix/ambassador-velo-backend-v1-app-deployment/es/build/http.impl.js
init_esm_shims();
var _appDeployment = {
  createdDate: "google.protobuf.Timestamp",
  updatedDate: "google.protobuf.Timestamp"
};
var _completeAppDeploymentRequest = { appDeployment: "_appDeployment" };
var _completeAppDeploymentResponse = { appDeployment: "_appDeployment" };
var _createAppDeploymentRequest = { appDeployment: "_appDeployment" };
var _createAppDeploymentResponse = { appDeployment: "_appDeployment" };
function resolveWixVeloBackendV1AppDeploymentManagementUrl(opts) {
  var domainToMappings = {
    "manage._base_domain_": [
      {
        srcPath: "/_api/wix-code-app-deployments",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function createAppDeployment(payload) {
  var _a = serializer(_createAppDeploymentRequest, { _appDeployment }), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_createAppDeploymentResponse, {
    _appDeployment
  }).fromJSON;
  function __createAppDeployment(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_deployment",
      method: "POST",
      methodFqn: "wix.velo.backend.v1.AppDeploymentManagement.CreateAppDeployment",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppDeploymentManagementUrl({
        protoPath: "/v1/app-projects/{appDeployment.appProjectId}/app-deployments",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __createAppDeployment.fromReq = fromReq;
  __createAppDeployment.__isAmbassador = true;
  return __createAppDeployment;
}
function completeAppDeployment(payload) {
  var _a = serializer(_completeAppDeploymentRequest, { _appDeployment }), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_completeAppDeploymentResponse, {
    _appDeployment
  }).fromJSON;
  function __completeAppDeployment(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_deployment",
      method: "POST",
      methodFqn: "wix.velo.backend.v1.AppDeploymentManagement.CompleteAppDeployment",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppDeploymentManagementUrl({
        protoPath: "/v1/app-projects/{appDeployment.appProjectId}/app-deployments/{appDeployment.id}/complete",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __completeAppDeployment.fromReq = fromReq;
  __completeAppDeployment.__isAmbassador = true;
  return __completeAppDeployment;
}

// ../../node_modules/@wix/ambassador-velo-backend-v1-app-project/build/es/http.impl.js
init_esm_shims();
var _appProject = {
  createdDate: "google.protobuf.Timestamp",
  updatedDate: "google.protobuf.Timestamp",
  customDomain: "_customDomain"
};
var _createAppProjectRequest = { appProject: "_appProject" };
var _createAppProjectResponse = { appProject: "_appProject" };
var _customDomain = { connectionDate: "google.protobuf.Timestamp" };
var _getAppProjectRequest = {};
var _getAppProjectResponse = { appProject: "_appProject" };
function resolveWixVeloBackendV1AppProjectLifecycleUrl(opts) {
  var domainToMappings = {
    "manage._base_domain_": [
      {
        srcPath: "/_api/wix-code-app-projects",
        destPath: ""
      }
    ],
    "www._base_domain_": [
      {
        srcPath: "/_api/wix-code-app-projects",
        destPath: ""
      }
    ],
    "vibe._base_domain_": [
      {
        srcPath: "/_api/wix-code-app-projects",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function createAppProject(payload) {
  var _a = serializer(_createAppProjectRequest, { _appProject, _customDomain }), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_createAppProjectResponse, {
    _appProject,
    _customDomain
  }).fromJSON;
  function __createAppProject(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_project",
      method: "POST",
      methodFqn: "wix.velo.backend.v1.AppProjectLifecycle.CreateAppProject",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppProjectLifecycleUrl({
        protoPath: "/v1/app-projects",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __createAppProject.fromReq = fromReq;
  __createAppProject.__isAmbassador = true;
  return __createAppProject;
}
function getAppProject(payload) {
  var _a = serializer(_getAppProjectRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_getAppProjectResponse, {
    _appProject,
    _customDomain
  }).fromJSON;
  function __getAppProject(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_project",
      method: "GET",
      methodFqn: "wix.velo.backend.v1.AppProjectLifecycle.GetAppProject",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppProjectLifecycleUrl({
        protoPath: "/v1/app-projects/{appProjectId}",
        data: serializedData,
        host
      }),
      params: toURLSearchParams(serializedData),
      transformResponse: fromRes
    };
    return metadata;
  }
  __getAppProject.fromReq = fromReq;
  __getAppProject.__isAmbassador = true;
  return __getAppProject;
}

// ../../node_modules/@wix/ambassador-velo-backend-v1-app-environment/build/es/http.impl.js
init_esm_shims();
var _appEnvironment = {
  createdDate: "google.protobuf.Timestamp",
  updatedDate: "google.protobuf.Timestamp"
};
var _getAppEnvironmentByNameRequest = {};
var _getAppEnvironmentByNameResponse = { appEnvironment: "_appEnvironment" };
var _removeAppEnvironmentVariablesRequest = {};
var _removeAppEnvironmentVariablesResponse = {
  appEnvironment: "_appEnvironment"
};
var _upsertAppEnvironmentRequest = {
  fieldMask: "google.protobuf.FieldMask",
  appEnvironment: "_appEnvironment"
};
var _upsertAppEnvironmentResponse = { appEnvironment: "_appEnvironment" };
function resolveWixVeloBackendV1AppEnvironmentManagementUrl(opts) {
  var domainToMappings = {
    "manage._base_domain_": [
      {
        srcPath: "/_api/wix-code-app-environments",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function upsertAppEnvironment(payload) {
  var _a = serializer(_upsertAppEnvironmentRequest, { _appEnvironment }), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_upsertAppEnvironmentResponse, {
    _appEnvironment
  }).fromJSON;
  function __upsertAppEnvironment(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_environment",
      method: "POST",
      methodFqn: "wix.velo.backend.v1.AppEnvironmentManagement.UpsertAppEnvironment",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppEnvironmentManagementUrl({
        protoPath: "/v1/app-projects/{appEnvironment.appProjectId}/app-environments/upsert/name/{appEnvironment.name}",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __upsertAppEnvironment.fromReq = fromReq;
  __upsertAppEnvironment.__isAmbassador = true;
  return __upsertAppEnvironment;
}
function getAppEnvironmentByName(payload) {
  var _a = serializer(_getAppEnvironmentByNameRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_getAppEnvironmentByNameResponse, {
    _appEnvironment
  }).fromJSON;
  function __getAppEnvironmentByName(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_environment",
      method: "GET",
      methodFqn: "wix.velo.backend.v1.AppEnvironmentManagement.GetAppEnvironmentByName",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppEnvironmentManagementUrl({
        protoPath: "/v1/app-projects/{appProjectId}/app-environments/name/{appEnvironmentName}",
        data: serializedData,
        host
      }),
      params: toURLSearchParams(serializedData),
      transformResponse: fromRes
    };
    return metadata;
  }
  __getAppEnvironmentByName.fromReq = fromReq;
  __getAppEnvironmentByName.__isAmbassador = true;
  return __getAppEnvironmentByName;
}
function removeAppEnvironmentVariables(payload) {
  var _a = serializer(_removeAppEnvironmentVariablesRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_removeAppEnvironmentVariablesResponse, { _appEnvironment }).fromJSON;
  function __removeAppEnvironmentVariables(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.velo.backend.v1.app_environment",
      method: "POST",
      methodFqn: "wix.velo.backend.v1.AppEnvironmentManagement.RemoveAppEnvironmentVariables",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixVeloBackendV1AppEnvironmentManagementUrl({
        protoPath: "/v1/app-projects/{appProjectId}/app-environments/{appEnvironmentId}/remove",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __removeAppEnvironmentVariables.fromReq = fromReq;
  __removeAppEnvironmentVariables.__isAmbassador = true;
  return __removeAppEnvironmentVariables;
}

// ../backend-as-a-service-client/src/schemas.ts
init_esm_shims();

// ../../node_modules/@wix/ambassador-velo-backend-v1-app-deployment/es/build/types.impl.js
init_esm_shims();
var CloudProvider;
(function(CloudProvider2) {
  CloudProvider2["UNKNOWN_CLOUD_PROVIDER"] = "UNKNOWN_CLOUD_PROVIDER";
  CloudProvider2["CLOUD_FLARE"] = "CLOUD_FLARE";
  CloudProvider2["KUBERNETES"] = "KUBERNETES";
})(CloudProvider || (CloudProvider = {}));
var DeploymentState;
(function(DeploymentState2) {
  DeploymentState2["UNKNOWN_DEPLOYMENT_STATE"] = "UNKNOWN_DEPLOYMENT_STATE";
  DeploymentState2["STATICS_UPLOAD_PENDING"] = "STATICS_UPLOAD_PENDING";
  DeploymentState2["DEPLOY_SUCCESS"] = "DEPLOY_SUCCESS";
  DeploymentState2["DEPLOY_FAILED"] = "DEPLOY_FAILED";
})(DeploymentState || (DeploymentState = {}));
var SortOrder;
(function(SortOrder2) {
  SortOrder2["ASC"] = "ASC";
  SortOrder2["DESC"] = "DESC";
})(SortOrder || (SortOrder = {}));
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 = {}));

// ../backend-as-a-service-client/src/schemas.ts
var staticFileMetadata = external_exports.object({
  path: external_exports.string(),
  hash: external_exports.string(),
  size: external_exports.number().optional(),
  contentType: external_exports.string()
});
var StaticFileUploadUrlSchema = external_exports.object({
  uploadUrl: external_exports.string().url(),
  staticFileMetadata
});
var AppDeploymentSchema = external_exports.object({
  id: external_exports.string().uuid(),
  deploymentBaseUrl: external_exports.string(),
  cloudProviderOverride: external_exports.nativeEnum(CloudProvider)
}).passthrough();
var CompleteAppDeploymentSchema = external_exports.object({
  appDeployment: AppDeploymentSchema
});
var AppEnvironmentSchema = external_exports.object({
  appEnvironment: external_exports.object({
    id: external_exports.string(),
    variables: external_exports.record(external_exports.string()),
    secrets: external_exports.record(external_exports.string())
  }).passthrough()
});
var AppProjectSchema = external_exports.object({
  appProject: external_exports.object({
    id: external_exports.string().uuid(),
    baseUrl: external_exports.string().url()
  })
});
var CreateAppProjectSchema = external_exports.object({
  appProject: external_exports.object({
    id: external_exports.string().uuid(),
    baseUrl: external_exports.string().url()
  })
});
var CreateAppDeploymentSchema = external_exports.object({
  staticFilesUploadUrls: external_exports.array(StaticFileUploadUrlSchema).optional(),
  uploadAuthToken: external_exports.string().optional(),
  appDeployment: AppDeploymentSchema.optional(),
  uploadBuckets: external_exports.array(
    external_exports.object({
      hashes: external_exports.array(external_exports.string()).optional()
    })
  ).optional()
});
var StaticFileUploadSchema = external_exports.object({
  result: external_exports.object({
    // The `jwt` field is optional because it is only returned in the last file upload.
    jwt: external_exports.string().optional()
  }).optional()
}).passthrough();

// ../backend-as-a-service-client/src/backend-as-a-service-client.ts
var { minRetryTimeout } = getTestOverrides();
var APP_PROJECT_TYPE_ID = "79144b61-68b9-4b0b-bfa7-e3adfa610101";
var HEADLESS_PROJECT_TYPE_ID = "eb363dea-85a0-4159-9b05-949542be5079";
var BackendAsAServiceClient = class {
  constructor(httpClient) {
    this.httpClient = httpClient;
    this.retryOptions = {
      retries: 3,
      minTimeout: minRetryTimeout,
      maxTimeout: 3 * 1e3
    };
  }
  retryOptions;
  getAppProject = async (appId) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(getAppProject({ appProjectId: appId })),
        this.retryOptions
      );
      return AppProjectSchema.parse(data).appProject;
    } catch (e) {
      if (isHttpError(e) && e.response?.status === 404) {
        return;
      }
      throw new CliError({
        code: CliErrorCode.FailedToGetAppProject(),
        cause: e
      });
    }
  };
  createAppProject = async ({
    cloudProvider,
    projectType,
    ...appProjectOptions
  }) => {
    try {
      const { data } = await this.httpClient.request(
        createAppProject({
          appProject: {
            ...appProjectOptions,
            appProjectTypeId: projectType === "HEADLESS" ? HEADLESS_PROJECT_TYPE_ID : APP_PROJECT_TYPE_ID,
            cloudProviderOverride: cloudProvider
          }
        })
      );
      return CreateAppProjectSchema.parse(data).appProject;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedCreatingAppProject(),
        cause: e
      });
    }
  };
  createAppDeployment = async (appId, staticFilesMetadata, generateAppDeploymentGroupId) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(
          createAppDeployment({
            appDeployment: {
              appProjectId: appId,
              staticFilesMetadata,
              appDeploymentGroupId: generateAppDeploymentGroupId ? randomUUID() : void 0
            }
          })
        ),
        this.retryOptions
      );
      return CreateAppDeploymentSchema.parse(data);
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedCreatingAppDeployment(),
        cause: e
      });
    }
  };
  completeAppDeployment = async (appDeployment, staticsCompletionToken) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(
          completeAppDeployment({
            appDeployment,
            staticsCompletionToken
          })
        ),
        this.retryOptions
      );
      return CompleteAppDeploymentSchema.parse(data).appDeployment;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedFinalizingAppDeployment(),
        cause: e
      });
    }
  };
  postForm = async (endpointUrl, token, formData) => {
    try {
      const responseJson = await pRetry(
        async () => {
          const response = await fetch(endpointUrl, {
            method: "POST",
            headers: {
              Authorization: `Bearer ${token}`
            },
            body: formData
          });
          if (!response.ok) {
            const error = await createHttpErrorFromFetch(response);
            throw error;
          }
          return response.json();
        },
        { retries: 3 }
      );
      return StaticFileUploadSchema.parse(responseJson);
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToUploadStaticFiles(),
        cause: e,
        info: { endpointUrl }
      });
    }
  };
  putBinaryFile = async (endpointUrl, fileContent, contentType) => {
    try {
      await pRetry(
        async () => {
          const response = await fetch(endpointUrl, {
            method: "PUT",
            headers: {
              "Content-Type": contentType
            },
            body: fileContent
          });
          if (!response.ok) {
            const error = await createHttpErrorFromFetch(response);
            throw error;
          }
        },
        { retries: 3 }
      );
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToUploadStaticFiles(),
        cause: e,
        info: { endpointUrl }
      });
    }
  };
  // Env management
  getAppEnvironmentByName = async (appId, environment) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(
          getAppEnvironmentByName({
            appProjectId: appId,
            appEnvironmentName: environment
          })
        ),
        this.retryOptions
      );
      return AppEnvironmentSchema.parse(data).appEnvironment;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToPullEnvironment(),
        cause: e
      });
    }
  };
  upsertAppEnvironment = async (appId, environment, variables) => {
    try {
      const { data } = await this.httpClient.request(
        upsertAppEnvironment({
          appEnvironment: {
            appProjectId: appId,
            name: environment,
            variables
          }
        })
      );
      return AppEnvironmentSchema.parse(data).appEnvironment;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToSetEnvironmentVariable(),
        cause: e
      });
    }
  };
  removeAppEnvironmentVariable = async (appId, environment, variable) => {
    try {
      const appEnvironment = await this.getAppEnvironmentByName(
        appId,
        environment
      );
      const { data } = await pRetry(
        () => this.httpClient.request(
          removeAppEnvironmentVariables({
            appEnvironmentId: appEnvironment.id,
            appProjectId: appId,
            variables: [variable]
          })
        ),
        this.retryOptions
      );
      return AppEnvironmentSchema.parse(data).appEnvironment;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToRemoveEnvironmentVariable(),
        cause: e
      });
    }
  };
};

// ../backend-as-a-service-client/src/useBackendAsAServiceClient.ts
function useBackendAsAServiceClient() {
  const httpClient = useHttpClient({ type: "backoffice" });
  const client = (0, import_react.useMemo)(
    () => new BackendAsAServiceClient(httpClient),
    [httpClient]
  );
  return usePanoramaMethodLogger(client);
}

// ../backend-as-a-service-client/src/index.ts
init_esm_shims();

export {
  CloudProvider,
  useBackendAsAServiceClient
};
//# sourceMappingURL=chunk-I2LFFO2M.js.map