import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  execa
} from "./chunk-GWE3BRHX.js";
import {
  CliError,
  CliErrorCode,
  external_exports,
  getTestOverrides,
  pRetry,
  pathExists,
  require_react,
  resolveUrl,
  serializer,
  toURLSearchParams,
  useBiLogger,
  useHttpClient,
  usePanoramaMethodLogger,
  wixCliAppsFlowTunnelCreationStatusSrc11Evid5233
} from "./chunk-HPSJVSZT.js";
import {
  __commonJS,
  __dirname,
  __require,
  __toESM,
  init_esm_shims
} from "./chunk-4EFJZ3GQ.js";

// ../../node_modules/cloudflared/lib/constants.js
var require_constants = __commonJS({
  "../../node_modules/cloudflared/lib/constants.js"(exports, module) {
    "use strict";
    init_esm_shims();
    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 __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var constants_exports = {};
    __export(constants_exports, {
      CLOUDFLARED_VERSION: () => CLOUDFLARED_VERSION,
      DEFAULT_CLOUDFLARED_BIN: () => DEFAULT_CLOUDFLARED_BIN,
      RELEASE_BASE: () => RELEASE_BASE,
      bin: () => bin3,
      use: () => use
    });
    module.exports = __toCommonJS(constants_exports);
    var import_node_path2 = __toESM2(__require("node:path"));
    var DEFAULT_CLOUDFLARED_BIN = import_node_path2.default.join(__dirname, "..", "bin", process.platform === "win32" ? "cloudflared.exe" : "cloudflared");
    var bin3 = process.env.CLOUDFLARED_BIN || DEFAULT_CLOUDFLARED_BIN;
    function use(executable) {
      bin3 = executable;
    }
    var CLOUDFLARED_VERSION = process.env.CLOUDFLARED_VERSION || "latest";
    var RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/";
  }
});

// ../../node_modules/cloudflared/lib/error.js
var require_error = __commonJS({
  "../../node_modules/cloudflared/lib/error.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var __defProp = Object.defineProperty;
    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames = Object.getOwnPropertyNames;
    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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var error_exports = {};
    __export(error_exports, {
      UnsupportedError: () => UnsupportedError
    });
    module.exports = __toCommonJS(error_exports);
    var UnsupportedError = class extends Error {
      constructor(message) {
        super(message);
      }
    };
  }
});

