var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// lib/enums/storage-type.ts
var StorageType = /* @__PURE__ */ ((StorageType2) => {
  StorageType2["CLOUD"] = "cloud";
  StorageType2["LOCAL"] = "local";
  StorageType2["TEMP"] = "temp";
  StorageType2["OPEN"] = "open";
  return StorageType2;
})(StorageType || {});

// src/create-profile/create-profile.ts
async function createProfileUrl(apiKey, storageType, targetUrl, profileId) {
  let defaultLink = "https://www.google.com";
  if (storageType === void 0 && targetUrl === void 0 && profileId !== void 0) {
    defaultLink = void 0;
  }
  const requestData = {
    action: storageType || "open" /* OPEN */,
    url: targetUrl || defaultLink,
    profileId
  };
  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `${apiKey}`
    },
    body: JSON.stringify(requestData)
  };
  const result = await fetch("http://localhost:54789/local-api/v1/action-token", requestOptions);
  if (!result) {
    throw new Error("Could not fetch resources.");
  }
  ;
  const data = await result.json();
  if (data.success) {
    const token = data.token;
    if (!token) {
      throw new Error("Generating action token was unsuccessful.");
    }
    ;
    const url = `https://open.sessionbox.dev?sbo_token=${token}`;
    return url;
  } else {
    throw new Error("Token could not be extracted.");
  }
}

// lib/utils.ts
import { Builder } from "selenium-webdriver";
import { Options } from "selenium-webdriver/chrome";
var os = __require("os");
function getArchitecture() {
  if (os.arch().includes("86")) {
    return "x86-32";
  } else if (os.arch().includes("64")) {
    return "x86-64";
  } else {
    return "arm";
  }
}
async function getBrowserVersion() {
  const driver = await new Builder().forBrowser("chrome").setChromeOptions(new Options().addArguments("--headless")).build();
  const capabilities = await driver.getCapabilities();
  driver.close();
  driver.quit();
  return capabilities.get("browserVersion").concat(".170");
}
async function createWebDriver(options) {
  const driver = await new Builder().forBrowser("chrome").setChromeOptions(options || new Options()).build();
  return driver;
}

// src/download-extension/download-extension.ts
import fs from "fs";
import { Options as Options2 } from "selenium-webdriver/chrome";
var PATH_TO_EXTENSION = "extension/chrome_extension.crx";
async function downloadExtension() {
  if (!fs.existsSync("extension"))
    fs.mkdirSync("extension");
  const architecture = getArchitecture();
  const browserVersion = await getBrowserVersion();
  const response = await fetch(`https://clients2.google.com/service/update2/crx?response=redirect&prodversion=${browserVersion}&acceptformat=crx2,crx3&x=id%3Dgmechnknnhcmhlciielglhgodjlcbien%26uc&nacl_arch=${architecture}`);
  const buffer = await response.arrayBuffer();
  fs.writeFileSync(PATH_TO_EXTENSION, Buffer.from(buffer));
}
function addExtension(options) {
  if (options)
    return options.addExtensions(PATH_TO_EXTENSION);
  else
    return new Options2().addExtensions(PATH_TO_EXTENSION);
}

