"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 __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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 __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);

// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
var require_ms = __commonJS({
  "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports2, module2) {
    var s = 1e3;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    module2.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse(val);
      } else if (type === "number" && isFinite(val)) {
        return options.long ? fmtLong(val) : fmtShort(val);
      }
      throw new Error(
        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
      );
    };
    function parse(str) {
      str = String(str);
      if (str.length > 100) {
        return;
      }
      var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
        str
      );
      if (!match) {
        return;
      }
      var n = parseFloat(match[1]);
      var type = (match[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n * y;
        case "weeks":
        case "week":
        case "w":
          return n * w;
        case "days":
        case "day":
        case "d":
          return n * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n * s;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n;
        default:
          return void 0;
      }
    }
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return Math.round(ms / d) + "d";
      }
      if (msAbs >= h) {
        return Math.round(ms / h) + "h";
      }
      if (msAbs >= m) {
        return Math.round(ms / m) + "m";
      }
      if (msAbs >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return plural(ms, msAbs, d, "day");
      }
      if (msAbs >= h) {
        return plural(ms, msAbs, h, "hour");
      }
      if (msAbs >= m) {
        return plural(ms, msAbs, m, "minute");
      }
      if (msAbs >= s) {
        return plural(ms, msAbs, s, "second");
      }
      return ms + " ms";
    }
    function plural(ms, msAbs, n, name) {
      var isPlural = msAbs >= n * 1.5;
      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
    }
  }
});

// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js
var require_common = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(exports2, module2) {
    function setup(env) {
      createDebug2.debug = createDebug2;
      createDebug2.default = createDebug2;
      createDebug2.coerce = coerce;
      createDebug2.disable = disable;
      createDebug2.enable = enable;
      createDebug2.enabled = enabled;
      createDebug2.humanize = require_ms();
      createDebug2.destroy = destroy;
      Object.keys(env).forEach((key) => {
        createDebug2[key] = env[key];
      });
      createDebug2.names = [];
      createDebug2.skips = [];
      createDebug2.formatters = {};
      function selectColor(namespace) {
        let hash = 0;
        for (let i = 0; i < namespace.length; i++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i);
          hash |= 0;
        }
        return createDebug2.colors[Math.abs(hash) % createDebug2.colors.length];
      }
      createDebug2.selectColor = selectColor;
      function createDebug2(namespace) {
        let prevTime;
        let enableOverride = null;
        let namespacesCache;
        let enabledCache;
        function debug2(...args) {
          if (!debug2.enabled) {
            return;
          }
          const self = debug2;
          const curr = Number(/* @__PURE__ */ new Date());
          const ms = curr - (prevTime || curr);
          self.diff = ms;
          self.prev = prevTime;
          self.curr = curr;
          prevTime = curr;
          args[0] = createDebug2.coerce(args[0]);
          if (typeof args[0] !== "string") {
            args.unshift("%O");
          }
          let index = 0;
          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
            if (match === "%%") {
              return "%";
            }
            index++;
            const formatter = createDebug2.formatters[format];
            if (typeof formatter === "function") {
              const val = args[index];
              match = formatter.call(self, val);
              args.splice(index, 1);
              index--;
            }
            return match;
          });
          createDebug2.formatArgs.call(self, args);
          const logFn = self.log || createDebug2.log;
          logFn.apply(self, args);
        }
        debug2.namespace = namespace;
        debug2.useColors = createDebug2.useColors();
        debug2.color = createDebug2.selectColor(namespace);
        debug2.extend = extend;
        debug2.destroy = createDebug2.destroy;
        Object.defineProperty(debug2, "enabled", {
          enumerable: true,
          configurable: false,
          get: () => {
            if (enableOverride !== null) {
              return enableOverride;
            }
            if (namespacesCache !== createDebug2.namespaces) {
              namespacesCache = createDebug2.namespaces;
              enabledCache = createDebug2.enabled(namespace);
            }
            return enabledCache;
          },
          set: (v) => {
            enableOverride = v;
          }
        });
        if (typeof createDebug2.init === "function") {
          createDebug2.init(debug2);
        }
        return debug2;
      }
      function extend(namespace, delimiter) {
        const newDebug = createDebug2(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      function enable(namespaces) {
        createDebug2.save(namespaces);
        createDebug2.namespaces = namespaces;
        createDebug2.names = [];
        createDebug2.skips = [];
        const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
        for (const ns of split) {
          if (ns[0] === "-") {
            createDebug2.skips.push(ns.slice(1));
          } else {
            createDebug2.names.push(ns);
          }
        }
      }
      function matchesTemplate(search, template) {
        let searchIndex = 0;
        let templateIndex = 0;
        let starIndex = -1;
        let matchIndex = 0;
        while (searchIndex < search.length) {
          if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
            if (template[templateIndex] === "*") {
              starIndex = templateIndex;
              matchIndex = searchIndex;
              templateIndex++;
            } else {
              searchIndex++;
              templateIndex++;
            }
          } else if (starIndex !== -1) {
            templateIndex = starIndex + 1;
            matchIndex++;
            searchIndex = matchIndex;
          } else {
            return false;
          }
        }
        while (templateIndex < template.length && template[templateIndex] === "*") {
          templateIndex++;
        }
        return templateIndex === template.length;
      }
      function disable() {
        const namespaces = [
          ...createDebug2.names,
          ...createDebug2.skips.map((namespace) => "-" + namespace)
        ].join(",");
        createDebug2.enable("");
        return namespaces;
      }
      function enabled(name) {
        for (const skip of createDebug2.skips) {
          if (matchesTemplate(name, skip)) {
            return false;
          }
        }
        for (const ns of createDebug2.names) {
          if (matchesTemplate(name, ns)) {
            return true;
          }
        }
        return false;
      }
      function coerce(val) {
        if (val instanceof Error) {
          return val.stack || val.message;
        }
        return val;
      }
      function destroy() {
        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
      }
      createDebug2.enable(createDebug2.load());
      return createDebug2;
    }
    module2.exports = setup;
  }
});

// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js
var require_browser = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js"(exports2, module2) {
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.storage = localstorage();
    exports2.destroy = /* @__PURE__ */ (() => {
      let warned = false;
      return () => {
        if (!warned) {
          warned = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports2.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c = "color: " + this.color;
      args.splice(1, 0, c, "color: inherit");
      let index = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index++;
        if (match === "%c") {
          lastC = index;
        }
      });
      args.splice(lastC, 0, c);
    }
    exports2.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports2.storage.setItem("debug", namespaces);
        } else {
          exports2.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    function load() {
      let r;
      try {
        r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  }
});

// ../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
var require_has_flag = __commonJS({
  "../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(exports2, module2) {
    "use strict";
    module2.exports = (flag, argv = process.argv) => {
      const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
      const position = argv.indexOf(prefix + flag);
      const terminatorPosition = argv.indexOf("--");
      return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
    };
  }
});

// ../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js
var require_supports_color = __commonJS({
  "../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js"(exports2, module2) {
    "use strict";
    var os2 = require("os");
    var tty = require("tty");
    var hasFlag = require_has_flag();
    var { env } = process;
    var forceColor;
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
      forceColor = 0;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      forceColor = 1;
    }
    if ("FORCE_COLOR" in env) {
      if (env.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor(haveStream, streamIsTTY) {
      if (forceColor === 0) {
        return 0;
      }
      if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
        return 3;
      }
      if (hasFlag("color=256")) {
        return 2;
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os2.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env) {
        const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env.TERM_PROGRAM) {
          case "iTerm.app":
            return version >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env) {
        return 1;
      }
      return min;
    }
    function getSupportLevel(stream) {
      const level = supportsColor(stream, stream && stream.isTTY);
      return translateLevel(level);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: translateLevel(supportsColor(true, tty.isatty(1))),
      stderr: translateLevel(supportsColor(true, tty.isatty(2)))
    };
  }
});

// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js
var require_node = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js"(exports2, module2) {
    var tty = require("tty");
    var util = require("util");
    exports2.init = init;
    exports2.log = log;
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.destroy = util.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports2.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor = require_supports_color();
      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
        exports2.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error) {
    }
    exports2.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
        return k.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
    }
    function formatArgs(args) {
      const { namespace: name, useColors: useColors2 } = this;
      if (useColors2) {
        const c = this.color;
        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
        const prefix = `  ${colorCode};1m${name} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name + " " + args[0];
      }
    }
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log(...args) {
      return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load() {
      return process.env.DEBUG;
    }
    function init(debug2) {
      debug2.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts);
    };
  }
});

// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js
var require_src = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js"(exports2, module2) {
    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
      module2.exports = require_browser();
    } else {
      module2.exports = require_node();
    }
  }
});

// src/index.ts
var index_exports = {};
__export(index_exports, {
  AppleDeviceKit: () => AppleDeviceKit
});
module.exports = __toCommonJS(index_exports);

// ../../node_modules/.pnpm/get-port@7.1.0/node_modules/get-port/index.js
var import_node_net = __toESM(require("node:net"), 1);
var import_node_os = __toESM(require("node:os"), 1);
var Locked = class extends Error {
  constructor(port) {
    super(`${port} is locked`);
  }
};
var lockedPorts = {
  old: /* @__PURE__ */ new Set(),
  young: /* @__PURE__ */ new Set()
};
var releaseOldLockedPortsIntervalMs = 1e3 * 15;
var minPort = 1024;
var maxPort = 65535;
var timeout;
var getLocalHosts = () => {
  const interfaces = import_node_os.default.networkInterfaces();
  const results = /* @__PURE__ */ new Set([void 0, "0.0.0.0"]);
  for (const _interface of Object.values(interfaces)) {
    for (const config of _interface) {
      results.add(config.address);
    }
  }
  return results;
};
var checkAvailablePort = (options) => new Promise((resolve, reject) => {
  const server = import_node_net.default.createServer();
  server.unref();
  server.on("error", reject);
  server.listen(options, () => {
    const { port } = server.address();
    server.close(() => {
      resolve(port);
    });
  });
});
var getAvailablePort = async (options, hosts) => {
  if (options.host || options.port === 0) {
    return checkAvailablePort(options);
  }
  for (const host of hosts) {
    try {
      await checkAvailablePort({ port: options.port, host });
    } catch (error) {
      if (!["EADDRNOTAVAIL", "EINVAL"].includes(error.code)) {
        throw error;
      }
    }
  }
  return options.port;
};
var portCheckSequence = function* (ports) {
  if (ports) {
    yield* ports;
  }
  yield 0;
};
async function getPorts(options) {
  let ports;
  let exclude = /* @__PURE__ */ new Set();
  if (options) {
    if (options.port) {
      ports = typeof options.port === "number" ? [options.port] : options.port;
    }
    if (options.exclude) {
      const excludeIterable = options.exclude;
      if (typeof excludeIterable[Symbol.iterator] !== "function") {
        throw new TypeError("The `exclude` option must be an iterable.");
      }
      for (const element of excludeIterable) {
        if (typeof element !== "number") {
          throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");
        }
        if (!Number.isSafeInteger(element)) {
          throw new TypeError(`Number ${element} in the exclude option is not a safe integer and can't be used`);
        }
      }
      exclude = new Set(excludeIterable);
    }
  }
  if (timeout === void 0) {
    timeout = setTimeout(() => {
      timeout = void 0;
      lockedPorts.old = lockedPorts.young;
      lockedPorts.young = /* @__PURE__ */ new Set();
    }, releaseOldLockedPortsIntervalMs);
    if (timeout.unref) {
      timeout.unref();
    }
  }
  const hosts = getLocalHosts();
  for (const port of portCheckSequence(ports)) {
    try {
      if (exclude.has(port)) {
        continue;
      }
      let availablePort = await getAvailablePort({ ...options, port }, hosts);
      while (lockedPorts.old.has(availablePort) || lockedPorts.young.has(availablePort)) {
        if (port !== 0) {
          throw new Locked(port);
        }
        availablePort = await getAvailablePort({ ...options, port }, hosts);
      }
      lockedPorts.young.add(availablePort);
      return availablePort;
    } catch (error) {
      if (!["EADDRINUSE", "EACCES"].includes(error.code) && !(error instanceof Locked)) {
        throw error;
      }
    }
  }
  throw new Error("No available ports found");
}
function portNumbers(from, to) {
  if (!Number.isInteger(from) || !Number.isInteger(to)) {
    throw new TypeError("`from` and `to` must be integer numbers");
  }
  if (from < minPort || from > maxPort) {
    throw new RangeError(`'from' must be between ${minPort} and ${maxPort}`);
  }
  if (to < minPort || to > maxPort) {
    throw new RangeError(`'to' must be between ${minPort} and ${maxPort}`);
  }
  if (from > to) {
    throw new RangeError("`to` must be greater than or equal to `from`");
  }
  const generator = function* (from2, to2) {
    for (let port = from2; port <= to2; port++) {
      yield port;
    }
  };
  return generator(from, to);
}

// src/utils/debug.ts
var import_debug = __toESM(require_src());
var debug = (0, import_debug.default)("apple-kit");
var debugTask = (0, import_debug.default)("apple-kit:task");
var debugWarning = (0, import_debug.default)("apple-kit:warning");
var debugError = (0, import_debug.default)("apple-kit:error");
function logInfo(message) {
  debug(message);
}
function logTask(message) {
  debugTask(message);
}

// src/logic/actions/device.ts
var import_node_child_process = require("node:child_process");
var import_node_fs = require("node:fs");
var import_node_path = require("node:path");
var import_node_util = require("node:util");

// src/logic/dataParser.ts
function parsePlistOutput(output) {
  const result = {};
  const lines = output.split("\n");
  for (const line of lines) {
    const colonIndex = line.indexOf(":");
    if (colonIndex > 0) {
      const key = line.substring(0, colonIndex).trim();
      const value = line.substring(colonIndex + 1).trim();
      result[key] = value;
    }
  }
  return result;
}
function parseAppList(output) {
  const apps = [];
  const lines = output.trim().split("\n");
  for (const line of lines) {
    const match = line.match(/^([^,]+),\s*([^,]+),\s*"?([^"]+)"?/);
    if (match) {
      apps.push({
        bundleId: match[1].trim(),
        version: match[2].trim(),
        displayName: match[3].trim(),
        bundleVersion: ""
      });
    }
  }
  return apps;
}