// ../../node_modules/cloudflared/lib/install.js
var require_install = __commonJS({
  "../../node_modules/cloudflared/lib/install.js"(exports, module) {
    "use strict";
    init_esm_shims();
    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 __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var install_exports = {};
    __export(install_exports, {
      install: () => install3,
      install_linux: () => install_linux,
      install_macos: () => install_macos,
      install_windows: () => install_windows
    });
    module.exports = __toCommonJS(install_exports);
    var import_node_fs = __toESM2(__require("node:fs"));
    var import_node_path2 = __toESM2(__require("node:path"));
    var import_node_https = __toESM2(__require("node:https"));
    var import_node_child_process = __require("node:child_process");
    var import_constants = require_constants();
    var import_error = require_error();
    var LINUX_URL = {
      arm64: "cloudflared-linux-arm64",
      arm: "cloudflared-linux-arm",
      x64: "cloudflared-linux-amd64",
      ia32: "cloudflared-linux-386"
    };
    var MACOS_URL = {
      arm64: "cloudflared-darwin-amd64.tgz",
      x64: "cloudflared-darwin-amd64.tgz"
    };
    var WINDOWS_URL = {
      x64: "cloudflared-windows-amd64.exe",
      ia32: "cloudflared-windows-386.exe"
    };
    function resolve_base(version) {
      if (version === "latest") {
        return `${import_constants.RELEASE_BASE}latest/download/`;
      }
      return `${import_constants.RELEASE_BASE}download/${version}/`;
    }
    async function install3(to, version = import_constants.CLOUDFLARED_VERSION) {
      if (process.platform === "linux") {
        return install_linux(to, version);
      } else if (process.platform === "darwin") {
        return install_macos(to, version);
      } else if (process.platform === "win32") {
        return install_windows(to, version);
      } else {
        throw new import_error.UnsupportedError("Unsupported platform: " + process.platform);
      }
    }
    async function install_linux(to, version = import_constants.CLOUDFLARED_VERSION) {
      const file = LINUX_URL[process.arch];
      if (file === void 0) {
        throw new import_error.UnsupportedError("Unsupported architecture: " + process.arch);
      }
      await download(resolve_base(version) + file, to);
      import_node_fs.default.chmodSync(to, "755");
      return to;
    }
    async function install_macos(to, version = import_constants.CLOUDFLARED_VERSION) {
      const file = MACOS_URL[process.arch];
      if (file === void 0) {
        throw new import_error.UnsupportedError("Unsupported architecture: " + process.arch);
      }
      await download(resolve_base(version) + file, `${to}.tgz`);
      process.env.VERBOSE && console.log(`Extracting to ${to}`);
      (0, import_node_child_process.execSync)(`tar -xzf ${import_node_path2.default.basename(`${to}.tgz`)}`, { cwd: import_node_path2.default.dirname(to) });
      import_node_fs.default.unlinkSync(`${to}.tgz`);
      import_node_fs.default.renameSync(`${import_node_path2.default.dirname(to)}/cloudflared`, to);
      return to;
    }
    async function install_windows(to, version = import_constants.CLOUDFLARED_VERSION) {
      const file = WINDOWS_URL[process.arch];
      if (file === void 0) {
        throw new import_error.UnsupportedError("Unsupported architecture: " + process.arch);
      }
      await download(resolve_base(version) + file, to);
      return to;
    }
    function download(url, to, redirect = 0) {
      if (redirect === 0) {
        process.env.VERBOSE && console.log(`Downloading ${url} to ${to}`);
      } else {
        process.env.VERBOSE && console.log(`Redirecting to ${url}`);
      }
      if (!import_node_fs.default.existsSync(import_node_path2.default.dirname(to))) {
        import_node_fs.default.mkdirSync(import_node_path2.default.dirname(to), { recursive: true });
      }
      return new Promise((resolve, reject) => {
        const request = import_node_https.default.get(url, (res) => {
          const redirect_code = [301, 302, 303, 307, 308];
          if (redirect_code.includes(res.statusCode) && res.headers.location !== void 0) {
            request.destroy();
            const redirection = res.headers.location;
            resolve(download(redirection, to, redirect + 1));
            return;
          }
          if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
            const file = import_node_fs.default.createWriteStream(to);
            file.on("finish", () => {
              file.close(() => resolve(to));
            });
            file.on("error", (err) => {
              import_node_fs.default.unlink(to, () => reject(err));
            });
            res.pipe(file);
          } else {
            request.destroy();
            reject(new Error(`HTTP response with status code: ${res.statusCode}`));
          }
        });
        request.on("error", (err) => {
          reject(err);
        });
        request.end();
      });
    }
  }
});

// ../../node_modules/cloudflared/lib/regex.js
var require_regex = __commonJS({
  "../../node_modules/cloudflared/lib/regex.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var __defProp = Object.defineProperty;
    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames = Object.getOwnPropertyNames;
    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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var regex_exports = {};
    __export(regex_exports, {
      config_regex: () => config_regex,
      conn_regex: () => conn_regex,
      connectorID_regex: () => connectorID_regex,
      disconnect_regex: () => disconnect_regex,
      index_regex: () => index_regex,
      ip_regex: () => ip_regex,
      location_regex: () => location_regex,
      metrics_regex: () => metrics_regex,
      tunnelID_regex: () => tunnelID_regex
    });
    module.exports = __toCommonJS(regex_exports);
    var conn_regex = /connection[= ]([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12})/i;
    var ip_regex = /ip=([0-9.]+)/;
    var location_regex = /location=([A-Za-z0-9]+)/;
    var index_regex = /connIndex=(\d)/;
    var disconnect_regex = /Unregistered tunnel connection connIndex=(\d)/i;
    var tunnelID_regex = /tunnelID=([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12})/i;
    var connectorID_regex = /Connector ID: ([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12})/i;
    var metrics_regex = /metrics server on ([0-9.:]+\/metrics)/;
    var config_regex = /config="(.+[^\\])"/;
  }
});

