import { N as L, f as h } from "./en_US-VXVFCG4S-BOE8Usaa.js";
const m = {}, f = {}, D = (n, t) => {
  f[n] = t;
}, e = (n) => {
  class t extends Error {
    cause;
    constructor(r, s, a) {
      if (super(r || n, a), Object.setPrototypeOf(this, t.prototype), this.name = n, s)
        for (const c in s)
          this[c] = s[c];
      if (a && U(a) && "cause" in a && !this.cause) {
        const c = a.cause;
        this.cause = c, "stack" in c && (this.stack = this.stack + `
CAUSE: ` + c.stack);
      }
    }
  }
  return m[n] = t, t;
};
function U(n) {
  return typeof n == "object";
}
const O = (n) => {
  if (n && typeof n == "object") {
    try {
      if (typeof n.message == "string") {
        const o = JSON.parse(n.message);
        o.message && o.name && (n = o);
      }
    } catch {
    }
    let t;
    if (typeof n.name == "string") {
      const { name: o } = n, r = f[o];
      if (r)
        t = r(n);
      else {
        let s = o === "Error" ? Error : m[o];
        s || (console.warn("deserializing an unknown class '" + o + "'"), s = e(o)), t = Object.create(s.prototype);
        try {
          for (const a in n)
            n.hasOwnProperty(a) && (t[a] = n[a]);
        } catch {
        }
      }
    } else
      typeof n.message == "string" && (t = new Error(n.message));
    return t && !t.stack && Error.captureStackTrace && Error.captureStackTrace(t, O), t;
  }
  return new Error(String(n));
}, F = (n) => n && (typeof n == "object" ? C(n, []) : typeof n == "function" ? `[Function: ${n.name || "anonymous"}]` : n);
function C(n, t) {
  const o = {};
  t.push(n);
  for (const r of Object.keys(n)) {
    const s = n[r];
    if (typeof s != "function") {
      if (!s || typeof s != "object") {
        o[r] = s;
        continue;
      }
      if (t.indexOf(n[r]) === -1) {
        o[r] = C(n[r], t.slice(0));
        continue;
      }
      o[r] = "[Circular]";
    }
  }
  return typeof n.name == "string" && (o.name = n.name), typeof n.message == "string" && (o.message = n.message), typeof n.stack == "string" && (o.stack = n.stack), o;
}
const w = e("AccountNameRequired"), M = e("AccountNotSupported"), k = e("AccountAwaitingSendPendingOperations"), b = e("AmountRequired"), B = e("BluetoothRequired"), H = e("BtcUnmatchedApp"), G = e("CantOpenDevice"), q = e("CashAddrNotSupported"), V = e("ClaimRewardsFeesWarning"), W = e("CurrencyNotSupported"), K = e("DeviceAppVerifyNotSupported"), z = e("DeviceGenuineSocketEarlyClose"), Y = e("DeviceNotGenuine"), X = e("DeviceOnDashboardExpected"), $ = e("DeviceOnDashboardUnexpected"), j = e("DeviceInOSUExpected"), Q = e("DeviceHalted"), J = e("DeviceNameInvalid"), Z = e("DeviceSocketFail"), ee = e("DeviceSocketNoBulkStatus"), te = e("DeviceSocketNoBulkStatus"), ne = e("UnresponsiveDeviceError"), oe = e("DisconnectedDevice"), re = e("DisconnectedDeviceDuringOperation"), se = e("DeviceExtractOnboardingStateError"), ae = e("DeviceOnboardingStatePollingError"), ce = e("EnpointConfig"), ie = e("EthAppPleaseEnableContractData"), de = e("FeeEstimationFailed"), ue = e("FirmwareNotRecognized"), pe = e("HardResetFail"), le = e("InvalidXRPTag"), Ee = e("InvalidAddress"), ge = e("InvalidNonce"), he = e("InvalidAddressBecauseDestinationIsAlsoSource"), Te = e("LatestMCUInstalledError"), Ne = e("LatestFirmwareVersionRequired"), Ae = e("UnknownMCU"), De = e("LedgerAPIError"), xe = e("LedgerAPIErrorWithMessage"), Ie = e("LedgerAPINotAvailable"), Se = e("ManagerAppAlreadyInstalled"), me = e("ManagerAppRelyOnBTC"), fe = e("ManagerAppDepInstallRequired"), Oe = e("ManagerAppDepUninstallRequired"), Ce = e("ManagerDeviceLocked"), Re = e("ManagerFirmwareNotEnoughSpace"), _e = e("ManagerNotEnoughSpace"), ve = e("ManagerUninstallBTCDep"), ye = e("NetworkDown"), Pe = e("NetworkError"), Le = e("NoAddressesFound"), Ue = e("NotEnoughBalance"), Fe = e("NotEnoughBalanceFees"), we = e("NotEnoughBalanceSwap"), Me = e("NotEnoughBalanceToDelegate"), ke = e("UnstakeNotEnoughStakedBalanceLeft"), be = e("RestakeNotEnoughStakedBalanceLeft"), Be = e("NotEnoughToRestake"), He = e("NotEnoughToUnstake"), Ge = e("NotEnoughBalanceInParentAccount"), qe = e("NotEnoughSpendableBalance"), Ve = e("NotEnoughBalanceBecauseDestinationNotCreated"), We = e("NotEnoughToStake"), Ke = e("NoAccessToCamera"), ze = e("NotEnoughGas"), Ye = e("NotEnoughGasSwap"), Xe = e("TronEmptyAccount"), $e = e("MaybeKeepTronAccountAlive"), je = e("NotSupportedLegacyAddress"), Qe = e("GasLessThanEstimate"), Je = e("PriorityFeeTooLow"), Ze = e("PriorityFeeTooHigh"), et = e("PriorityFeeHigherThanMaxFee"), tt = e("MaxFeeTooLow"), nt = e("PasswordsDontMatch"), ot = e("PasswordIncorrect"), rt = e("RecommendSubAccountsToEmpty"), st = e("RecommendUndelegation"), at = e("TimeoutTagged"), ct = e("UnexpectedBootloader"), it = e("MCUNotGenuineToDashboard"), dt = e("RecipientRequired"), ut = e("UnavailableTezosOriginatedAccountReceive"), pt = e("UnavailableTezosOriginatedAccountSend"), lt = e("UpdateFetchFileFail"), Et = e("UpdateIncorrectHash"), gt = e("UpdateIncorrectSig"), ht = e("UpdateYourApp"), Tt = e("UserRefusedDeviceNameChange"), Nt = e("UserRefusedAddress"), At = e("UserRefusedFirmwareUpdate"), Dt = e("UserRefusedAllowManager"), xt = e("UserRefusedOnDevice"), It = e("PinNotSet"), St = e("ExpertModeRequired"), mt = e("TransportOpenUserCancelled"), ft = e("TransportInterfaceNotAvailable"), R = e("TransportRaceCondition"), Ot = e("TransportWebUSBGestureRequired"), Ct = e("TransactionHasBeenValidatedError"), Rt = e("TransportExchangeTimeoutError"), _t = e("DeviceShouldStayInApp"), vt = e("WebsocketConnectionError"), yt = e("WebsocketConnectionFailed"), Pt = e("WrongDeviceForAccount"), Lt = e("WrongDeviceForAccountPayout"), Ut = e("MissingSwapPayloadParamaters"), Ft = e("WrongDeviceForAccountRefund"), wt = e("WrongAppForCurrency"), Mt = e("ETHAddressNonEIP"), kt = e("CantScanQRCode"), bt = e("FeeNotLoaded"), Bt = e("FeeNotLoadedSwap"), Ht = e("FeeRequired"), Gt = e("FeeTooHigh"), qt = e("PendingOperation"), Vt = e("SyncError"), Wt = e("PairingFailed"), Kt = e("PeerRemovedPairing"), zt = e("GenuineCheckFailed"), Yt = e("LedgerAPI4xx"), Xt = e("LedgerAPI5xx"), $t = e("FirmwareOrAppUpdateRequired"), jt = e("ReplacementTransactionUnderpriced"), Qt = e("OpReturnSizeLimit"), Jt = e("DustLimit"), Zt = e("HederaInsufficientFundsForAssociation"), en = e("HederaRecipientTokenAssociationRequired"), tn = e("HederaRecipientTokenAssociationUnverified"), nn = e("LanguageNotFound"), on = e("NoDBPathGiven"), rn = e("DBWrongPassword"), sn = e("DBNotReset"), an = e("SequenceNumberError"), cn = e("DisabledTransactionBroadcastError");
var A;
(function(n) {
  n.Unknown = "Unknown", n.LocationServicesDisabled = "LocationServicesDisabled", n.LocationServicesUnauthorized = "LocationServicesUnauthorized", n.BluetoothScanStartFailed = "BluetoothScanStartFailed";
})(A || (A = {}));
class x extends Error {
  type;
  constructor(t, o) {
    super(o), this.name = "HwTransportError", this.type = t, Object.setPrototypeOf(this, x.prototype);
  }
}
class E extends Error {
  id;
  constructor(t, o) {
    const r = "TransportError";
    super(t || r), this.name = r, this.message = t, this.stack = new Error(t).stack, this.id = o;
  }
}
D("TransportError", (n) => new E(n.message, n.id));
const p = {
  ACCESS_CONDITION_NOT_FULFILLED: 38916,
  ALGORITHM_NOT_SUPPORTED: 38020,
  CLA_NOT_SUPPORTED: 28160,
  CODE_BLOCKED: 38976,
  CODE_NOT_INITIALIZED: 38914,
  COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 27009,
  CONDITIONS_OF_USE_NOT_SATISFIED: 27013,
  CONTRADICTION_INVALIDATION: 38928,
  CONTRADICTION_SECRET_CODE_STATUS: 38920,
  DEVICE_IN_RECOVERY_MODE: 26159,
  CUSTOM_IMAGE_EMPTY: 26158,
  FILE_ALREADY_EXISTS: 27273,
  FILE_NOT_FOUND: 37892,
  GP_AUTH_FAILED: 25344,
  HALTED: 28586,
  INCONSISTENT_FILE: 37896,
  INCORRECT_DATA: 27264,
  INCORRECT_LENGTH: 26368,
  INCORRECT_P1_P2: 27392,
  INS_NOT_SUPPORTED: 27904,
  DEVICE_NOT_ONBOARDED: 27911,
  DEVICE_NOT_ONBOARDED_2: 26129,
  INVALID_KCV: 38021,
  INVALID_OFFSET: 37890,
  LICENSING: 28482,
  LOCKED_DEVICE: 21781,
  MAX_VALUE_REACHED: 38992,
  MEMORY_PROBLEM: 37440,
  MISSING_CRITICAL_PARAMETER: 26624,
  NO_EF_SELECTED: 37888,
  NOT_ENOUGH_MEMORY_SPACE: 27268,
  OK: 36864,
  PIN_REMAINING_ATTEMPTS: 25536,
  REFERENCED_DATA_NOT_FOUND: 27272,
  SECURITY_STATUS_NOT_SATISFIED: 27010,
  TECHNICAL_PROBLEM: 28416,
  UNKNOWN_APDU: 27906,
  USER_REFUSED_ON_DEVICE: 21761,
  NOT_ENOUGH_SPACE: 20738,
  APP_NOT_FOUND_OR_INVALID_CONTEXT: 20771,
  INVALID_APP_NAME_LENGTH: 26378,
  GEN_AES_KEY_FAILED: 21529,
  INTERNAL_CRYPTO_OPERATION_FAILED: 21530,
  INTERNAL_COMPUTE_AES_CMAC_FAILED: 21531,
  ENCRYPT_APP_STORAGE_FAILED: 21532,
  INVALID_BACKUP_STATE: 26178,
  PIN_NOT_SET: 21762,
  INVALID_BACKUP_LENGTH: 26419,
  INVALID_RESTORE_STATE: 26179,
  INVALID_CHUNK_LENGTH: 26420,
  INVALID_BACKUP_HEADER: 26698,
  // Not documented:
  TRUSTCHAIN_WRONG_SEED: 45063
};
function _(n) {
  switch (n) {
    // improve text of most common errors
    case 26368:
      return "Incorrect length";
    case 26624:
      return "Missing critical parameter";
    case 27010:
      return "Security not satisfied (dongle locked or have invalid access rights)";
    case 27013:
      return "Condition of use not satisfied (denied by the user?)";
    case 27264:
      return "Invalid data received";
    case 27392:
      return "Invalid parameter received";
    case 21781:
      return "Locked device";
  }
  if (28416 <= n && n <= 28671)
    return "Internal error, please report";
}
class l extends Error {
  statusCode;
  statusText;
  /**
   * @param statusCode The error status code coming from a Transport implementation
   * @param options containing:
   *  - canBeMappedToChildError: enable the mapping of TransportStatusError to an error extending/inheriting from it
   *  . Ex: LockedDeviceError. Default to true.
   */
  constructor(t, { canBeMappedToChildError: o = !0 } = {}) {
    const r = Object.keys(p).find((i) => p[i] === t) || "UNKNOWN_ERROR", s = _(t) || r, a = t.toString(16), c = `Ledger device: ${s} (0x${a})`;
    if (super(c), this.name = "TransportStatusError", this.statusCode = t, this.statusText = r, Object.setPrototypeOf(this, l.prototype), o && t === p.LOCKED_DEVICE)
      return new T(c);
  }
}
class T extends l {
  constructor(t) {
    super(p.LOCKED_DEVICE, { canBeMappedToChildError: !1 }), t && (this.message = t), this.name = "LockedDeviceError", Object.setPrototypeOf(this, T.prototype);
  }
}
class I extends Error {
  constructor(t, o) {
    super(o), this.name = t, Object.setPrototypeOf(this, I.prototype);
  }
}
D("TransportStatusError", (n) => new l(n.statusCode));
const En = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  AccountAwaitingSendPendingOperations: k,
  AccountNameRequiredError: w,
  AccountNotSupported: M,
  AmountRequired: b,
  BluetoothRequired: B,
  BtcUnmatchedApp: H,
  CantOpenDevice: G,
  CantScanQRCode: kt,
  CashAddrNotSupported: q,
  ClaimRewardsFeesWarning: V,
  CurrencyNotSupported: W,
  DBNotReset: sn,
  DBWrongPassword: rn,
  DeviceAppVerifyNotSupported: K,
  DeviceExtractOnboardingStateError: se,
  DeviceGenuineSocketEarlyClose: z,
  DeviceHalted: Q,
  DeviceInOSUExpected: j,
  DeviceMangementKitError: I,
  DeviceNameInvalid: J,
  DeviceNeedsRestart: te,
  DeviceNotGenuineError: Y,
  DeviceOnDashboardExpected: X,
  DeviceOnDashboardUnexpected: $,
  DeviceOnboardingStatePollingError: ae,
  DeviceShouldStayInApp: _t,
  DeviceSocketFail: Z,
  DeviceSocketNoBulkStatus: ee,
  DisabledTransactionBroadcastError: cn,
  DisconnectedDevice: oe,
  DisconnectedDeviceDuringOperation: re,
  DustLimit: Jt,
  ETHAddressNonEIP: Mt,
  EnpointConfigError: ce,
  EthAppPleaseEnableContractData: ie,
  ExpertModeRequired: St,
  FeeEstimationFailed: de,
  FeeNotLoaded: bt,
  FeeNotLoadedSwap: Bt,
  FeeRequired: Ht,
  FeeTooHigh: Gt,
  FirmwareNotRecognized: ue,
  FirmwareOrAppUpdateRequired: $t,
  GasLessThanEstimate: Qe,
  GenuineCheckFailed: zt,
  HardResetFail: pe,
  HederaInsufficientFundsForAssociation: Zt,
  HederaRecipientTokenAssociationRequired: en,
  HederaRecipientTokenAssociationUnverified: tn,
  HwTransportError: x,
  get HwTransportErrorType() {
    return A;
  },
  InvalidAddress: Ee,
  InvalidAddressBecauseDestinationIsAlsoSource: he,
  InvalidNonce: ge,
  InvalidXRPTag: le,
  LanguageNotFound: nn,
  LatestFirmwareVersionRequired: Ne,
  LatestMCUInstalledError: Te,
  LedgerAPI4xx: Yt,
  LedgerAPI5xx: Xt,
  LedgerAPIError: De,
  LedgerAPIErrorWithMessage: xe,
  LedgerAPINotAvailable: Ie,
  LockedDeviceError: T,
  MCUNotGenuineToDashboard: it,
  ManagerAppAlreadyInstalledError: Se,
  ManagerAppDepInstallRequired: fe,
  ManagerAppDepUninstallRequired: Oe,
  ManagerAppRelyOnBTCError: me,
  ManagerDeviceLockedError: Ce,
  ManagerFirmwareNotEnoughSpaceError: Re,
  ManagerNotEnoughSpaceError: _e,
  ManagerUninstallBTCDep: ve,
  MaxFeeTooLow: tt,
  MaybeKeepTronAccountAlive: $e,
  MissingSwapPayloadParamaters: Ut,
  NetworkDown: ye,
  NetworkError: Pe,
  NoAccessToCamera: Ke,
  NoAddressesFound: Le,
  NoDBPathGiven: on,
  NotEnoughBalance: Ue,
  NotEnoughBalanceBecauseDestinationNotCreated: Ve,
  NotEnoughBalanceFees: Fe,
  NotEnoughBalanceInParentAccount: Ge,
  NotEnoughBalanceSwap: we,
  NotEnoughBalanceToDelegate: Me,
  NotEnoughGas: ze,
  NotEnoughGasSwap: Ye,
  NotEnoughSpendableBalance: qe,
  NotEnoughToRestake: Be,
  NotEnoughToStake: We,
  NotEnoughToUnstake: He,
  NotSupportedLegacyAddress: je,
  OpReturnDataSizeLimit: Qt,
  PairingFailed: Wt,
  PasswordIncorrectError: ot,
  PasswordsDontMatchError: nt,
  PeerRemovedPairing: Kt,
  PendingOperation: qt,
  PinNotSet: It,
  PriorityFeeHigherThanMaxFee: et,
  PriorityFeeTooHigh: Ze,
  PriorityFeeTooLow: Je,
  RecipientRequired: dt,
  RecommendSubAccountsToEmpty: rt,
  RecommendUndelegation: st,
  ReplacementTransactionUnderpriced: jt,
  RestakeNotEnoughStakedBalanceLeft: be,
  SequenceNumberError: an,
  StatusCodes: p,
  SyncError: Vt,
  TimeoutTagged: at,
  TransactionHasBeenValidatedError: Ct,
  TransportError: E,
  TransportExchangeTimeoutError: Rt,
  TransportInterfaceNotAvailable: ft,
  TransportOpenUserCancelled: mt,
  TransportRaceCondition: R,
  TransportStatusError: l,
  TransportWebUSBGestureRequired: Ot,
  TronEmptyAccount: Xe,
  UnavailableTezosOriginatedAccountReceive: ut,
  UnavailableTezosOriginatedAccountSend: pt,
  UnexpectedBootloader: ct,
  UnknownMCU: Ae,
  UnresponsiveDeviceError: ne,
  UnstakeNotEnoughStakedBalanceLeft: ke,
  UpdateFetchFileFail: lt,
  UpdateIncorrectHash: Et,
  UpdateIncorrectSig: gt,
  UpdateYourApp: ht,
  UserRefusedAddress: Nt,
  UserRefusedAllowManager: Dt,
  UserRefusedDeviceNameChange: Tt,
  UserRefusedFirmwareUpdate: At,
  UserRefusedOnDevice: xt,
  WebsocketConnectionError: vt,
  WebsocketConnectionFailed: yt,
  WrongAppForCurrency: wt,
  WrongDeviceForAccount: Pt,
  WrongDeviceForAccountPayout: Lt,
  WrongDeviceForAccountRefund: Ft,
  addCustomErrorDeserializer: D,
  createCustomErrorClass: e,
  deserializeError: O,
  getAltStatusMessage: _,
  serializeError: F
}, Symbol.toStringTag, { value: "Module" }));
let v = 0;
const u = [], gn = (n, t, o) => {
  const r = {
    type: n,
    id: String(++v),
    date: /* @__PURE__ */ new Date()
  };
  t && (r.message = t), y(r);
}, dn = ({ type: n, message: t, data: o, context: r }) => {
  const s = {
    type: n,
    id: String(++v),
    date: /* @__PURE__ */ new Date()
  };
  t && (s.message = t), o && (s.data = o), r && (s.context = r), y(s);
};
class g {
  type;
  context;
  constructor(t, o) {
    this.type = t, this.context = o;
  }
  trace(t, o) {
    dn({
      type: this.type,
      message: t,
      data: o,
      context: this.context
    });
  }
  getContext() {
    return this.context;
  }
  setContext(t) {
    this.context = t;
  }
  updateContext(t) {
    this.context = { ...this.context, ...t };
  }
  getType() {
    return this.type;
  }
  setType(t) {
    this.type = t;
  }
  /**
   * Create a new instance of the LocalTracer with an updated `type`
   *
   * It does not mutate the calling instance, but returns a new LocalTracer,
   * following a simple builder pattern.
   */
  withType(t) {
    return new g(t, this.context);
  }
  /**
   * Create a new instance of the LocalTracer with a new `context`
   *
   * It does not mutate the calling instance, but returns a new LocalTracer,
   * following a simple builder pattern.
   *
   * @param context A TraceContext, that can undefined to reset the context
   */
  withContext(t) {
    return new g(this.type, t);
  }
  /**
   * Create a new instance of the LocalTracer with an updated `context`,
   * on which an additional context is merged with the existing one.
   *
   * It does not mutate the calling instance, but returns a new LocalTracer,
   * following a simple builder pattern.
   */
  withUpdatedContext(t) {
    return new g(this.type, { ...this.context, ...t });
  }
}
const un = (n) => (u.push(n), () => {
  const t = u.indexOf(n);
  t !== -1 && (u[t] = u[u.length - 1], u.pop());
});
function y(n) {
  for (let t = 0; t < u.length; t++)
    try {
      u[t](n);
    } catch (o) {
      console.error(o);
    }
}
typeof window < "u" && (window.__ledgerLogsListen = un);
const pn = "transport";
class hn {
  exchangeTimeout = 3e4;
  unresponsiveTimeout = 15e3;
  deviceModel = null;
  tracer;
  constructor({ context: t, logType: o } = {}) {
    this.tracer = new g(o ?? pn, t);
  }
  /**
   * Check if the transport is supported on the current platform/browser.
   * @returns {Promise<boolean>} A promise that resolves with a boolean indicating support.
   */
  static isSupported;
  /**
   * List all available descriptors for the transport.
   * For a better granularity, checkout `listen()`.
   *
   * @returns {Promise<Array<any>>} A promise that resolves with an array of descriptors.
   * @example
   * TransportFoo.list().then(descriptors => ...)
   */
  static list;
  /**
   * Listen for device events for the transport. The method takes an observer of DescriptorEvent and returns a Subscription.
   * A DescriptorEvent is an object containing a "descriptor" and a "type" field. The "type" field can be "add" or "remove", and the "descriptor" field can be passed to the "open" method.
   * The "listen" method will first emit all currently connected devices and then will emit events as they occur, such as when a USB device is plugged in or a Bluetooth device becomes discoverable.
   * @param {Observer<DescriptorEvent<any>>} observer - An object with "next", "error", and "complete" functions, following the observer pattern.
   * @returns {Subscription} A Subscription object on which you can call ".unsubscribe()" to stop listening to descriptors.
   * @example
  const sub = TransportFoo.listen({
  next: e => {
    if (e.type==="add") {
      sub.unsubscribe();
      const transport = await TransportFoo.open(e.descriptor);
      ...
    }
  },
  error: error => {},
  complete: () => {}
  })
   */
  static listen;
  /**
   * Attempt to create a Transport instance with a specific descriptor.
   * @param {any} descriptor - The descriptor to open the transport with.
   * @param {number} timeout - An optional timeout for the transport connection.
   * @param {TraceContext} context Optional tracing/log context
   * @returns {Promise<Transport>} A promise that resolves with a Transport instance.
   * @example
  TransportFoo.open(descriptor).then(transport => ...)
   */
  static open;
  /**
   * Send data to the device using a low level API.
   * It's recommended to use the "send" method for a higher level API.
   * @param {Buffer} apdu - The data to send.
   * @param {Object} options - Contains optional options for the exchange function
   *  - abortTimeoutMs: stop the exchange after a given timeout. Another timeout exists
   *    to detect unresponsive device (see `unresponsiveTimeout`). This timeout aborts the exchange.
   * @returns {Promise<Buffer>} A promise that resolves with the response data from the device.
   */
  exchange(t, { abortTimeoutMs: o } = {}) {
    throw new Error("exchange not implemented");
  }
  /**
   * Send apdus in batch to the device using a low level API.
   * The default implementation is to call exchange for each apdu.
   * @param {Array<Buffer>} apdus - array of apdus to send.
   * @param {Observer<Buffer>} observer - an observer that will receive the response of each apdu.
   * @returns {Subscription} A Subscription object on which you can call ".unsubscribe()" to stop sending apdus.
   */
  exchangeBulk(t, o) {
    let r = !1;
    const s = () => {
      r = !0;
    };
    return (async () => {
      if (!r)
        for (const c of t) {
          const i = await this.exchange(c);
          if (r)
            return;
          const d = i.readUInt16BE(i.length - 2);
          if (d !== p.OK)
            throw new l(d);
          o.next(i);
        }
    })().then(() => !r && o.complete(), (c) => !r && o.error(c)), { unsubscribe: s };
  }
  /**
   * Set the "scramble key" for the next data exchanges with the device.
   * Each app can have a different scramble key and it is set internally during instantiation.
   * @param {string} key - The scramble key to set.
   * deprecated This method is no longer needed for modern transports and should be migrated away from.
   * no @ before deprecated as it breaks documentationjs on version 14.0.2
   * https://github.com/documentationjs/documentation/issues/1596
   */
  setScrambleKey(t) {
  }
  /**
   * Close the connection with the device.
   *
   * Note: for certain transports (hw-transport-node-hid-singleton for ex), once the promise resolved,
   * the transport instance is actually still cached, and the device is disconnected only after a defined timeout.
   * But for the consumer of the Transport, this does not matter and it can consider the transport to be closed.
   *
   * @returns {Promise<void>} A promise that resolves when the transport is closed.
   */
  close() {
    return Promise.resolve();
  }
  _events = new L();
  /**
   * Listen for an event on the transport instance.
   * Transport implementations may have specific events. Common events include:
   * "disconnect" : triggered when the transport is disconnected.
   * @param {string} eventName - The name of the event to listen for.
   * @param {(...args: Array<any>) => any} cb - The callback function to be invoked when the event occurs.
   */
  on(t, o) {
    this._events.on(t, o);
  }
  /**
   * Stop listening to an event on an instance of transport.
   */
  off(t, o) {
    this._events.removeListener(t, o);
  }
  emit(t, ...o) {
    this._events.emit(t, ...o);
  }
  /**
   * Enable or not logs of the binary exchange
   */
  setDebugMode() {
    console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore.");
  }
  /**
   * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F)
   */
  setExchangeTimeout(t) {
    this.exchangeTimeout = t;
  }
  /**
   * Define the delay before emitting "unresponsive" on an exchange that does not respond
   */
  setExchangeUnresponsiveTimeout(t) {
    this.unresponsiveTimeout = t;
  }
  /**
   * Send data to the device using the higher level API.
   *
   * @param {number} cla - The instruction class for the command.
   * @param {number} ins - The instruction code for the command.
   * @param {number} p1 - The first parameter for the instruction.
   * @param {number} p2 - The second parameter for the instruction.
   * @param {Buffer} data - The data to be sent. Defaults to an empty buffer.
   * @param {Array<number>} statusList - A list of acceptable status codes for the response. Defaults to [StatusCodes.OK].
   * @param {Object} options - Contains optional options for the exchange function
   *  - abortTimeoutMs: stop the send after a given timeout. Another timeout exists
   *    to detect unresponsive device (see `unresponsiveTimeout`). This timeout aborts the exchange.
   * @returns {Promise<Buffer>} A promise that resolves with the response data from the device.
   */
  send = async (t, o, r, s, a = h.alloc(0), c = [p.OK], { abortTimeoutMs: i } = {}) => {
    const d = this.tracer.withUpdatedContext({ function: "send" });
    if (a.length >= 256)
      throw d.trace("data.length exceeded 256 bytes limit", { dataLength: a.length }), new E("data.length exceed 256 bytes limit. Got: " + a.length, "DataLengthTooBig");
    d.trace("Starting an exchange", { abortTimeoutMs: i });
    const N = await this.exchange(
      // The size of the data is added in 1 byte just before `data`
      h.concat([h.from([t, o, r, s]), h.from([a.length]), a]),
      { abortTimeoutMs: i }
    );
    d.trace("Received response from exchange");
    const S = N.readUInt16BE(N.length - 2);
    if (!c.some((P) => P === S))
      throw new l(S);
    return N;
  };
  /**
   * create() allows to open the first descriptor available or
   * throw if there is none or if timeout is reached.
   * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase)
   * @example
  TransportFoo.create().then(transport => ...)
   */
  static create(t = 3e3, o) {
    return new Promise((r, s) => {
      let a = !1;
      const c = this.listen({
        next: (d) => {
          a = !0, c && c.unsubscribe(), i && clearTimeout(i), this.open(d.descriptor, t).then(r, s);
        },
        error: (d) => {
          i && clearTimeout(i), s(d);
        },
        complete: () => {
          i && clearTimeout(i), a || s(new E(this.ErrorMessage_NoDeviceFound, "NoDeviceFound"));
        }
      }), i = o ? setTimeout(() => {
        c.unsubscribe(), s(new E(this.ErrorMessage_ListenTimeout, "ListenTimeout"));
      }, o) : null;
    });
  }
  // Blocks other exchange to happen concurrently
  exchangeBusyPromise;
  /**
   * Wrapper to make an exchange "atomic" (blocking any other exchange)
   *
   * It also handles "unresponsiveness" by emitting "unresponsive" and "responsive" events.
   *
   * @param f The exchange job, using the transport to run
   * @returns a Promise resolving with the output of the given job
   */
  async exchangeAtomicImpl(t) {
    const o = this.tracer.withUpdatedContext({
      function: "exchangeAtomicImpl",
      unresponsiveTimeout: this.unresponsiveTimeout
    });
    if (this.exchangeBusyPromise)
      throw o.trace("Atomic exchange is already busy"), new R("An action was already pending on the Ledger device. Please deny or reconnect.");
    let r;
    const s = new Promise((i) => {
      r = i;
    });
    this.exchangeBusyPromise = s;
    let a = !1;
    const c = setTimeout(() => {
      o.trace('Timeout reached, emitting Transport event "unresponsive"', {
        unresponsiveTimeout: this.unresponsiveTimeout
      }), a = !0, this.emit("unresponsive");
    }, this.unresponsiveTimeout);
    try {
      const i = await t();
      return a && (o.trace("Device was unresponsive, emitting responsive"), this.emit("responsive")), i;
    } finally {
      o.trace("Finalize, clearing busy guard"), clearTimeout(c), r && r(), this.exchangeBusyPromise = null;
    }
  }
  decorateAppAPIMethods(t, o, r) {
    for (const s of o)
      t[s] = this.decorateAppAPIMethod(s, t[s], t, r);
  }
  _appAPIlock = null;
  decorateAppAPIMethod(t, o, r, s) {
    return async (...a) => {
      const { _appAPIlock: c } = this;
      if (c)
        return Promise.reject(new E("Ledger Device is busy (lock " + c + ")", "TransportLocked"));
      try {
        return this._appAPIlock = t, this.setScrambleKey(s), await o.apply(r, a);
      } finally {
        this._appAPIlock = null;
      }
    };
  }
  /**
   * Sets the context used by the logging/tracing mechanism
   *
   * Useful when re-using (cached) the same Transport instance,
   * but with a new tracing context.
   *
   * @param context A TraceContext, that can undefined to reset the context
   */
  setTraceContext(t) {
    this.tracer = this.tracer.withContext(t);
  }
  /**
   * Updates the context used by the logging/tracing mechanism
   *
   * The update only overrides the key-value that are already defined in the current context.
   *
   * @param contextToAdd A TraceContext that will be added to the current context
   */
  updateTraceContext(t) {
    this.tracer.updateContext(t);
  }
  /**
   * Gets the tracing context of the transport instance
   */
  getTraceContext() {
    return this.tracer.getContext();
  }
  static ErrorMessage_ListenTimeout = "No Ledger device found (timeout)";
  static ErrorMessage_NoDeviceFound = "No Ledger device found";
}
export {
  re as D,
  mt as T,
  gn as a,
  hn as b,
  E as c,
  oe as d,
  O as e,
  En as l,
  F as s
};
//# sourceMappingURL=Transport-D5pzX14K.js.map