// src/logic/actions/device.ts
var import_meta = {};
var execAsync = (0, import_node_util.promisify)(import_node_child_process.exec);
function getModuleDir() {
  if (typeof import_meta !== "undefined" && import_meta.url) {
    const { fileURLToPath } = require("node:url");
    return (0, import_node_path.dirname)(fileURLToPath(import_meta.url));
  }
  return __dirname;
}
async function getDeviceInfo(udid) {
  logTask(`Getting device info for ${udid}`);
  const result = await runIDeviceTool("ideviceinfo", ["-u", udid]);
  if (!result) {
    throw new Error("Failed to get device info");
  }
  const props = parsePlistOutput(result.stdout);
  return {
    deviceName: props.DeviceName || "",
    productType: props.ProductType || "",
    productVersion: props.ProductVersion || "",
    buildVersion: props.BuildVersion || "",
    serialNumber: props.SerialNumber || "",
    udid: props.UniqueDeviceID || udid,
    wifiAddress: props.WiFiAddress || "",
    bluetoothAddress: props.BluetoothAddress || "",
    phoneNumber: props.PhoneNumber || "",
    cpuArchitecture: props.CPUArchitecture || "",
    hardwareModel: props.HardwareModel || "",
    modelNumber: props.ModelNumber || "",
    regionInfo: props.RegionInfo || "",
    timeZone: props.TimeZone || "",
    uniqueChipID: props.UniqueChipID || "",
    isPaired: true
    // If we can get info, device is paired
  };
}
async function runIDeviceTool(toolName, args = [], options = {}) {
  const binPath = getIDeviceBinPath();
  const ext = process.platform === "win32" ? ".exe" : "";
  const toolPath = binPath ? (0, import_node_path.join)(binPath, `${toolName}${ext}`) : `${toolName}${ext}`;
  const command = `"${toolPath}" ${args.map((a) => `"${a}"`).join(" ")}`;
  return execIDevice(command, options);
}
async function execIDevice(command, options = {}) {
  const binPath = getIDeviceBinPath();
  if (binPath) {
    options.cwd = binPath;
  }
  const result = await execAsync(command, {
    ...options,
    env: process.env,
    windowsHide: true,
    encoding: "utf8"
  });
  return {
    stdout: result.stdout.toString(),
    stderr: result.stderr.toString()
  };
}
function getPlatformDir() {
  const platform = process.platform;
  if (platform === "win32") {
    return "windows";
  }
  if (platform === "darwin") {
    return "darwin";
  }
  if (platform === "linux") {
    return "linux";
  }
  return platform;
}
function getBundledResourcesPath() {
  const moduleDir = getModuleDir();
  let packageRoot;
  if (moduleDir.includes("dist")) {
    packageRoot = (0, import_node_path.join)(moduleDir, "..", "..");
  } else {
    packageRoot = (0, import_node_path.join)(moduleDir, "..", "..", "..", "..");
  }
  const platformDir = getPlatformDir();
  const distPath = (0, import_node_path.join)(packageRoot, "dist", "resources", "bin", platformDir);
  if ((0, import_node_fs.existsSync)((0, import_node_path.join)(distPath, "idevice_id")) || (0, import_node_fs.existsSync)((0, import_node_path.join)(distPath, "idevice_id.exe"))) {
    return distPath;
  }
  const devPath = (0, import_node_path.join)(packageRoot, "resources", "bin", platformDir);
  if ((0, import_node_fs.existsSync)((0, import_node_path.join)(devPath, "idevice_id")) || (0, import_node_fs.existsSync)((0, import_node_path.join)(devPath, "idevice_id.exe"))) {
    return devPath;
  }
  return null;
}
function getResourcesBinPath() {
  const envBinPath = process.env.IDeviceBinPath;
  if (envBinPath) {
    return envBinPath;
  }
  const bundledPath = getBundledResourcesPath();
  if (bundledPath) {
    return bundledPath;
  }
  if (process.platform === "darwin") {
    const homebrewArmPath = "/opt/homebrew/bin";
    if ((0, import_node_fs.existsSync)((0, import_node_path.join)(homebrewArmPath, "idevice_id"))) {
      return homebrewArmPath;
    }
    const homebrewIntelPath = "/usr/local/bin";
    if ((0, import_node_fs.existsSync)((0, import_node_path.join)(homebrewIntelPath, "idevice_id"))) {
      return homebrewIntelPath;
    }
  }
  if (process.platform === "linux") {
    const linuxPaths = ["/usr/bin", "/usr/local/bin"];
    for (const linuxPath of linuxPaths) {
      if ((0, import_node_fs.existsSync)((0, import_node_path.join)(linuxPath, "idevice_id"))) {
        return linuxPath;
      }
    }
  }
  return "";
}
function getIDeviceBinPath() {
  return getResourcesBinPath();
}

// src/logic/actions/activation.ts
async function getActivationState(udid) {
  logTask(`Getting activation state for device ${udid}`);
  try {
    const result = await runIDeviceTool("ideviceinfo", ["-u", udid, "-k", "ActivationState"]);
    if (!result) {
      return {
        isActivated: false,
        activationState: "Unknown"
      };
    }
    const { stdout } = result;
    const state = stdout.trim();
    return {
      isActivated: state === "Activated",
      activationState: state
    };
  } catch {
    return {
      isActivated: false,
      activationState: "Unknown"
    };
  }
}
async function activate(udid) {
  logTask(`Activating device ${udid}`);
  try {
    const result = await runIDeviceTool("ideviceactivation", ["-u", udid, "activate"]);
    if (!result) {
      return false;
    }
    return result.stdout.toLowerCase().includes("success") || result.stdout.toLowerCase().includes("activated");
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : String(error);
    throw new Error(`Activation failed: ${errorMsg}`);
  }
}