// ../../node_modules/cloudflared/lib/tunnel.js
var require_tunnel = __commonJS({
  "../../node_modules/cloudflared/lib/tunnel.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var __defProp = Object.defineProperty;
    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames = Object.getOwnPropertyNames;
    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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var tunnel_exports = {};
    __export(tunnel_exports, {
      tunnel: () => tunnel2
    });
    module.exports = __toCommonJS(tunnel_exports);
    var import_node_child_process = __require("node:child_process");
    var import_constants = require_constants();
    var import_regex = require_regex();
    function tunnel2(options = {}) {
      const args = ["tunnel"];
      for (const [key, value] of Object.entries(options)) {
        if (typeof value === "string") {
          args.push(`${key}`, value);
        } else if (typeof value === "number") {
          args.push(`${key}`, value.toString());
        } else if (value === null) {
          args.push(`${key}`);
        }
      }
      if (args.length === 1) {
        args.push("--url", "localhost:8080");
      }
      const child = (0, import_node_child_process.spawn)(import_constants.bin, args, { stdio: ["ignore", "pipe", "pipe"] });
      if (process.env.VERBOSE) {
        child.stdout.pipe(process.stdout);
        child.stderr.pipe(process.stderr);
      }
      const url_regex = /\|\s+(https?:\/\/[^\s]+)/;
      let url_resolver = () => void 0;
      let url_rejector = () => void 0;
      const url = new Promise((...pair) => [url_resolver, url_rejector] = pair);
      const connection_resolvers = [];
      const connection_rejectors = [];
      const connections = [];
      for (let i = 0; i < 1; i++) {
        connections.push(new Promise((...pair) => [connection_resolvers[i], connection_rejectors[i]] = pair));
      }
      const parser = (data) => {
        var _a;
        const str = data.toString();
        const url_match = str.match(url_regex);
        url_match && url_resolver(url_match[1]);
        const conn_match = str.match(import_regex.conn_regex);
        const ip_match = str.match(import_regex.ip_regex);
        const location_match = str.match(import_regex.location_regex);
        const index_match = str.match(import_regex.index_regex);
        if (conn_match && ip_match && location_match && index_match) {
          const [, id] = conn_match;
          const [, ip] = ip_match;
          const [, location] = location_match;
          const [, idx] = index_match;
          (_a = connection_resolvers[+idx]) == null ? void 0 : _a.call(connection_resolvers, { id, ip, location });
        }
      };
      child.stdout.on("data", parser).on("error", url_rejector);
      child.stderr.on("data", parser).on("error", url_rejector);
      const stop = () => child.kill("SIGINT");
      return { url, connections, child, stop };
    }
  }
});

