"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var client_exports = {};
__export(client_exports, {
  ApiClient: () => ApiClient
});
module.exports = __toCommonJS(client_exports);
var client = __toESM(require("@botpress/client"));
var import_semver = __toESM(require("semver"));
var import_yn = __toESM(require("yn"));
var errors = __toESM(require("../errors"));
var import_package_ref = require("../package-ref");
var paging = __toESM(require("./paging"));
var retry = __toESM(require("./retry"));
__reExport(client_exports, require("./types"), module.exports);
class ApiClient {
  constructor(props, _logger) {
    this._logger = _logger;
    const { apiUrl, token, workspaceId, botId } = props;
    this.client = new client.Client({
      apiUrl,
      token,
      workspaceId,
      botId,
      retry: retry.config,
      headers: { "x-multiple-integrations": "true" }
    });
    this.url = apiUrl;
    this.token = token;
    this.workspaceId = workspaceId;
    this.botId = botId;
  }
  client;
  url;
  token;
  workspaceId;
  botId;
  static newClient = (props, logger) => new ApiClient(props, logger);
  get isBotpressWorkspace() {
    const isBotpressWorkspace = (0, import_yn.default)(process.env.BP_IS_BOTPRESS_WORKSPACE);
    if (isBotpressWorkspace !== void 0) {
      return isBotpressWorkspace;
    }
    return [
      "6a76fa10-e150-4ff6-8f59-a300feec06c1",
      "95de33eb-1551-4af9-9088-e5dcb02efd09",
      "11111111-1111-1111-aaaa-111111111111"
    ].includes(this.workspaceId);
  }
  async safeListTables(req) {
    try {
      const result = await this.client.listTables(req);
      return { success: true, tables: result.tables };
    } catch (thrown) {
      const error = thrown instanceof Error ? thrown : new Error(String(thrown));
      return { success: false, error };
    }
  }
  async getWorkspace() {
    return this.client.getWorkspace({ id: this.workspaceId });
  }
  async findWorkspaceByHandle(handle) {
    const { workspaces } = await this.client.listWorkspaces({ handle });
    return workspaces[0];
  }
  switchWorkspace(workspaceId) {
    return ApiClient.newClient({ apiUrl: this.url, token: this.token, workspaceId }, this._logger);
  }
  switchBot(botId) {
    return ApiClient.newClient(
      { apiUrl: this.url, token: this.token, botId, workspaceId: this.workspaceId },
      this._logger
    );
  }
  async updateWorkspace(props) {
    return this.client.updateWorkspace({ id: this.workspaceId, ...props });
  }
  async getPublicOrPrivateIntegration(ref) {
    const integration = await this.findPublicOrPrivateIntegration(ref);
    if (!integration) {
      throw new Error(`Integration "${(0, import_package_ref.formatPackageRef)(ref)}" not found`);
    }
    return integration;
  }
  async findPublicOrPrivateIntegration(ref) {
    const formatted = (0, import_package_ref.formatPackageRef)(ref);
    const privateIntegration = await this.findPrivateIntegration(ref);
    if (privateIntegration) {
      this._logger.debug(`Found integration "${formatted}" in workspace`);
      return privateIntegration;
    }
    const publicIntegration = await this.findPublicIntegration(ref);
    if (publicIntegration) {
      this._logger.debug(`Found integration "${formatted}" in hub`);
      return publicIntegration;
    }
    return;
  }
  async findPrivateIntegration(ref) {
    const { workspaceId } = this;
    if (ref.type === "id") {
      return this.client.getIntegration(ref).then((r) => ({ ...r.integration, workspaceId })).catch(this._returnUndefinedOnError("ResourceNotFound"));
    }
    return this.client.getIntegrationByName(ref).then((r) => ({ ...r.integration, workspaceId })).catch(this._returnUndefinedOnError("ResourceNotFound"));
  }
  async findPublicIntegration(ref) {
    if (ref.type === "id") {
      return this.client.getPublicIntegrationById(ref).then((r) => ({ ...r.integration, visibility: r.integration.visibility })).catch(this._returnUndefinedOnError("ResourceNotFound"));
    }
    return this.client.getPublicIntegration(ref).then((r) => ({ ...r.integration, visibility: r.integration.visibility })).catch(this._returnUndefinedOnError("ResourceNotFound"));
  }
  async findPublicOrPrivateInterface(ref) {
    const formatted = (0, import_package_ref.formatPackageRef)(ref);
    const privateInterface = await this.findPrivateInterface(ref);
    if (privateInterface) {
      this._logger.debug(`Found interface "${formatted}" in workspace`);
      return privateInterface;
    }
    const publicInterface = await this.findPublicInterface(ref);
    if (publicInterface) {
      this._logger.debug(`Found interface "${formatted}" in hub`);
      return publicInterface;
    }
    return;
  }
  async findPrivateInterface(ref) {
    const { workspaceId } = this;
    if (ref.type === "id") {
      return this.client.getInterface(ref).then((r) => ({ ...r.interface, workspaceId })).catch(this._returnUndefinedOnError("ResourceNotFound"));
    }
    return this.client.getInterfaceByName(ref).then((r) => ({ ...r.interface, workspaceId })).catch(this._returnUndefinedOnError("ResourceNotFound"));
  }
  async getPublicInterface(ref) {
    const intrface = await this.findPublicInterface(ref);
    if (!intrface) {
      throw new Error(`Interface "${(0, import_package_ref.formatPackageRef)(ref)}" not found`);
    }
    return intrface;
  }
  async findPublicInterface(ref) {
    if (ref.type === "id") {
      return this.client.getPublicInterfaceById(ref).then((r) => ({ ...r.interface, public: true })).catch(this._returnUndefinedOnError("ResourceNotFound"));
    }
    return this.client.getPublicInterface(ref).then((r) => ({ ...r.interface, public: true })).catch(this._returnUndefinedOnError("ResourceNotFound"));
  }
  async findPublicPlugin(ref) {
    if (ref.type === "id") {
      return this.client.getPublicPluginById(ref).then((r) => ({ ...r.plugin, public: true })).catch(this._returnUndefinedOnError("ResourceNotFound"));
    }
    return this.client.getPublicPlugin(ref).then((r) => ({ ...r.plugin, public: true })).catch(this._returnUndefinedOnError("ResourceNotFound"));
  }
  async getPublicOrPrivatePlugin(ref) {
    const plugin = await this.findPublicOrPrivatePlugin(ref);
    if (!plugin) {
      throw new Error(`Plugin "${(0, import_package_ref.formatPackageRef)(ref)}" not found`);
    }
    return plugin;
  }
  async findPublicOrPrivatePlugin(ref) {
    const formatted = (0, import_package_ref.formatPackageRef)(ref);
    const privatePlugin = await this.findPrivatePlugin(ref);
    if (privatePlugin) {
      this._logger.debug(`Found plugin "${formatted}" in workspace`);
      return privatePlugin;
    }
    const publicPlugin = await this.findPublicPlugin(ref);
    if (publicPlugin) {
      this._logger.debug(`Found plugin "${formatted}" in hub`);
      return publicPlugin;
    }
    return;
  }
  async findPrivatePlugin(ref) {
    const { workspaceId } = this;
    if (ref.type === "id") {
      return this.client.getPlugin(ref).then((r) => ({ ...r.plugin, workspaceId })).catch(this._returnUndefinedOnError("ResourceNotFound"));
    }
    return this.client.getPluginByName(ref).then((r) => ({ ...r.plugin, workspaceId })).catch(this._returnUndefinedOnError("ResourceNotFound"));
  }
  async testLogin() {
    await this.client.listBots({});
  }
  listAllPages = paging.listAllPages;
  async findPreviousIntegrationVersion(ref) {
    const isValidSemverVersion = import_semver.default.valid(ref.version);
    if (!isValidSemverVersion) {
      throw new errors.BotpressCLIError(`Invalid version "${ref.version}" for integration "${ref.name}"`);
    }
    return this.findPublicOrPrivateIntegration({ ...ref, version: `<${ref.version}` });
  }
  async findBotByName(name) {
    const allBots = await this.listAllPages(this.client.listBots, (r) => r.bots);
    return allBots.find((b) => b.name === name);
  }
  _returnUndefinedOnError = (type) => (thrown) => {
    if (client.isApiError(thrown) && thrown.type === type) {
      return;
    }
    throw thrown;
  };
  async getOrGenerateShareableId(botId, integrationId, integrationAlias) {
    const { shareableId, isExpired } = await this.client.getIntegrationShareableId({
      botId,
      integrationId,
      integrationInstanceAlias: integrationAlias
    }).catch(() => ({ shareableId: void 0, isExpired: true }));
    if (shareableId && !isExpired) {
      return shareableId;
    }
    const { shareableId: newShareableId } = await this.client.createIntegrationShareableId({
      botId,
      integrationId,
      integrationInstanceAlias: integrationAlias
    });
    return newShareableId;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ApiClient,
  ...require("./types")
});
//# sourceMappingURL=client.js.map