// src/logic/actions/pair.ts
async function isPaired(udid) {
  logTask(`Checking pairing status for ${udid}`);
  try {
    const result = await runIDeviceTool("idevicepair", ["-u", udid, "validate"]);
    if (!result) {
      return false;
    }
    return result.stdout.toLowerCase().includes("success");
  } catch {
    return false;
  }
}
async function trustDevice(udid, timeout2 = 6e4, onWaitingForTrust) {
  logTask(`Trusting device ${udid}`);
  if (await isPaired(udid)) {
    logInfo(`Device ${udid} is already trusted`);
    return true;
  }
  logInfo(`Initiating pairing for device ${udid}`);
  const pairResult = await pair(udid);
  if (pairResult) {
    logInfo(`Device ${udid} paired successfully`);
    return true;
  }
  logInfo("Please accept the trust dialog on the device...");
  onWaitingForTrust?.();
  try {
    await waitForPairing(udid, timeout2, 1e3);
    logInfo(`Device ${udid} is now trusted`);
    return true;
  } catch {
    logInfo(`Timeout waiting for trust acceptance on device ${udid}`);
    return false;
  }
}
async function waitForPairing(udid, timeout2 = 12e4, pollInterval = 1e3) {
  logTask(`Waiting for pairing on device ${udid}`);
  const startTime = Date.now();
  while (Date.now() - startTime < timeout2) {
    if (await isPaired(udid)) {
      logInfo(`Device ${udid} is now paired`);
      return true;
    }
    await new Promise((resolve) => setTimeout(resolve, pollInterval));
  }
  throw new Error(`Timeout waiting for device pairing after ${timeout2}ms`);
}
async function pair(udid) {
  logTask(`Initiating pairing for device ${udid}`);
  try {
    const result = await runIDeviceTool("idevicepair", ["-u", udid, "pair"]);
    if (!result) {
      return false;
    }
    return result.stdout.toLowerCase().includes("success");
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : String(error);
    if (errorMsg.includes("Please accept the trust dialog")) {
      return false;
    }
    throw error;
  }
}
async function unpair(udid) {
  logTask(`Un-pairing device ${udid}`);
  try {
    const result = await runIDeviceTool("idevicepair", ["-u", udid, "unpair"]);
    if (!result) {
      return false;
    }
    return result.stdout.toLowerCase().includes("success");
  } catch {
    return false;
  }
}