// ../../node_modules/cloudflared/lib/service.js
var require_service = __commonJS({
  "../../node_modules/cloudflared/lib/service.js"(exports, module) {
    "use strict";
    init_esm_shims();
    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 __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var service_exports = {};
    __export(service_exports, {
      AlreadyInstalledError: () => AlreadyInstalledError2,
      LINUX_SERVICE_PATH: () => LINUX_SERVICE_PATH,
      MACOS_SERVICE_PATH: () => MACOS_SERVICE_PATH2,
      NotInstalledError: () => NotInstalledError2,
      clean: () => clean,
      current: () => current,
      err: () => err,
      exists: () => exists,
      identifier: () => identifier2,
      install: () => install3,
      journal: () => journal,
      log: () => log,
      service: () => service2,
      service_name: () => service_name,
      uninstall: () => uninstall
    });
    module.exports = __toCommonJS(service_exports);
    var import_node_os = __toESM2(__require("node:os"));
    var import_node_fs = __toESM2(__require("node:fs"));
    var import_node_child_process = __require("node:child_process");
    var import_constants = require_constants();
    var import_regex = require_regex();
    var identifier2 = "com.cloudflare.cloudflared";
    var service_name = "cloudflared.service";
    var MACOS_SERVICE_PATH2 = {
      PLIST: is_root() ? `/Library/LaunchDaemons/${identifier2}.plist` : `${import_node_os.default.homedir()}/Library/LaunchAgents/${identifier2}.plist`,
      OUT: is_root() ? `/Library/Logs/${identifier2}.out.log` : `${import_node_os.default.homedir()}/Library/Logs/${identifier2}.out.log`,
      ERR: is_root() ? `/Library/Logs/${identifier2}.err.log` : `${import_node_os.default.homedir()}/Library/Logs/${identifier2}.err.log`
    };
    var LINUX_SERVICE_PATH = {
      SYSTEMD: `/etc/systemd/system/${service_name}`,
      SERVICE: "/etc/init.d/cloudflared",
      SERVICE_OUT: "/var/log/cloudflared.log",
      SERVICE_ERR: "/var/log/cloudflared.err"
    };
    var service2 = { install: install3, uninstall, exists, log, err, current, clean, journal };
    var AlreadyInstalledError2 = class extends Error {
      constructor() {
        super("service is already installed");
      }
    };
    var NotInstalledError2 = class extends Error {
      constructor() {
        super("service is not installed");
      }
    };
    function install3(token) {
      if (!["darwin", "linux"].includes(process.platform)) {
        throw new Error(`Not Implemented on platform ${process.platform}`);
      }
      if (exists()) {
        throw new AlreadyInstalledError2();
      }
      const args = ["service", "install"];
      if (token) {
        args.push(token);
      }
      const result = (0, import_node_child_process.spawnSync)(import_constants.bin, args);
      if (result.status !== 0) {
        throw new Error(`service install failed: ${result.stderr.toString()}`);
      }
    }
    function uninstall() {
      if (!["darwin", "linux"].includes(process.platform)) {
        throw new Error(`Not Implemented on platform ${process.platform}`);
      }
      if (!exists()) {
        throw new NotInstalledError2();
      }
      const result = (0, import_node_child_process.spawnSync)(import_constants.bin, ["service", "uninstall"]);
      if (result.status !== 0) {
        throw new Error(`service uninstall failed: ${result.stderr.toString()}`);
      }
      if (process.platform === "darwin") {
        import_node_fs.default.rmSync(MACOS_SERVICE_PATH2.OUT);
        import_node_fs.default.rmSync(MACOS_SERVICE_PATH2.ERR);
      } else if (process.platform === "linux" && !is_systemd()) {
        import_node_fs.default.rmSync(LINUX_SERVICE_PATH.SERVICE_OUT);
        import_node_fs.default.rmSync(LINUX_SERVICE_PATH.SERVICE_ERR);
      }
    }
    function log() {
      if (!exists()) {
        throw new NotInstalledError2();
      }
      if (process.platform === "darwin") {
        return import_node_fs.default.readFileSync(MACOS_SERVICE_PATH2.OUT, "utf8");
      }
      if (process.platform === "linux" && !is_systemd()) {
        return import_node_fs.default.readFileSync(LINUX_SERVICE_PATH.SERVICE_OUT, "utf8");
      }
      throw new Error(`Not Implemented on platform ${process.platform}`);
    }
    function err() {
      if (!exists()) {
        throw new NotInstalledError2();
      }
      if (process.platform === "darwin") {
        return import_node_fs.default.readFileSync(MACOS_SERVICE_PATH2.ERR, "utf8");
      }
      if (process.platform === "linux" && !is_systemd()) {
        return import_node_fs.default.readFileSync(LINUX_SERVICE_PATH.SERVICE_ERR, "utf8");
      }
      throw new Error(`Not Implemented on platform ${process.platform}`);
    }
    function journal(n = 300) {
      if (process.platform === "linux" && is_systemd()) {
        const args = ["-u", service_name, "-o", "cat", "-n", n.toString()];
        return (0, import_node_child_process.spawnSync)("journalctl", args).stdout.toString();
      }
      throw new Error(`Not Implemented on platform ${process.platform}`);
    }
    function current() {
      var _a, _b, _c, _d;
      if (!["darwin", "linux"].includes(process.platform)) {
        throw new Error(`Not Implemented on platform ${process.platform}`);
      }
      if (!exists()) {
        throw new NotInstalledError2();
      }
      const log2 = is_systemd() ? journal() : err();
      let tunnelID = "";
      let connectorID = "";
      const connections = [];
      let metrics = "";
      let config = {};
      for (const line of log2.split("\n")) {
        try {
          if (line.match(import_regex.tunnelID_regex)) {
            tunnelID = ((_a = line.match(import_regex.tunnelID_regex)) == null ? void 0 : _a[1]) ?? "";
          } else if (line.match(import_regex.connectorID_regex)) {
            connectorID = ((_b = line.match(import_regex.connectorID_regex)) == null ? void 0 : _b[1]) ?? "";
          } else if (line.match(import_regex.conn_regex) && line.match(import_regex.location_regex) && line.match(import_regex.ip_regex) && line.match(import_regex.index_regex)) {
            const [, id] = line.match(import_regex.conn_regex) ?? [];
            const [, location] = line.match(import_regex.location_regex) ?? [];
            const [, ip] = line.match(import_regex.ip_regex) ?? [];
            const [, idx] = line.match(import_regex.index_regex) ?? [];
            connections[parseInt(idx)] = { id, ip, location };
          } else if (line.match(import_regex.disconnect_regex)) {
            const [, idx] = line.match(import_regex.disconnect_regex) ?? [];
            if (parseInt(idx) in connections) {
              connections[parseInt(idx)] = { id: "", ip: "", location: "" };
            }
          } else if (line.match(import_regex.metrics_regex)) {
            metrics = ((_c = line.match(import_regex.metrics_regex)) == null ? void 0 : _c[1]) ?? "";
          } else if (line.match(import_regex.config_regex)) {
            config = JSON.parse(((_d = line.match(import_regex.config_regex)) == null ? void 0 : _d[1].replace(/\\/g, "")) ?? "{}");
          }
        } catch (err2) {
          if (process.env.VERBOSE) {
            console.error("log parsing failed", err2);
          }
        }
      }
      return { tunnelID, connectorID, connections, metrics, config };
    }
    function clean() {
      if (process.platform !== "darwin") {
        throw new Error(`Not Implemented on platform ${process.platform}`);
      }
      if (exists()) {
        throw new AlreadyInstalledError2();
      }
      import_node_fs.default.rmSync(MACOS_SERVICE_PATH2.OUT, { force: true });
      import_node_fs.default.rmSync(MACOS_SERVICE_PATH2.ERR, { force: true });
    }
    function exists() {
      if (process.platform === "darwin") {
        return import_node_fs.default.existsSync(MACOS_SERVICE_PATH2.PLIST);
      } else if (process.platform === "linux") {
        return is_systemd() ? import_node_fs.default.existsSync(LINUX_SERVICE_PATH.SYSTEMD) : import_node_fs.default.existsSync(LINUX_SERVICE_PATH.SERVICE);
      }
      throw new Error(`Not Implemented on platform ${process.platform}`);
    }
    function is_root() {
      var _a;
      return ((_a = process.getuid) == null ? void 0 : _a.call(process)) === 0;
    }
    function is_systemd() {
      return process.platform === "linux" && import_node_fs.default.existsSync("/run/systemd/system");
    }
  }
});