// lib/fetch.ts
async function getData(apiKey, endpoint) {
  try {
    const response = await fetch(endpoint, {
      method: "GET",
      headers: {
        "Authorization": `${apiKey}`
      }
    });
    if (!response.ok) {
      throw new Error(`Request failed with status: ${response.statusText}`);
    }
    let data;
    if (response.headers.get("content-type")?.includes("application/json")) {
      data = await response.json();
    }
    return data;
  } catch (error) {
    console.error("Error in getData:", error);
    throw error;
  }
}
async function postData(apiKey, endpoint, payload) {
  const options = {
    method: "POST",
    headers: {
      "Authorization": `${apiKey}`,
      "Content-Type": "application/json"
    }
  };
  if (payload) {
    options.body = JSON.stringify(payload);
  }
  try {
    const response = await fetch(endpoint, options);
    if (!response.ok) {
      throw new Error(`Request failed with status: ${response.statusText}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error in postData:", error);
    throw error;
  }
}
async function deleteData(apiKey, endpoint) {
  try {
    const response = await fetch(endpoint, {
      method: "DELETE",
      headers: {
        "Authorization": `${apiKey}`
      }
    });
    if (!response.ok) {
      throw new Error(`Request failed with status: ${response.statusText}`);
    }
    let data;
    if (response.headers.get("content-type")?.includes("application/json")) {
      data = await response.json();
    }
    return data;
  } catch (error) {
    console.error("Error in deleteData:", error);
    throw error;
  }
}
async function updateData(apiKey, endpoint, payload) {
  try {
    const response = await fetch(endpoint, {
      method: "PUT",
      headers: {
        "Authorization": `${apiKey}`
      },
      body: JSON.stringify(payload)
    });
    if (!response.ok) {
      throw new Error(`Request failed with status: ${response.statusText}`);
    }
    let data;
    if (response.headers.get("content-type")?.includes("application/json")) {
      data = await response.json();
    }
    return data;
  } catch (error) {
    console.error("Error in updateData:", error);
    throw error;
  }
}

// lib/enums/color-names.ts
var ColorNames = /* @__PURE__ */ ((ColorNames2) => {
  ColorNames2["RED"] = "red";
  ColorNames2["PINK"] = "pink";
  ColorNames2["PURPLE"] = "purple";
  ColorNames2["DEEP_PURPLE"] = "deep purple";
  ColorNames2["INDIGO"] = "indigo";
  ColorNames2["LIGHT_BLUE"] = "light blue";
  ColorNames2["CYAN"] = "cyan";
  ColorNames2["TEAL"] = "teal";
  ColorNames2["GREEN"] = "green";
  ColorNames2["LIGHT_GREEN"] = "light green";
  ColorNames2["LIME"] = "lime";
  ColorNames2["YELLOW"] = "yellow";
  ColorNames2["AMBER"] = "amber";
  ColorNames2["ORANGE"] = "orange";
  ColorNames2["DEEP_ORANGE"] = "deep orange";
  ColorNames2["BROWN"] = "brown";
  ColorNames2["GREY"] = "grey";
  ColorNames2["BLUE_GREY"] = "blue grey";
  return ColorNames2;
})(ColorNames || {});

// src/index.ts
function selenium(apiKey) {
  function isWebDriverWithExtension(driver) {
    return driver.sbExtension;
  }
  function checkDriver(driver) {
    if (!isWebDriverWithExtension(driver)) {
      throw new Error("Driver does not have SessionBox extension installed. Please initialize driver with createSessionBoxDriver.");
    }
  }
  async function waitUntilNavigation(driver) {
    await driver.wait(async () => {
      return driver.getCurrentUrl().then(function(url) {
        return !url.startsWith("https://open.sessionbox.dev") && !url.startsWith("chrome-extension://");
      });
    });
  }
  async function openNewProfile(storageType, targetUrl, driver) {
    console.log("i am in");
    const url = await createProfileUrl(apiKey, storageType, targetUrl);
    if (!driver) {
      driver = await createSessionBoxDriver();
    }
    checkDriver(driver);
    await driver.get(url);
    console.log(url);
    await waitUntilNavigation(driver);
    console.log("wait is over");
    return driver;
  }
  async function openExistingProfile(profileId, driver) {
    const url = await createProfileUrl(apiKey, void 0, void 0, profileId);
    if (!driver) {
      driver = await createSessionBoxDriver();
    }
    checkDriver(driver);
    await driver.get(url);
    await waitUntilNavigation(driver);
    return driver;
  }
  async function createSessionBoxDriver(options) {
    await downloadExtension();
    let optionsWithExtension = addExtension(options || void 0);
    const driver = await createWebDriver(optionsWithExtension);
    driver.sbExtension = true;
    return driver;
  }
  return {
    openNewProfile,
    openExistingProfile,
    createSessionBoxDriver
  };
}
function api(apiKey) {
  async function listProfiles() {
    return await getData(apiKey, "http://localhost:54789/local-api/v1/profiles");
  }
  async function getProfile(profileId) {
    return await getData(apiKey, `http://localhost:54789/local-api/v1/profiles/${profileId}`);
  }
  async function createProfile(color, group, name, url, storageType, cookies) {
    const payload = {
      "color": color,
      "group": group,
      "name": name,
      "url": url,
      "storageType": storageType,
      "cookies": cookies
    };
    const result = await postData(apiKey, "http://localhost:54789/local-api/v1/profiles", payload);
    return result;
  }
  async function updateProfile(profileId, color, group, name, sbProxyId, url) {
    const payload = {
      ...color !== void 0 && { "color": color },
      ...group !== void 0 && { "group": group },
      ...name !== void 0 && { "name": name },
      ...sbProxyId !== void 0 && { "sbProxyId": sbProxyId },
      ...url !== void 0 && { "url": url }
    };
    await updateData(apiKey, `http://localhost:54789/local-api/v1/profiles/${profileId}`, payload);
  }
  async function deleteProfile(profileId) {
    await deleteData(apiKey, `http://localhost:54789/local-api/v1/profiles/${profileId}`);
  }
  async function createActionToken(action, profileId, url) {
    const payload = {
      action,
      url
    };
    if (action = "open" /* OPEN */) {
      payload.profileId = profileId;
    }
    const result = await postData(apiKey, "http://localhost:54789/local-api/v1/action-token", payload);
    if (result.success) {
      return result.token;
    } else {
      throw new Error("Token not found");
    }
  }
  async function addProxy(name, type, username, password, ip, port, teamId) {
    const payload = {
      name,
      type,
      username,
      password,
      ip,
      port,
      teamId
    };
    return await postData(apiKey, "http://localhost:54789/local-api/v1/proxies", payload);
  }
  async function listProxies() {
    return await getData(apiKey, "http://localhost:54789/local-api/v1/proxies");
  }
  async function removeProxy(proxyId) {
    return await deleteData(apiKey, `http://localhost:54789/local-api/v1/proxies/${proxyId}`);
  }
  async function listTeams() {
    return await getData(apiKey, "http://localhost:54789/local-api/v1/teams");
  }
  return {
    listProfiles,
    getProfile,
    createProfile,
    deleteProfile,
    updateProfile,
    createActionToken,
    addProxy,
    removeProxy,
    listProxies,
    listTeams
  };
}
function sessionBoxInit(apiKey) {
  const seleniumAutomation = selenium(apiKey);
  const sessionBoxAPI = api(apiKey);
  return { api: sessionBoxAPI, selenium: seleniumAutomation };
}
export {
  ColorNames,
  StorageType,
  sessionBoxInit
};