// src/logic/actions/install.ts
async function installApp(ipaPath, udid) {
  logTask(`Installing app ${ipaPath} on device ${udid}`);
  if (!await isPaired(udid)) {
    await waitForPairing(udid, 1e4);
  }
  await runIDeviceTool("ideviceinstaller", ["-u", udid, "-i", ipaPath]);
}
async function uninstallApp(bundleId, udid) {
  logTask(`Uninstalling app ${bundleId} from device ${udid}`);
  if (!await isPaired(udid)) {
    await waitForPairing(udid, 1e4);
  }
  await runIDeviceTool("ideviceinstaller", ["-u", udid, "-U", bundleId]);
}
async function listApps(udid) {
  logTask(`Listing apps on device ${udid}`);
  if (!await isPaired(udid)) {
    await waitForPairing(udid, 1e4);
  }
  try {
    const result = await runIDeviceTool("ideviceinstaller", ["-u", udid, "-l"]);
    if (!result) {
      return [];
    }
    const { stdout } = result;
    return parseAppList(stdout);
  } catch {
    return [];
  }
}
async function isAppInstalled(bundleId, udid) {
  logTask(`Checking if app ${bundleId} is installed on device ${udid}`);
  const apps = await listApps(udid);
  return apps.some((app) => app.bundleId === bundleId);
}
async function wakeDevice(udid) {
  try {
    logInfo("Attempting to wake device screen...");
    await runIDeviceTool("ideviceinfo", ["-u", udid, "-k", "DeviceName"]);
    try {
      await runIDeviceTool("ideviceinfo", ["-u", udid, "-k", "ActivationState"]);
    } catch {
    }
    try {
      await runIDeviceTool("idevicepair", ["-u", udid, "validate"]);
    } catch {
    }
    await new Promise((resolve) => setTimeout(resolve, 1e3));
    logInfo("Device wake attempt completed");
  } catch (error) {
    logInfo(
      `Device wake attempt failed (non-critical): ${error instanceof Error ? error.message : String(error)}`
    );
  }
}
async function launchApp(bundleId, args, udid) {
  logTask(`Launching app ${bundleId} on device ${udid}`);
  if (!await isPaired(udid)) {
    await waitForPairing(udid, 1e4);
  }
  await wakeDevice(udid);
  try {
    logInfo(`Attempting to launch ${bundleId} using idevicedebug...`);
    const result = await runIDeviceTool("idevicedebug", ["-u", udid, "run", bundleId, ...args]);
    const output = (result?.stdout ?? "") + (result?.stderr ?? "");
    if (output.trim()) {
      logInfo(`idevicedebug output: ${output.substring(0, 200)}`);
    }
    if (output.toLowerCase().includes("could not start") && output.toLowerCase().includes("debugserver")) {
      logInfo("idevicedebug requires debugserver, falling back to pymobiledevice3...");
      throw new Error("debugserver_not_available");
    }
    logInfo(`App ${bundleId} launched successfully using idevicedebug`);
    await new Promise((resolve) => setTimeout(resolve, 1e3));
    return;
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : String(error);
    if (errorMsg.includes("debugserver_not_available") || errorMsg.toLowerCase().includes("could not start") || errorMsg.toLowerCase().includes("debugserver")) {
      logInfo("idevicedebug failed, trying pymobiledevice3 for iOS 17+...");
      await launchAppWithPymobiledevice3(bundleId, args, udid);
      return;
    }
    throw error;
  }
}
async function launchAppWithPymobiledevice3(bundleId, args, udid) {
  logTask(`Launching app ${bundleId} using pymobiledevice3`);
  const { exec } = await import("node:child_process");
  const { promisify: promisify2 } = await import("node:util");
  const execAsync2 = promisify2(exec);
  try {
    let cmdArgs = [
      "-m",
      "pymobiledevice3",
      "developer",
      "dvt",
      "launch",
      "--udid",
      udid,
      "--kill-existing",
      // Kill existing instance to bring app to foreground
      bundleId,
      ...args
    ];
    let command = `python ${cmdArgs.map((a) => `"${a}"`).join(" ")}`;
    logInfo(`Executing: ${command}`);
    const result = await execAsync2(command, {
      windowsHide: true,
      encoding: "utf8",
      timeout: 3e4
      // 30 second timeout
    });
    const output = result.stdout.toString() + result.stderr.toString();
    if (output.trim()) {
      logInfo(`pymobiledevice3 output: ${output.substring(0, 200)}`);
    }
    if (output.toLowerCase().includes("developer mode") && output.toLowerCase().includes("not enabled")) {
      throw new Error(
        "Developer Mode is not enabled on the device.\nPlease enable it: Settings \u2192 Privacy & Security \u2192 Developer Mode \u2192 Enable"
      );
    }
    if (output.toLowerCase().includes("tunneld") && (output.toLowerCase().includes("unable to connect") || output.toLowerCase().includes("invalidserviceerror"))) {
      logInfo("Tunnel required, retrying with tunnel option...");
      cmdArgs = [
        "-m",
        "pymobiledevice3",
        "developer",
        "dvt",
        "launch",
        "--udid",
        udid,
        "--tunnel",
        udid,
        // Use UDID for tunnel
        "--kill-existing",
        bundleId,
        ...args
      ];
      command = `python ${cmdArgs.map((a) => `"${a}"`).join(" ")}`;
      logInfo(`Retrying with tunnel: ${command}`);
      try {
        const retryResult = await execAsync2(command, {
          windowsHide: true,
          encoding: "utf8",
          timeout: 3e4
        });
        const retryOutput = retryResult.stdout.toString() + retryResult.stderr.toString();
        if (retryOutput.trim()) {
          logInfo(`pymobiledevice3 retry output: ${retryOutput.substring(0, 200)}`);
        }
        if (retryOutput.toLowerCase().includes("tunneld") && retryOutput.toLowerCase().includes("unable to connect")) {
          throw new Error(
            "Tunnel connection failed. For iOS 17+, you may need to start tunneld:\n  python -m pymobiledevice3 remote tunneld\nOr ensure Developer Mode is enabled and device is unlocked."
          );
        }
        logInfo(`App ${bundleId} launched successfully using pymobiledevice3 with tunnel`);
        await new Promise((resolve) => setTimeout(resolve, 500));
        return;
      } catch {
        throw new Error(
          "Tunnel connection failed. For iOS 17+, you may need to start tunneld:\n  python -m pymobiledevice3 remote tunneld\nOr ensure Developer Mode is enabled and device is unlocked."
        );
      }
    }
    if (output.toLowerCase().includes("not found") || output.toLowerCase().includes("command not found") || output.toLowerCase().includes("cannot find")) {
      throw new Error(
        "pymobiledevice3 is not installed.\nInstall it with: python -m pip install --user pymobiledevice3"
      );
    }
    if (output.toLowerCase().includes("error") && !output.toLowerCase().includes("warning")) {
      logInfo(`Warning: pymobiledevice3 reported errors: ${output.substring(0, 300)}`);
    }
    logInfo(`App ${bundleId} launched successfully using pymobiledevice3`);
    await new Promise((resolve) => setTimeout(resolve, 1e3));
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : String(error);
    if (errorMsg.includes("not found") || errorMsg.includes("command not found") || errorMsg.includes("cannot find") || errorMsg.includes("No module named")) {
      throw new Error(
        "pymobiledevice3 is not installed or Python is not available.\nInstall it with: python -m pip install --user pymobiledevice3\nFor iOS 17+, Developer Mode must also be enabled on the device."
      );
    }
    throw error;
  }
}