// ../../node_modules/cloudflared/lib/lib.js
var require_lib = __commonJS({
  "../../node_modules/cloudflared/lib/lib.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var __defProp = Object.defineProperty;
    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames = Object.getOwnPropertyNames;
    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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var lib_exports = {};
    __export(lib_exports, {
      AlreadyInstalledError: () => import_service.AlreadyInstalledError,
      MACOS_SERVICE_PATH: () => import_service.MACOS_SERVICE_PATH,
      NotInstalledError: () => import_service.NotInstalledError,
      bin: () => import_constants.bin,
      identifier: () => import_service.identifier,
      install: () => import_install.install,
      service: () => import_service.service,
      tunnel: () => import_tunnel2.tunnel
    });
    module.exports = __toCommonJS(lib_exports);
    var import_constants = require_constants();
    var import_install = require_install();
    var import_tunnel2 = require_tunnel();
    var import_service = require_service();
  }
});

// ../cli-tunnel/src/useTunnel.ts
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);

// ../cli-tunnel/src/tunnel.ts
init_esm_shims();
import { dirname } from "node:path";
var import_cloudflared = __toESM(require_lib(), 1);
async function launchTunnel(port, tunnelClient) {
  const { localTunnel } = getTestOverrides();
  if (!localTunnel && !await pathExists(import_cloudflared.bin)) {
    try {
      await (0, import_cloudflared.install)(import_cloudflared.bin);
    } catch (e) {
      const err = e;
      if (e instanceof Error && err.code === "EACCES") {
        throw new CliError({
          code: CliErrorCode.FailedInstallCloudflareNoAccess({
            path: dirname(err.path)
          }),
          cause: e
        });
      }
      throw e;
    }
  }
  const tunnel2 = await tunnelClient.createTunnel({ port });
  const domain = `http${localTunnel ? "" : "s"}://${tunnel2.domain}`;
  const createTunnelPromise = new Promise((resolve, reject) => {
    const tunnelProcess = localTunnel ? execa("echo", [tunnel2.domain, tunnel2.token], { detached: true }) : execa(import_cloudflared.bin, ["tunnel", "run", "--token", tunnel2.token]);
    const close = () => {
      tunnelProcess.kill();
    };
    const listener = async (data) => {
      const output = data.toString();
      const match = output.match(tunnel2.domain)?.[0];
      if (match) {
        resolve({
          domain,
          close
        });
      }
    };
    tunnelProcess.stderr?.on("data", listener);
    tunnelProcess.stdout?.on("data", listener);
    tunnelProcess.on("error", (err) => {
      reject(err);
    });
  });
  return {
    domain,
    close: async () => {
      const tunnel3 = await createTunnelPromise;
      return tunnel3.close();
    }
  };
}

// ../cli-tunnel/src/bi/events.ts
init_esm_shims();
var wixCliTunnelBiEvents = (biLogger) => ({
  tunnel: () => {
    const startTimestamp = Date.now();
    return {
      finish: ({
        isSuccess,
        failureReason
      }) => {
        void biLogger.report(
          wixCliAppsFlowTunnelCreationStatusSrc11Evid5233({
            isSuccess,
            failureReason,
            tunnelCreationTime: Date.now() - startTimestamp
          })
        );
      }
    };
  }
});

// ../cli-tunnel/src/useTunnelClient.ts
init_esm_shims();
var import_react = __toESM(require_react(), 1);

// ../cli-tunnel/src/client.ts
init_esm_shims();

// ../../node_modules/@wix/ambassador-apps-hosting-v1-deployment/build/es/http.impl.js
init_esm_shims();
var _createTunnelRequest = {};
var _createTunnelResponse = {};
var _deleteTunnelRequest = {};
var _deleteTunnelResponse = {};
function resolveWixAppsHostingV1BackendServiceUrl(opts) {
  var domainToMappings = {
    "bo._base_domain_": [
      {
        srcPath: "/_serverless/wix-app-backend-manager",
        destPath: ""
      }
    ],
    "wixbo.ai": [
      {
        srcPath: "/_serverless/wix-app-backend-manager",
        destPath: ""
      }
    ],
    "wix-bo.com": [
      {
        srcPath: "/_serverless/wix-app-backend-manager",
        destPath: ""
      }
    ],
    "manage._base_domain_": [
      {
        srcPath: "/_serverless/wix-app-backend-manager",
        destPath: ""
      }
    ],
    "api._api_base_domain_": [
      {
        srcPath: "/wix-app-backend-manager",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function createTunnel(payload) {
  var _a = serializer(_createTunnelRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_createTunnelResponse, {}).fromJSON;
  function __createTunnel(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.apps.hosting.v1.deployment",
      method: "POST",
      methodFqn: "wix.apps.hosting.v1.BackendService.CreateTunnel",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixAppsHostingV1BackendServiceUrl({
        protoPath: "/v1/tunnel",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __createTunnel.fromReq = fromReq;
  __createTunnel.__isAmbassador = true;
  return __createTunnel;
}
function deleteTunnel(payload) {
  var _a = serializer(_deleteTunnelRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_deleteTunnelResponse, {}).fromJSON;
  function __deleteTunnel(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.apps.hosting.v1.deployment",
      method: "DELETE",
      methodFqn: "wix.apps.hosting.v1.BackendService.DeleteTunnel",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixAppsHostingV1BackendServiceUrl({
        protoPath: "/v1/tunnel",
        data: serializedData,
        host
      }),
      params: toURLSearchParams(serializedData),
      transformResponse: fromRes
    };
    return metadata;
  }
  __deleteTunnel.fromReq = fromReq;
  __deleteTunnel.__isAmbassador = true;
  return __deleteTunnel;
}

// ../cli-tunnel/src/schemas.ts
init_esm_shims();
var createTunnelSchema = external_exports.object({
  id: external_exports.string(),
  token: external_exports.string(),
  domain: external_exports.string()
});

// ../cli-tunnel/src/client.ts
var TunnelClient = class {
  constructor(httpClient) {
    this.httpClient = httpClient;
    const { minRetryTimeout } = getTestOverrides();
    this.retryOptions = {
      retries: 3,
      minTimeout: minRetryTimeout,
      maxTimeout: 3 * 1e3
    };
  }
  retryOptions;
  createTunnel = async ({ port }) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(createTunnel({ port })),
        this.retryOptions
      );
      return createTunnelSchema.parse(data);
    } catch (error) {
      throw new CliError({
        code: CliErrorCode.FailedToCreateTunnel(),
        cause: error
      });
    }
  };
  deleteTunnel = async (tunnelId) => {
    try {
      await pRetry(
        () => this.httpClient.request(deleteTunnel({ id: tunnelId })),
        this.retryOptions
      );
    } catch (error) {
      throw new CliError({
        code: CliErrorCode.FailedToDeleteTunnel(),
        cause: error
      });
    }
  };
};

// ../cli-tunnel/src/useTunnelClient.ts
function useTunnelClient() {
  const httpClient = useHttpClient({ type: "backoffice" });
  const client = (0, import_react.useMemo)(() => new TunnelClient(httpClient), [httpClient]);
  return usePanoramaMethodLogger(client);
}

// ../cli-tunnel/src/useTunnel.ts
function useTunnel() {
  const connectionRef = (0, import_react2.useRef)();
  const tunnelClient = useTunnelClient();
  const biLogger = useBiLogger();
  (0, import_react2.useEffect)(() => {
    return () => {
      connectionRef.current?.close();
    };
  }, []);
  return (0, import_react2.useCallback)(
    async (port) => {
      const biEvents = wixCliTunnelBiEvents(biLogger);
      const tunnelCreationBi = biEvents.tunnel();
      try {
        const tunnel2 = await launchTunnel(port, tunnelClient);
        connectionRef.current = tunnel2;
        tunnelCreationBi.finish({ isSuccess: true });
        return { url: tunnel2.domain };
      } catch (ex) {
        tunnelCreationBi.finish({
          isSuccess: false,
          failureReason: ex instanceof Error ? ex.message : "Unknown error"
        });
        throw ex;
      }
    },
    [tunnelClient, biLogger]
  );
}

// ../cli-tunnel/src/index.ts
init_esm_shims();

export {
  useTunnel
};
//# sourceMappingURL=chunk-37V57F6S.js.map