// src/logic/actions/proxy.ts
var import_node_child_process2 = require("node:child_process");
var import_node_fs2 = require("node:fs");
var import_node_path2 = require("node:path");
var import_meta2 = {};
function getModuleDir2() {
  if (typeof import_meta2 !== "undefined" && import_meta2.url) {
    const { fileURLToPath } = require("node:url");
    return (0, import_node_path2.dirname)(fileURLToPath(import_meta2.url));
  }
  return __dirname;
}
function getPlatformDir2() {
  const platform = process.platform;
  if (platform === "win32") {
    return "windows";
  }
  if (platform === "darwin") {
    return "darwin";
  }
  if (platform === "linux") {
    return "linux";
  }
  return platform;
}
function getBundledResourcesPath2() {
  const moduleDir = getModuleDir2();
  let packageRoot;
  if (moduleDir.includes("dist")) {
    packageRoot = (0, import_node_path2.join)(moduleDir, "..", "..");
  } else {
    packageRoot = (0, import_node_path2.join)(moduleDir, "..", "..", "..", "..");
  }
  const platformDir = getPlatformDir2();
  const distPath = (0, import_node_path2.join)(packageRoot, "dist", "resources", "bin", platformDir);
  if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(distPath, "iproxy")) || (0, import_node_fs2.existsSync)((0, import_node_path2.join)(distPath, "iproxy.exe"))) {
    return distPath;
  }
  const devPath = (0, import_node_path2.join)(packageRoot, "resources", "bin", platformDir);
  if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(devPath, "iproxy")) || (0, import_node_fs2.existsSync)((0, import_node_path2.join)(devPath, "iproxy.exe"))) {
    return devPath;
  }
  return null;
}
function getResourcesBinPath2() {
  const envBinPath = process.env.IDeviceBinPath;
  if (envBinPath) {
    return envBinPath;
  }
  const bundledPath = getBundledResourcesPath2();
  if (bundledPath) {
    return bundledPath;
  }
  if (process.platform === "darwin") {
    const homebrewArmPath = "/opt/homebrew/bin";
    if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(homebrewArmPath, "iproxy"))) {
      return homebrewArmPath;
    }
    const homebrewIntelPath = "/usr/local/bin";
    if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(homebrewIntelPath, "iproxy"))) {
      return homebrewIntelPath;
    }
  }
  if (process.platform === "linux") {
    const linuxPaths = ["/usr/bin", "/usr/local/bin"];
    for (const linuxPath of linuxPaths) {
      if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(linuxPath, "iproxy"))) {
        return linuxPath;
      }
    }
  }
  return "";
}
function startPortForward(localPort, devicePort, udid, startupTimeout = 500) {
  return new Promise((resolve, reject) => {
    logTask(`Starting port forward ${localPort} -> ${devicePort} for device ${udid}`);
    const binPath = getResourcesBinPath2();
    const ext = process.platform === "win32" ? ".exe" : "";
    const toolPath = binPath ? (0, import_node_path2.join)(binPath, `iproxy${ext}`) : `iproxy${ext}`;
    const spawnOptions = {
      windowsHide: true,
      stdio: ["ignore", "pipe", "pipe"]
    };
    if (binPath) {
      spawnOptions.cwd = binPath;
    }
    const child = (0, import_node_child_process2.spawn)(
      toolPath,
      [localPort.toString(), devicePort.toString(), "-u", udid],
      spawnOptions
    );
    let hasResolved = false;
    let stderrOutput = "";
    child.stderr?.on("data", (data) => {
      const msg = data.toString();
      stderrOutput += msg;
      if (msg.toLowerCase().includes("error") && !hasResolved) {
        hasResolved = true;
        child.kill();
        reject(new Error(`Port forwarding failed: ${msg}`));
      }
    });
    child.on("error", (error) => {
      if (!hasResolved) {
        hasResolved = true;
        reject(new Error(`Failed to start iproxy: ${error.message}`));
      }
    });
    child.on("exit", (code) => {
      if (!hasResolved) {
        hasResolved = true;
        if (code !== 0 && code !== null) {
          reject(new Error(`iproxy exited with code ${code}: ${stderrOutput}`));
        }
      }
    });
    setTimeout(() => {
      if (!hasResolved) {
        hasResolved = true;
        logTask(`Port forward started: ${localPort} -> ${devicePort} for device ${udid}`);
        resolve({
          result: {
            localPort,
            devicePort
          },
          process: child
        });
      }
    }, startupTimeout);
  });
}
function killPortForwardProcess(process2) {
  if (process2 && !process2.killed) {
    logTask("Killing port forward process");
    process2.kill();
  }
}

// src/logic/appleDeviceKit.ts
var AppleDeviceKit = class {
  constructor(udid, logicalPort) {
    this.logicalPort = logicalPort;
    this.deviceId = udid;
    logInfo(
      `AppleDeviceKit initialized for device: ${this.deviceId}, logical port: ${this.logicalPort}`
    );
  }
  deviceId;
  proxyProcess = null;
  localDevicePort = null;
  isDisposed = false;
  /**
   * Throws if the kit has been disposed
   */
  ensureNotDisposed() {
    if (this.isDisposed) {
      throw new Error("AppleDeviceKit has been disposed");
    }
  }
  /**
   * Get detailed device information
   */
  async getDeviceInfo() {
    this.ensureNotDisposed();
    return getDeviceInfo(this.deviceId);
  }
  /**
   * Check if device is paired/trusted with this computer
   */
  async isPaired() {
    this.ensureNotDisposed();
    return isPaired(this.deviceId);
  }
  /**
   * Wait for device to be paired
   * Polls the pairing status until successful or timeout
   *
   * @param timeout Timeout in milliseconds (default: 120000)
   * @param pollInterval Poll interval in milliseconds (default: 1000)
   */
  async waitForPairing(timeout2 = 12e4, pollInterval = 1e3) {
    this.ensureNotDisposed();
    return waitForPairing(this.deviceId, timeout2, pollInterval);
  }
  /**
   * Attempt to pair/trust the device
   * User must accept the trust dialog on the device
   */
  async pair() {
    this.ensureNotDisposed();
    return pair(this.deviceId);
  }
  /**
   * Trust/pair the device - initiates pairing and waits for user to accept
   *
   * This is the recommended method for establishing trust with a device.
   * It will:
   * 1. Check if already paired
   * 2. If not, initiate pairing (shows "Trust This Computer?" on device)
   * 3. Wait for user to accept the trust dialog
   *
   * @param timeout Timeout in milliseconds to wait for user acceptance (default: 60000)
   * @param onWaitingForTrust Callback when waiting for user to accept trust dialog
   * @returns true if device is now trusted
   */
  async trustDevice(timeout2 = 6e4, onWaitingForTrust) {
    this.ensureNotDisposed();
    return trustDevice(this.deviceId, timeout2, onWaitingForTrust);
  }
  /**
   * Unpair/untrust the device
   */
  async unpair() {
    this.ensureNotDisposed();
    return unpair(this.deviceId);
  }
  /**
   * Install an IPA file on the device (install agent)
   *
   * @param ipaPath Path to the IPA file
   */
  async installApp(ipaPath) {
    this.ensureNotDisposed();
    installApp(ipaPath, this.deviceId);
  }
  /**
   * Uninstall an app by bundle ID (uninstall agent)
   *
   * @param bundleId Application bundle identifier
   */
  async uninstallApp(bundleId) {
    this.ensureNotDisposed();
    uninstallApp(bundleId, this.deviceId);
  }
  /**
   * Check if an app is installed on the device
   *
   * @param bundleId Application bundle identifier
   */
  async isAppInstalled(bundleId) {
    this.ensureNotDisposed();
    return isAppInstalled(bundleId, this.deviceId);
  }
  /**
   * List all installed user applications
   */
  async listApps() {
    this.ensureNotDisposed();
    return listApps(this.deviceId);
  }
  /**
   * Launch an application on the device
   *
   * @param bundleId Application bundle identifier
   * @param args Application arguments
   */
  async launchApp(bundleId, args = []) {
    this.ensureNotDisposed();
    return launchApp(bundleId, args, this.deviceId);
  }
  /**
   * Start port forwarding and wait for it to be ready.
   * The local port is automatically allocated based on the logical port.
   *
   * We need port forwarding to be able to connect to the device from the computer
   * and communicate with it using the local port.
   *
   * Note: Only one port forward can be active at a time per kit instance.
   * Starting a new port forward will kill any existing one.
   *
   * @param devicePort Device port to forward to
   * @param startupTimeout Time to wait for proxy to start (ms)
   * @returns The port forward result with the allocated local port
   */
  async startPortForwardAsync(devicePort, startupTimeout = 500) {
    this.ensureNotDisposed();
    this.killProxyProcess();
    this.localDevicePort = await getPorts({ port: portNumbers(3e4, 31e3) });
    const { result, process: process2 } = await startPortForward(
      this.localDevicePort,
      devicePort,
      this.deviceId,
      startupTimeout
    );
    this.proxyProcess = process2;
    return result;
  }
  /**
   * Kill the current port forwarding process if running
   */
  killProxyProcess() {
    if (this.proxyProcess) {
      killPortForwardProcess(this.proxyProcess);
      this.proxyProcess = null;
    }
  }
  /**
   * Close the current port forwarding session and release the port
   */
  closePortForward() {
    this.killProxyProcess();
    if (this.localDevicePort) {
      this.localDevicePort = null;
    }
  }
  /**
   * Get the activation state of the device
   */
  async getActivationState() {
    this.ensureNotDisposed();
    return getActivationState(this.deviceId);
  }
  /**
   * Activate the device (register in apple servers), an activated device belongs to someone (a user/company).
   * A device that is on hello screen cannot pass the wifi step unless it is activated.
   * the activate save us the need of the device to be connected to the internet to do the activation
   * and register in apple servers.
   *
   * Note: This requires a valid activation record or Apple server access
   *
   * precondition: the device must be paired and trusted
   */
  async activate() {
    this.ensureNotDisposed();
    return activate(this.deviceId);
  }
  /**
   * Get the device UDID
   */
  getDeviceId() {
    return this.deviceId;
  }
  /**
   * Get the logical port number (USB hub position)
   */
  getLogicalPort() {
    return this.logicalPort;
  }
  /**
   * Get the currently allocated local port for forwarding
   * Returns undefined if no port forward is active
   */
  getDevicePort() {
    return this.localDevicePort;
  }
  /**
   * Check if this kit has been disposed
   */
  get disposed() {
    return this.isDisposed;
  }
  /**
   * Check if a port forward is currently active
   */
  get hasActivePortForward() {
    return this.proxyProcess !== null && !this.proxyProcess.killed;
  }
  /**
   * Dispose of the kit and clean up all resources.
   * This will kill any running proxy processes and release port allocations.
   *
   * After calling dispose(), the kit instance should not be used.
   */
  dispose() {
    if (this.isDisposed) {
      return;
    }
    logInfo(`Disposing AppleDeviceKit for device: ${this.deviceId}`);
    this.closePortForward();
    this.isDisposed = true;
  }
  /**
   * Symbol.dispose implementation for using with `using` keyword (TypeScript 5.2+)
   */
  [Symbol.dispose]() {
    this.dispose();
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AppleDeviceKit
});
//# sourceMappingURL=index.js.map
