@onekeyfe/hd-core 1.2.2-alpha.8 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +1 -1
  2. package/__tests__/AllNetworkGetAddressBase.tracing.test.ts +503 -10
  3. package/__tests__/DeviceCommands.test.ts +254 -1
  4. package/__tests__/core-error-output.test.ts +169 -1
  5. package/__tests__/device-lifecycle-events.test.ts +432 -15
  6. package/__tests__/logBlockEvent.test.ts +45 -122
  7. package/__tests__/open-wallet-session-error-response.test.ts +2 -2
  8. package/__tests__/open-wallet-session.test.ts +94 -363
  9. package/__tests__/protocol-v2.test.ts +132 -2
  10. package/__tests__/public-device-state-api.test.ts +2 -7
  11. package/__tests__/search-devices.test.ts +196 -8
  12. package/__tests__/sol-sign-offchain-message.test.ts +64 -0
  13. package/dist/api/FirmwareUpdateV4.d.ts +1 -0
  14. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  15. package/dist/api/GetFeatures.d.ts.map +1 -1
  16. package/dist/api/GetPassphraseState.d.ts.map +1 -1
  17. package/dist/api/OpenWalletSession.d.ts.map +1 -1
  18. package/dist/api/SearchDevices.d.ts +2 -15
  19. package/dist/api/SearchDevices.d.ts.map +1 -1
  20. package/dist/api/UploadPortfolio.d.ts +1 -0
  21. package/dist/api/UploadPortfolio.d.ts.map +1 -1
  22. package/dist/api/allnetwork/AllNetworkGetAddress.d.ts +2 -0
  23. package/dist/api/allnetwork/AllNetworkGetAddress.d.ts.map +1 -1
  24. package/dist/api/allnetwork/AllNetworkGetAddressBase.d.ts +7 -1
  25. package/dist/api/allnetwork/AllNetworkGetAddressBase.d.ts.map +1 -1
  26. package/dist/api/allnetwork/AllNetworkGetAddressByLoop.d.ts.map +1 -1
  27. package/dist/api/device/DeviceVerify.d.ts.map +1 -1
  28. package/dist/api/solana/SolSignOffchainMessage.d.ts.map +1 -1
  29. package/dist/core/RequestQueue.d.ts +3 -0
  30. package/dist/core/RequestQueue.d.ts.map +1 -1
  31. package/dist/core/index.d.ts +3 -1
  32. package/dist/core/index.d.ts.map +1 -1
  33. package/dist/core/uiPromiseRegistry.d.ts +1 -1
  34. package/dist/data-manager/TransportManager.d.ts +2 -0
  35. package/dist/data-manager/TransportManager.d.ts.map +1 -1
  36. package/dist/device/Device.d.ts +2 -0
  37. package/dist/device/Device.d.ts.map +1 -1
  38. package/dist/device/DeviceCommands.d.ts +5 -4
  39. package/dist/device/DeviceCommands.d.ts.map +1 -1
  40. package/dist/events/logBlockEvent.d.ts.map +1 -1
  41. package/dist/index.d.ts +35 -30
  42. package/dist/index.js +620 -325
  43. package/dist/protocols/protocol-v2/walletSession.d.ts.map +1 -1
  44. package/dist/types/api/getFeatures.d.ts.map +1 -1
  45. package/dist/types/api/getPassphraseState.d.ts.map +1 -1
  46. package/dist/types/api/openWalletSession.d.ts +1 -10
  47. package/dist/types/api/openWalletSession.d.ts.map +1 -1
  48. package/dist/types/api/protocolV2.d.ts +3 -4
  49. package/dist/types/api/protocolV2.d.ts.map +1 -1
  50. package/dist/types/api/solSignOffchainMessage.d.ts +1 -0
  51. package/dist/types/api/solSignOffchainMessage.d.ts.map +1 -1
  52. package/dist/types/params.d.ts.map +1 -1
  53. package/dist/utils/patch.d.ts +1 -1
  54. package/dist/utils/patch.d.ts.map +1 -1
  55. package/package.json +4 -4
  56. package/src/api/FirmwareUpdateV4.ts +9 -4
  57. package/src/api/GetFeatures.ts +1 -0
  58. package/src/api/GetPassphraseState.ts +1 -0
  59. package/src/api/OpenWalletSession.ts +7 -77
  60. package/src/api/SearchDevices.ts +121 -27
  61. package/src/api/UploadPortfolio.ts +5 -4
  62. package/src/api/allnetwork/AllNetworkGetAddress.ts +79 -45
  63. package/src/api/allnetwork/AllNetworkGetAddressBase.ts +95 -24
  64. package/src/api/allnetwork/AllNetworkGetAddressByLoop.ts +3 -0
  65. package/src/api/device/DeviceVerify.ts +8 -0
  66. package/src/api/solana/SolSignOffchainMessage.ts +44 -4
  67. package/src/core/RequestQueue.ts +36 -1
  68. package/src/core/index.ts +178 -63
  69. package/src/data/messages/messages-protocol-v2.json +49 -33
  70. package/src/data/messages/messages.json +8 -5
  71. package/src/data-manager/TransportManager.ts +14 -3
  72. package/src/device/Device.ts +58 -27
  73. package/src/device/DeviceCommands.ts +29 -2
  74. package/src/events/logBlockEvent.ts +6 -75
  75. package/src/protocols/protocol-v2/walletSession.ts +18 -2
  76. package/src/types/api/getFeatures.ts +2 -1
  77. package/src/types/api/getPassphraseState.ts +2 -5
  78. package/src/types/api/openWalletSession.ts +7 -19
  79. package/src/types/api/protocolV2.ts +3 -4
  80. package/src/types/api/solSignOffchainMessage.ts +2 -0
  81. package/src/types/params.ts +7 -0
package/dist/index.js CHANGED
@@ -291,7 +291,6 @@ const writeFirmwareByteSource = ({ source, chunkSize, write, }) => __awaiter(voi
291
291
  const OpenWalletSessionMode = {
292
292
  Standard: 'standard',
293
293
  SelectHidden: 'select-hidden',
294
- ResumeHidden: 'resume-hidden',
295
294
  };
296
295
 
297
296
  exports.EOneKeyDeviceMode = void 0;
@@ -13203,7 +13202,8 @@ var nested$2 = {
13203
13202
  },
13204
13203
  SolanaOffChainMessageVersion: {
13205
13204
  values: {
13206
- MESSAGE_VERSION_0: 0
13205
+ MESSAGE_VERSION_0: 0,
13206
+ MESSAGE_VERSION_1: 1
13207
13207
  }
13208
13208
  },
13209
13209
  SolanaOffChainMessageFormat: {
@@ -13236,14 +13236,16 @@ var nested$2 = {
13236
13236
  },
13237
13237
  message_format: {
13238
13238
  type: "SolanaOffChainMessageFormat",
13239
- id: 4,
13240
- options: {
13241
- "default": "V0_RESTRICTED_ASCII"
13242
- }
13239
+ id: 4
13243
13240
  },
13244
13241
  application_domain: {
13245
13242
  type: "bytes",
13246
13243
  id: 5
13244
+ },
13245
+ required_signers: {
13246
+ rule: "repeated",
13247
+ type: "bytes",
13248
+ id: 7
13247
13249
  }
13248
13250
  }
13249
13251
  },
@@ -31499,10 +31501,6 @@ var nested = {
31499
31501
  request_id: {
31500
31502
  type: "bytes",
31501
31503
  id: 5
31502
- },
31503
- source_fingerprint: {
31504
- type: "uint32",
31505
- id: 6
31506
31504
  }
31507
31505
  }
31508
31506
  },
@@ -31758,10 +31756,6 @@ var nested = {
31758
31756
  expected_address: {
31759
31757
  type: "bytes",
31760
31758
  id: 12
31761
- },
31762
- source_fingerprint: {
31763
- type: "uint32",
31764
- id: 13
31765
31759
  }
31766
31760
  }
31767
31761
  },
@@ -31846,10 +31840,6 @@ var nested = {
31846
31840
  expected_address: {
31847
31841
  type: "bytes",
31848
31842
  id: 12
31849
- },
31850
- source_fingerprint: {
31851
- type: "uint32",
31852
- id: 13
31853
31843
  }
31854
31844
  }
31855
31845
  },
@@ -31997,7 +31987,29 @@ var nested = {
31997
31987
  type: "EthereumAuthorizationSignature",
31998
31988
  id: 10
31999
31989
  }
32000
- }
31990
+ },
31991
+ reserved: [
31992
+ [
31993
+ 5,
31994
+ 5
31995
+ ],
31996
+ [
31997
+ 6,
31998
+ 6
31999
+ ],
32000
+ [
32001
+ 7,
32002
+ 7
32003
+ ],
32004
+ [
32005
+ 8,
32006
+ 8
32007
+ ],
32008
+ [
32009
+ 9,
32010
+ 9
32011
+ ]
32012
+ ]
32001
32013
  },
32002
32014
  EthereumTxAckOneKey: {
32003
32015
  fields: {
@@ -32026,10 +32038,6 @@ var nested = {
32026
32038
  chain_id: {
32027
32039
  type: "uint64",
32028
32040
  id: 3
32029
- },
32030
- source_fingerprint: {
32031
- type: "uint32",
32032
- id: 4
32033
32041
  }
32034
32042
  }
32035
32043
  },
@@ -36027,7 +36035,8 @@ var nested = {
36027
36035
  },
36028
36036
  SolanaOffChainMessageVersion: {
36029
36037
  values: {
36030
- MESSAGE_VERSION_0: 0
36038
+ MESSAGE_VERSION_0: 0,
36039
+ MESSAGE_VERSION_1: 1
36031
36040
  }
36032
36041
  },
36033
36042
  SolanaOffChainMessageFormat: {
@@ -36075,10 +36084,6 @@ var nested = {
36075
36084
  rule: "required",
36076
36085
  type: "bytes",
36077
36086
  id: 2
36078
- },
36079
- source_fingerprint: {
36080
- type: "uint32",
36081
- id: 3
36082
36087
  }
36083
36088
  }
36084
36089
  },
@@ -36115,17 +36120,15 @@ var nested = {
36115
36120
  },
36116
36121
  message_format: {
36117
36122
  type: "SolanaOffChainMessageFormat",
36118
- id: 4,
36119
- options: {
36120
- "default": "V0_RESTRICTED_ASCII"
36121
- }
36123
+ id: 4
36122
36124
  },
36123
36125
  application_domain: {
36124
36126
  type: "bytes",
36125
36127
  id: 5
36126
36128
  },
36127
- source_fingerprint: {
36128
- type: "uint32",
36129
+ required_signers: {
36130
+ rule: "repeated",
36131
+ type: "bytes",
36129
36132
  id: 6
36130
36133
  }
36131
36134
  }
@@ -36144,10 +36147,6 @@ var nested = {
36144
36147
  rule: "required",
36145
36148
  type: "bytes",
36146
36149
  id: 2
36147
- },
36148
- source_fingerprint: {
36149
- type: "uint32",
36150
- id: 3
36151
36150
  }
36152
36151
  }
36153
36152
  },
@@ -38564,6 +38563,7 @@ var nested = {
38564
38563
  MessageType_DeviceFindMyTokenState: 60450,
38565
38564
  MessageType_DeviceFindMyTokenUpdate: 60451,
38566
38565
  MessageType_DeviceFindMyTokenStateGet: 60452,
38566
+ MessageType_DeviceAnimationControl: 60461,
38567
38567
  MessageType_DeviceInfoGet: 60600,
38568
38568
  MessageType_DeviceInfo: 60601,
38569
38569
  MessageType_DeviceStatusGet: 60602,
@@ -38902,6 +38902,26 @@ var nested = {
38902
38902
  }
38903
38903
  }
38904
38904
  },
38905
+ DeviceAnimationAction: {
38906
+ values: {
38907
+ AnimationAction_Unknown: 0,
38908
+ AnimationAction_Start: 1,
38909
+ AnimationAction_Stop: 2
38910
+ }
38911
+ },
38912
+ DeviceAnimationControl: {
38913
+ fields: {
38914
+ action: {
38915
+ rule: "required",
38916
+ type: "DeviceAnimationAction",
38917
+ id: 1
38918
+ },
38919
+ timeout_ms: {
38920
+ type: "uint32",
38921
+ id: 2
38922
+ }
38923
+ }
38924
+ },
38905
38925
  DeviceFactoryAck: {
38906
38926
  values: {
38907
38927
  FACTORY_ACK_SUCCESS: 0,
@@ -38963,6 +38983,10 @@ var nested = {
38963
38983
  manufacture_time: {
38964
38984
  type: "DeviceFactoryInfoManufactureTime",
38965
38985
  id: 5
38986
+ },
38987
+ data: {
38988
+ type: "bytes",
38989
+ id: 100
38966
38990
  }
38967
38991
  }
38968
38992
  },
@@ -38972,11 +38996,19 @@ var nested = {
38972
38996
  rule: "required",
38973
38997
  type: "DeviceFactoryInfo",
38974
38998
  id: 1
38999
+ },
39000
+ full_data: {
39001
+ type: "bool",
39002
+ id: 2
38975
39003
  }
38976
39004
  }
38977
39005
  },
38978
39006
  DeviceFactoryInfoGet: {
38979
39007
  fields: {
39008
+ full_data: {
39009
+ type: "bool",
39010
+ id: 1
39011
+ }
38980
39012
  }
38981
39013
  },
38982
39014
  DeviceFactoryPermanentLock: {
@@ -41663,61 +41695,13 @@ const LogBlockEvent = new Set([
41663
41695
  UI_RESPONSE.RECEIVE_PIN,
41664
41696
  UI_RESPONSE.RECEIVE_PASSPHRASE,
41665
41697
  ]);
41666
- const LogLabelMethod = new Set([
41667
- 'openWalletSession',
41698
+ const LogPayloadBlockMethod = new Set([
41668
41699
  'deviceUploadNft',
41669
41700
  'deviceUploadWallpaper',
41670
41701
  'uploadPortfolio',
41671
41702
  'fileWrite',
41672
41703
  'fileRead',
41673
41704
  ]);
41674
- const LogPayloadBlockMethod = new Set([
41675
- 'deviceUploadNft',
41676
- 'deviceUploadWallpaper',
41677
- 'uploadPortfolio',
41678
- ]);
41679
- const SensitiveLogKeys = new Set([
41680
- 'devicestate',
41681
- 'entropy',
41682
- 'expectedpassphrasestate',
41683
- 'mnemonic',
41684
- 'passphrase',
41685
- 'passphrasestate',
41686
- 'password',
41687
- 'pin',
41688
- 'privatekey',
41689
- 'seed',
41690
- 'session',
41691
- 'sessionid',
41692
- 'walletsessionid',
41693
- 'xprv',
41694
- ]);
41695
- const normalizeLogKey = (key) => key.replace(/[_-]/g, '').toLowerCase();
41696
- const isSigningMethod = (methodName) => /sign/i.test(methodName);
41697
- const redactLogValue = (value, seen) => {
41698
- if (ArrayBuffer.isView(value)) {
41699
- return `[BINARY:${value.byteLength}]`;
41700
- }
41701
- if (value instanceof ArrayBuffer) {
41702
- return `[BINARY:${value.byteLength}]`;
41703
- }
41704
- if (Array.isArray(value)) {
41705
- return value.map(item => redactLogValue(item, seen));
41706
- }
41707
- if (!value || typeof value !== 'object')
41708
- return value;
41709
- if (seen.has(value))
41710
- return '[CIRCULAR]';
41711
- seen.add(value);
41712
- const redacted = Object.fromEntries(Object.entries(value).map(([key, item]) => [
41713
- key,
41714
- SensitiveLogKeys.has(normalizeLogKey(key)) && item !== null && item !== undefined
41715
- ? '[REDACTED]'
41716
- : redactLogValue(item, seen),
41717
- ]));
41718
- seen.delete(value);
41719
- return redacted;
41720
- };
41721
41705
  function getLogBlockLabel(message) {
41722
41706
  if (!message || typeof message !== 'object')
41723
41707
  return undefined;
@@ -41726,26 +41710,16 @@ function getLogBlockLabel(message) {
41726
41710
  return type;
41727
41711
  }
41728
41712
  const methodName = method !== null && method !== void 0 ? method : payload === null || payload === void 0 ? void 0 : payload.method;
41729
- if (methodName && (LogLabelMethod.has(methodName) || isSigningMethod(methodName))) {
41713
+ if (methodName && LogPayloadBlockMethod.has(methodName)) {
41730
41714
  return methodName;
41731
41715
  }
41732
41716
  return undefined;
41733
41717
  }
41734
41718
  function getSafeLogPayload(value, blockLabel) {
41735
- if (blockLabel &&
41736
- (LogBlockEvent.has(blockLabel) ||
41737
- LogPayloadBlockMethod.has(blockLabel) ||
41738
- isSigningMethod(blockLabel))) {
41719
+ if (blockLabel) {
41739
41720
  return { method: blockLabel, payload: '[REDACTED]' };
41740
41721
  }
41741
- const redactedValue = redactLogValue(value, new WeakSet());
41742
- if (blockLabel &&
41743
- redactedValue &&
41744
- typeof redactedValue === 'object' &&
41745
- !Array.isArray(redactedValue)) {
41746
- return Object.assign(Object.assign({}, redactedValue), { method: blockLabel });
41747
- }
41748
- return redactedValue;
41722
+ return value;
41749
41723
  }
41750
41724
  function formatLogMethodLabel(label, methodName) {
41751
41725
  return methodName ? `${label} [${methodName}]` : label;
@@ -41869,7 +41843,7 @@ const selectDeviceSession = (device, expectedPassphraseState, deriveCardano, onS
41869
41843
  return getDeviceSession(device, buildDeviceSessionGetRequest());
41870
41844
  });
41871
41845
  function getProtocolV2WalletSession(device, options) {
41872
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
41846
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
41873
41847
  return __awaiter(this, void 0, void 0, function* () {
41874
41848
  const forceWalletSelection = (options === null || options === void 0 ? void 0 : options.forceWalletSelection) === true || (options === null || options === void 0 ? void 0 : options.initSession) === true;
41875
41849
  const readCurrentAttachPinSession = (options === null || options === void 0 ? void 0 : options.readCurrentAttachPinSession) === true;
@@ -41904,11 +41878,16 @@ function getProtocolV2WalletSession(device, options) {
41904
41878
  ? device.getInternalState()
41905
41879
  : undefined;
41906
41880
  let response;
41881
+ let walletSelectionRequested = false;
41907
41882
  let resumed = false;
41908
41883
  let walletStatusRefreshed = false;
41909
41884
  const markWalletStatusRefreshed = () => {
41910
41885
  walletStatusRefreshed = true;
41911
41886
  };
41887
+ if ((options === null || options === void 0 ? void 0 : options.onlyMainPin) && options.mainPinSelected !== true) {
41888
+ yield refreshProtocolV2DeviceStatus(device);
41889
+ markWalletStatusRefreshed();
41890
+ }
41912
41891
  let mainPinAuthenticated = (options === null || options === void 0 ? void 0 : options.mainPinSelected) === true ||
41913
41892
  ((options === null || options === void 0 ? void 0 : options.onlyMainPin) === true &&
41914
41893
  ((_d = device.features) === null || _d === void 0 ? void 0 : _d.unlocked) === true &&
@@ -41936,7 +41915,7 @@ function getProtocolV2WalletSession(device, options) {
41936
41915
  return keepAttachPin ? Object.assign(session, { viaAttachPin: true }) : session;
41937
41916
  });
41938
41917
  const rejectMismatchedAttachPinWallet = () => __awaiter(this, void 0, void 0, function* () {
41939
- var _m;
41918
+ var _o;
41940
41919
  const features = yield refreshProtocolV2DeviceStatus(device);
41941
41920
  markWalletStatusRefreshed();
41942
41921
  if (features.unlockedAttachPin !== true) {
@@ -41945,10 +41924,10 @@ function getProtocolV2WalletSession(device, options) {
41945
41924
  try {
41946
41925
  yield device.lockDevice();
41947
41926
  }
41948
- catch (_o) {
41927
+ catch (_p) {
41949
41928
  }
41950
41929
  if (options === null || options === void 0 ? void 0 : options.rejectAttachPinForMainWallet) {
41951
- (_m = device.clearStandardInternalState) === null || _m === void 0 ? void 0 : _m.call(device);
41930
+ (_o = device.clearStandardInternalState) === null || _o === void 0 ? void 0 : _o.call(device);
41952
41931
  device.clearInternalState();
41953
41932
  }
41954
41933
  else {
@@ -41957,11 +41936,11 @@ function getProtocolV2WalletSession(device, options) {
41957
41936
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckUnlockTypeError);
41958
41937
  });
41959
41938
  const lockAttachPinBeforePassphraseSelection = () => __awaiter(this, void 0, void 0, function* () {
41960
- var _p;
41939
+ var _q;
41961
41940
  if (readCurrentAttachPinSession || (options === null || options === void 0 ? void 0 : options.onlyMainPin)) {
41962
41941
  return;
41963
41942
  }
41964
- if (((_p = device.features) === null || _p === void 0 ? void 0 : _p.unlockedAttachPin) !== true) {
41943
+ if (((_q = device.features) === null || _q === void 0 ? void 0 : _q.unlockedAttachPin) !== true) {
41965
41944
  return;
41966
41945
  }
41967
41946
  yield rejectMismatchedAttachPinWallet();
@@ -41982,8 +41961,8 @@ function getProtocolV2WalletSession(device, options) {
41982
41961
  }
41983
41962
  });
41984
41963
  const selectStandardWallet = (forceMainPin = false) => __awaiter(this, void 0, void 0, function* () {
41985
- var _q;
41986
- if (((_q = device.features) === null || _q === void 0 ? void 0 : _q.passphraseProtection) === true) {
41964
+ var _r;
41965
+ if (((_r = device.features) === null || _r === void 0 ? void 0 : _r.passphraseProtection) === true) {
41987
41966
  yield selectMainPin();
41988
41967
  yield askDevicePassphrase(device, {
41989
41968
  passphrase: '',
@@ -42048,6 +42027,9 @@ function getProtocolV2WalletSession(device, options) {
42048
42027
  throw error;
42049
42028
  }
42050
42029
  resumed = false;
42030
+ if (((_g = device.features) === null || _g === void 0 ? void 0 : _g.unlockedAttachPin) === true) {
42031
+ response = yield getDeviceSession(device, sessionGetRequest());
42032
+ }
42051
42033
  }
42052
42034
  }
42053
42035
  else if (expectedPassphraseState) {
@@ -42068,6 +42050,7 @@ function getProtocolV2WalletSession(device, options) {
42068
42050
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.WalletSessionInvalid);
42069
42051
  }
42070
42052
  yield lockAttachPinBeforePassphraseSelection();
42053
+ walletSelectionRequested = true;
42071
42054
  response = yield selectDeviceSession(device, expectedPassphraseState, options === null || options === void 0 ? void 0 : options.deriveCardano, markWalletStatusRefreshed);
42072
42055
  }
42073
42056
  let { message } = response;
@@ -42076,7 +42059,7 @@ function getProtocolV2WalletSession(device, options) {
42076
42059
  }
42077
42060
  catch (error) {
42078
42061
  if (options === null || options === void 0 ? void 0 : options.onlyMainPin) {
42079
- (_g = device.clearStandardInternalState) === null || _g === void 0 ? void 0 : _g.call(device);
42062
+ (_h = device.clearStandardInternalState) === null || _h === void 0 ? void 0 : _h.call(device);
42080
42063
  }
42081
42064
  else {
42082
42065
  device.clearInternalState();
@@ -42090,8 +42073,12 @@ function getProtocolV2WalletSession(device, options) {
42090
42073
  device.clearInternalState();
42091
42074
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.WalletSessionInvalid);
42092
42075
  }
42076
+ if (walletSelectionRequested) {
42077
+ clearCurrentWalletSession();
42078
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckPassphraseStateError);
42079
+ }
42093
42080
  if (options === null || options === void 0 ? void 0 : options.onlyMainPin) {
42094
- (_h = device.clearStandardInternalState) === null || _h === void 0 ? void 0 : _h.call(device);
42081
+ (_j = device.clearStandardInternalState) === null || _j === void 0 ? void 0 : _j.call(device);
42095
42082
  yield selectStandardWallet(true);
42096
42083
  response = yield getDeviceSession(device, sessionGetRequest());
42097
42084
  }
@@ -42106,7 +42093,7 @@ function getProtocolV2WalletSession(device, options) {
42106
42093
  }
42107
42094
  catch (error) {
42108
42095
  if (options === null || options === void 0 ? void 0 : options.onlyMainPin) {
42109
- (_j = device.clearStandardInternalState) === null || _j === void 0 ? void 0 : _j.call(device);
42096
+ (_k = device.clearStandardInternalState) === null || _k === void 0 ? void 0 : _k.call(device);
42110
42097
  }
42111
42098
  else {
42112
42099
  device.clearInternalState();
@@ -42129,7 +42116,7 @@ function getProtocolV2WalletSession(device, options) {
42129
42116
  if (sessionIsAttachPinWallet(response)) {
42130
42117
  response = yield askEmptyPassphraseAndGet({ deriveCardano: true, keepAttachPin: true });
42131
42118
  }
42132
- else if (((_k = device.features) === null || _k === void 0 ? void 0 : _k.passphraseProtection) === false) {
42119
+ else if (((_l = device.features) === null || _l === void 0 ? void 0 : _l.passphraseProtection) === false) {
42133
42120
  response = yield getDeviceSession(device, buildDeviceSessionGetRequest());
42134
42121
  }
42135
42122
  else if (options === null || options === void 0 ? void 0 : options.onlyMainPin) {
@@ -42146,7 +42133,7 @@ function getProtocolV2WalletSession(device, options) {
42146
42133
  }
42147
42134
  catch (error) {
42148
42135
  if (options === null || options === void 0 ? void 0 : options.onlyMainPin) {
42149
- (_l = device.clearStandardInternalState) === null || _l === void 0 ? void 0 : _l.call(device);
42136
+ (_m = device.clearStandardInternalState) === null || _m === void 0 ? void 0 : _m.call(device);
42150
42137
  }
42151
42138
  else {
42152
42139
  device.clearInternalState();
@@ -43718,6 +43705,18 @@ class TransportManager {
43718
43705
  this.defaultMessages = DataManager.getProtobufMessages();
43719
43706
  this.currentMessages = this.defaultMessages;
43720
43707
  this.protocolV1MessageSchema = 'v1CurrentSchema';
43708
+ this.webUsbInit = false;
43709
+ }
43710
+ static ensureInitialized() {
43711
+ return __awaiter(this, void 0, void 0, function* () {
43712
+ const env = DataManager.getSettings('env');
43713
+ if (env !== 'webusb' && env !== 'desktop-webusb')
43714
+ return;
43715
+ if (this.webUsbInit)
43716
+ return;
43717
+ yield this.transport.init(WebUsbLogger, DevicePool.emitter);
43718
+ this.webUsbInit = true;
43719
+ });
43721
43720
  }
43722
43721
  static configure() {
43723
43722
  return __awaiter(this, void 0, void 0, function* () {
@@ -43746,7 +43745,7 @@ class TransportManager {
43746
43745
  yield this.transport.init(WebBleLogger, DevicePool.emitter);
43747
43746
  }
43748
43747
  else if (env === 'webusb' || env === 'desktop-webusb') {
43749
- yield this.transport.init(WebUsbLogger, DevicePool.emitter);
43748
+ yield this.ensureInitialized();
43750
43749
  }
43751
43750
  else {
43752
43751
  yield this.transport.init(HttpLogger);
@@ -43829,6 +43828,7 @@ class TransportManager {
43829
43828
  }
43830
43829
  }
43831
43830
  TransportManager.reactNativeInit = false;
43831
+ TransportManager.webUsbInit = false;
43832
43832
  TransportManager.protocolV1MessageSchema = 'v1CurrentSchema';
43833
43833
  TransportManager.plugin = null;
43834
43834
 
@@ -43951,6 +43951,7 @@ class DeviceCommands {
43951
43951
  var _a, _b;
43952
43952
  return __awaiter(this, void 0, void 0, function* () {
43953
43953
  this.disposed = true;
43954
+ this.disposalToken = {};
43954
43955
  yield ((_b = (_a = this.transport).cancel) === null || _b === void 0 ? void 0 : _b.call(_a));
43955
43956
  });
43956
43957
  }
@@ -44124,7 +44125,24 @@ class DeviceCommands {
44124
44125
  }
44125
44126
  _commonCall(type, msg, options) {
44126
44127
  return __awaiter(this, void 0, void 0, function* () {
44127
- const resp = yield this.call(type, msg, options);
44128
+ const { disposalToken } = this;
44129
+ let resp = yield this.call(type, msg, options);
44130
+ for (let retry = 0; retry < 3 &&
44131
+ this.device.isProtocolV2() &&
44132
+ DEVICE_SESSION_CALLS.has(type) &&
44133
+ resp.type === 'Failure' &&
44134
+ resp.message.code === 'Failure_ProcessError' &&
44135
+ resp.message.subcode === hdTransport.DeviceSessionErrorCode.DeviceSessionError_Busy; retry += 1) {
44136
+ yield wait(100);
44137
+ if (this.device.wasInterruptedByUser()) {
44138
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
44139
+ }
44140
+ this.checkDisposed();
44141
+ if (this.disposalToken !== disposalToken) {
44142
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'DeviceCommands lifecycle changed');
44143
+ }
44144
+ resp = yield this.call(type, msg, options);
44145
+ }
44128
44146
  return this._filterCommonTypes(resp, type, options);
44129
44147
  });
44130
44148
  }
@@ -46345,6 +46363,10 @@ class Device extends events.exports {
46345
46363
  }
46346
46364
  this.invalidateProtocolV2RuntimeState();
46347
46365
  }
46366
+ waitForRunCleanup() {
46367
+ var _a;
46368
+ return (_a = this.runCleanupPromise) !== null && _a !== void 0 ? _a : Promise.resolve();
46369
+ }
46348
46370
  run(fn, options) {
46349
46371
  return __awaiter(this, void 0, void 0, function* () {
46350
46372
  if (this.runPromise) {
@@ -46462,44 +46484,68 @@ class Device extends events.exports {
46462
46484
  });
46463
46485
  }
46464
46486
  interruptionFromUser() {
46465
- var _a, _b, _c, _d;
46466
- return __awaiter(this, void 0, void 0, function* () {
46467
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
46468
- this.interruptedAttempt = this.connectionAttempt;
46469
- const cleanupPromise = this.runCleanupPromise;
46470
- const { cancelableAction } = this;
46471
- if (cancelableAction) {
46472
- yield cancelableAction(error);
46473
- }
46474
- else if (this.shouldSendFallbackProtocolCancel()) {
46475
- yield ((_b = (_a = this.commands) === null || _a === void 0 ? void 0 : _a.cancelDevice) === null || _b === void 0 ? void 0 : _b.call(_a).catch(cancelError => {
46476
- Log$h.debug('Protocol V2 fallback cancel error', cancelError);
46477
- }));
46487
+ var _a;
46488
+ const attempt = this.connectionAttempt;
46489
+ if (((_a = this.userInterruption) === null || _a === void 0 ? void 0 : _a.attempt) === attempt) {
46490
+ return this.userInterruption.promise;
46491
+ }
46492
+ const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
46493
+ this.interruptedAttempt = attempt;
46494
+ const cleanupPromise = this.runCleanupPromise;
46495
+ const { cancelableAction, commands, runPromise, deviceConnector, mainId } = this;
46496
+ const sendFallbackCancel = this.shouldSendFallbackProtocolCancel();
46497
+ const acquired = this.hasDeviceAcquire();
46498
+ const promise = (() => __awaiter(this, void 0, void 0, function* () {
46499
+ var _b;
46500
+ try {
46501
+ if (cancelableAction) {
46502
+ yield cancelableAction(error);
46503
+ }
46504
+ else if (sendFallbackCancel) {
46505
+ yield ((_b = commands === null || commands === void 0 ? void 0 : commands.cancelDevice) === null || _b === void 0 ? void 0 : _b.call(commands).catch(cancelError => {
46506
+ Log$h.debug('Protocol V2 fallback cancel error', cancelError);
46507
+ }));
46508
+ }
46509
+ else if (!acquired) {
46510
+ if (mainId && (deviceConnector === null || deviceConnector === void 0 ? void 0 : deviceConnector.disconnect)) {
46511
+ Log$h.debug('interruptionFromUser: disconnecting device without acquire, mainId:', mainId);
46512
+ yield deviceConnector.disconnect(mainId);
46513
+ }
46514
+ if (this.connectionAttempt === attempt)
46515
+ this.markTransportDisconnected();
46516
+ }
46517
+ yield (commands === null || commands === void 0 ? void 0 : commands.cancel());
46478
46518
  }
46479
- else if (!this.hasDeviceAcquire()) {
46480
- if (this.mainId && ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.disconnect)) {
46481
- yield this.deviceConnector.disconnect(this.mainId).catch(disconnectError => {
46482
- Log$h.debug('Ignored disconnect during user cancel without acquire', disconnectError);
46519
+ catch (cleanupError) {
46520
+ Log$h.warn('User cancellation cleanup failed; disconnecting device', cleanupError);
46521
+ if (mainId && (deviceConnector === null || deviceConnector === void 0 ? void 0 : deviceConnector.disconnect)) {
46522
+ yield deviceConnector.disconnect(mainId).catch(disconnectError => {
46523
+ Log$h.debug('User cancellation fallback disconnect failed', disconnectError);
46483
46524
  });
46484
46525
  }
46485
- this.markTransportDisconnected();
46526
+ if (this.connectionAttempt === attempt)
46527
+ this.markTransportDisconnected();
46486
46528
  }
46487
- yield ((_d = this.commands) === null || _d === void 0 ? void 0 : _d.cancel());
46488
- if (this.runPromise) {
46489
- this.runPromise.reject(error);
46490
- this.runPromise = null;
46529
+ finally {
46530
+ runPromise === null || runPromise === void 0 ? void 0 : runPromise.reject(error);
46531
+ if (this.runPromise === runPromise)
46532
+ this.runPromise = null;
46533
+ yield (cleanupPromise === null || cleanupPromise === void 0 ? void 0 : cleanupPromise.catch(() => undefined));
46491
46534
  }
46492
- yield (cleanupPromise === null || cleanupPromise === void 0 ? void 0 : cleanupPromise.catch(() => undefined));
46493
- });
46535
+ }))();
46536
+ this.userInterruption = { attempt, promise };
46537
+ return promise;
46494
46538
  }
46495
46539
  setCancelableAction(callback) {
46496
- this.cancelableAction = (e) => callback(e)
46540
+ const action = (e) => callback(e)
46497
46541
  .catch(e2 => {
46498
46542
  Log$h.debug('cancelableAction error', e2);
46499
46543
  })
46500
46544
  .finally(() => {
46501
- this.clearCancelableAction();
46545
+ if (this.cancelableAction === action)
46546
+ this.clearCancelableAction();
46502
46547
  });
46548
+ this.cancelableAction = action;
46503
46549
  }
46504
46550
  clearCancelableAction() {
46505
46551
  this.cancelableAction = undefined;
@@ -47231,6 +47277,48 @@ class PreInitialize extends BaseMethod {
47231
47277
  }
47232
47278
 
47233
47279
  const Log$e = getLogger(exports.LoggerNames.DevicePool);
47280
+ const getDescriptorKeys = (descriptor) => [descriptor.path, descriptor.id].filter((key) => typeof key === 'string' && key.length > 0);
47281
+ const isOwnedByActiveWebUsbRequest = (descriptor, requestQueue) => {
47282
+ if (!requestQueue)
47283
+ return false;
47284
+ return getDescriptorKeys(descriptor).some(key => requestQueue.getRequestTasksIdByConnectId(key).length > 0);
47285
+ };
47286
+ const getUsbHandle = (descriptor) => descriptor === null || descriptor === void 0 ? void 0 : descriptor.device;
47287
+ const getOwningRequestDevice = (descriptor, requestQueue) => {
47288
+ var _a, _b;
47289
+ if (!requestQueue)
47290
+ return undefined;
47291
+ const usbHandle = getUsbHandle(descriptor);
47292
+ if (usbHandle === undefined)
47293
+ return undefined;
47294
+ for (const key of getDescriptorKeys(descriptor)) {
47295
+ for (const requestId of requestQueue.getRequestTasksIdByConnectId(key)) {
47296
+ const device = (_a = requestQueue.getTask(requestId)) === null || _a === void 0 ? void 0 : _a.method.device;
47297
+ if ((device === null || device === void 0 ? void 0 : device.features) &&
47298
+ (device.mainId === key || ((_b = device.originalDescriptor) === null || _b === void 0 ? void 0 : _b.path) === key) &&
47299
+ getUsbHandle(device.originalDescriptor) === usbHandle) {
47300
+ return device;
47301
+ }
47302
+ }
47303
+ }
47304
+ return undefined;
47305
+ };
47306
+ const toSearchDeviceFromDescriptor = (descriptor) => {
47307
+ const connectId = descriptor.path || descriptor.id || null;
47308
+ return {
47309
+ connectId,
47310
+ uuid: '',
47311
+ serialNo: null,
47312
+ deviceId: null,
47313
+ deviceType: hdShared.EDeviceType.Unknown,
47314
+ name: descriptor.name || connectId || '',
47315
+ commType: descriptor.commType,
47316
+ };
47317
+ };
47318
+ const toSearchDevice = (device) => {
47319
+ const message = device.toMessageObject();
47320
+ return message ? message : null;
47321
+ };
47234
47322
  class SearchDevices extends BaseMethod {
47235
47323
  init() {
47236
47324
  this.useDevice = false;
@@ -47238,20 +47326,32 @@ class SearchDevices extends BaseMethod {
47238
47326
  this.skipForceUpdateCheck = true;
47239
47327
  }
47240
47328
  run() {
47241
- var _a, _b, _c, _d, _e;
47329
+ var _a, _b, _c, _d, _e, _f, _g;
47242
47330
  return __awaiter(this, void 0, void 0, function* () {
47243
- yield TransportManager.configure();
47244
- const deviceDiff = yield ((_a = this.connector) === null || _a === void 0 ? void 0 : _a.enumerate());
47245
- const devicesDescriptor = (_b = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _b !== void 0 ? _b : [];
47246
47331
  const env = DataManager.getSettings('env');
47332
+ const isWebUsb = env === 'webusb' || env === 'desktop-webusb';
47333
+ const requestQueue = (_a = this.context) === null || _a === void 0 ? void 0 : _a.requestQueue;
47334
+ const hasActiveWebUsbRequest = isWebUsb && ((_b = requestQueue === null || requestQueue === void 0 ? void 0 : requestQueue.getRequestTasksId().length) !== null && _b !== void 0 ? _b : 0) > 0;
47335
+ if (isWebUsb) {
47336
+ try {
47337
+ yield TransportManager.ensureInitialized();
47338
+ }
47339
+ catch (error) {
47340
+ Log$e.debug('WebUSB bring-up unavailable', error);
47341
+ }
47342
+ }
47343
+ if (!hasActiveWebUsbRequest)
47344
+ yield TransportManager.configure();
47345
+ const deviceDiff = yield ((_c = this.connector) === null || _c === void 0 ? void 0 : _c.enumerate());
47346
+ const devicesDescriptor = (_d = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _d !== void 0 ? _d : [];
47247
47347
  if (DataManager.isBleConnect(env)) {
47248
47348
  const devices = [];
47249
47349
  const seenIds = new Set();
47250
47350
  for (const device of devicesDescriptor) {
47251
- const lowerId = (_c = device.id) === null || _c === void 0 ? void 0 : _c.toLowerCase();
47351
+ const lowerId = (_e = device.id) === null || _e === void 0 ? void 0 : _e.toLowerCase();
47252
47352
  if (!seenIds.has(lowerId)) {
47253
47353
  seenIds.add(lowerId);
47254
- const rawBleName = (_e = (_d = device.name) !== null && _d !== void 0 ? _d : device.localName) !== null && _e !== void 0 ? _e : '';
47354
+ const rawBleName = (_g = (_f = device.name) !== null && _f !== void 0 ? _f : device.localName) !== null && _g !== void 0 ? _g : '';
47255
47355
  const bleName = hdShared.canonicalizePro2BleAdvertisementName(rawBleName);
47256
47356
  devices.push(Object.assign(Object.assign({}, device), { connectId: device.id, serialNo: null, uuid: '', deviceId: null, name: bleName || device.name, deviceType: getDeviceTypeByBleName(bleName) }));
47257
47357
  }
@@ -47260,22 +47360,34 @@ class SearchDevices extends BaseMethod {
47260
47360
  }
47261
47361
  const deviceList = [];
47262
47362
  for (const descriptor of devicesDescriptor) {
47263
- try {
47264
- const result = yield DevicePool.getDevices([descriptor], descriptor.path, {
47265
- connectProtocol: undefined,
47266
- forceProtocolDetection: true,
47267
- refreshRuntimeState: true,
47268
- });
47269
- deviceList.push(...result.deviceList);
47363
+ if (hasActiveWebUsbRequest && isOwnedByActiveWebUsbRequest(descriptor, requestQueue)) {
47364
+ const cached = DevicePool.getDeviceByPath(descriptor.path);
47365
+ const known = (cached === null || cached === void 0 ? void 0 : cached.features) ? cached : getOwningRequestDevice(descriptor, requestQueue);
47366
+ const message = known ? toSearchDevice(known) : null;
47367
+ deviceList.push(message !== null && message !== void 0 ? message : toSearchDeviceFromDescriptor(descriptor));
47270
47368
  }
47271
- catch (error) {
47272
- const errorCode = error && typeof error === 'object' && 'errorCode' in error
47273
- ? error.errorCode
47274
- : undefined;
47275
- Log$e.debug('Skip unavailable device during search', Object.assign({ path: descriptor.path }, (errorCode !== undefined ? { errorCode } : {})));
47369
+ else {
47370
+ try {
47371
+ const result = yield DevicePool.getDevices([descriptor], descriptor.path, {
47372
+ connectProtocol: undefined,
47373
+ forceProtocolDetection: true,
47374
+ refreshRuntimeState: true,
47375
+ });
47376
+ for (const device of result.deviceList) {
47377
+ const message = toSearchDevice(device);
47378
+ if (message)
47379
+ deviceList.push(message);
47380
+ }
47381
+ }
47382
+ catch (error) {
47383
+ const errorCode = error && typeof error === 'object' && 'errorCode' in error
47384
+ ? error.errorCode
47385
+ : undefined;
47386
+ Log$e.debug('Skip unavailable device during search', Object.assign({ path: descriptor.path }, (errorCode !== undefined ? { errorCode } : {})));
47387
+ }
47276
47388
  }
47277
47389
  }
47278
- return deviceList.map(device => device.toMessageObject());
47390
+ return deviceList;
47279
47391
  });
47280
47392
  }
47281
47393
  }
@@ -47609,15 +47721,6 @@ function validateResult(result, nonNullableFields, options) {
47609
47721
  }
47610
47722
  }
47611
47723
 
47612
- const requiredString = (value, name) => {
47613
- if (value === undefined || value === null) {
47614
- throw invalidParameter(`Missing required parameter: ${name}`);
47615
- }
47616
- if (typeof value !== 'string' || !value.trim()) {
47617
- throw invalidParameter(`Parameter [${name}] must be a non-empty string.`);
47618
- }
47619
- return value.trim();
47620
- };
47621
47724
  const wasResumed = (session) => !!session &&
47622
47725
  typeof session === 'object' &&
47623
47726
  'resumed' in session &&
@@ -47639,25 +47742,16 @@ const normalizeParams = (payload) => {
47639
47742
  throw invalidParameter('Parameter [mode] is required.');
47640
47743
  }
47641
47744
  if (payload.mode !== OpenWalletSessionMode.Standard &&
47642
- payload.mode !== OpenWalletSessionMode.SelectHidden &&
47643
- payload.mode !== OpenWalletSessionMode.ResumeHidden) {
47644
- throw invalidParameter('Parameter [mode] must be one of standard, select-hidden, or resume-hidden.');
47745
+ payload.mode !== OpenWalletSessionMode.SelectHidden) {
47746
+ throw invalidParameter('Parameter [mode] must be one of standard or select-hidden.');
47645
47747
  }
47646
47748
  if (payload.useEmptyPassphrase !== undefined || payload.initSession !== undefined) {
47647
47749
  throw invalidParameter('Legacy parameters [useEmptyPassphrase] and [initSession] are not supported by openWalletSession.');
47648
47750
  }
47649
- if (payload.mode === OpenWalletSessionMode.Standard ||
47650
- payload.mode === OpenWalletSessionMode.SelectHidden) {
47651
- if (payload.deviceId !== undefined || payload.passphraseState !== undefined) {
47652
- throw invalidParameter('Parameters [deviceId] and [passphraseState] are only allowed with mode [resume-hidden].');
47653
- }
47654
- return { mode: payload.mode };
47751
+ if (payload.deviceId !== undefined || payload.passphraseState !== undefined) {
47752
+ throw invalidParameter('Parameters [deviceId] and [passphraseState] are not supported by openWalletSession. Pass passphraseState on later address and signing calls.');
47655
47753
  }
47656
- return {
47657
- mode: OpenWalletSessionMode.ResumeHidden,
47658
- deviceId: requiredString(payload.deviceId, 'deviceId'),
47659
- passphraseState: requiredString(payload.passphraseState, 'passphraseState'),
47660
- };
47754
+ return { mode: payload.mode };
47661
47755
  };
47662
47756
  class OpenWalletSession extends BaseMethod {
47663
47757
  getSupportedProtocols() {
@@ -47760,43 +47854,6 @@ class OpenWalletSession extends BaseMethod {
47760
47854
  resumed: wasResumed(session),
47761
47855
  };
47762
47856
  }
47763
- if (this.params.mode === OpenWalletSessionMode.ResumeHidden) {
47764
- if (isProtocolV2) {
47765
- yield ensureProtocolV2WalletStatus();
47766
- const refreshedDeviceId = requireDeviceId();
47767
- if (refreshedDeviceId !== this.params.deviceId) {
47768
- deviceWalletSessionStore.delete(this.params.deviceId, this.params.passphraseState);
47769
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckDeviceIdError);
47770
- }
47771
- }
47772
- else if (requireDeviceId() !== this.params.deviceId) {
47773
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckDeviceIdError);
47774
- }
47775
- this.device.passphraseState = this.params.passphraseState;
47776
- const cachedSessionId = deviceWalletSessionStore.get(this.params.deviceId, this.params.passphraseState);
47777
- if (!cachedSessionId && !isProtocolV2) {
47778
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.WalletSessionInvalid);
47779
- }
47780
- if (!isProtocolV2) {
47781
- yield this.device.initialize({
47782
- deviceId: this.params.deviceId,
47783
- passphraseState: this.params.passphraseState,
47784
- });
47785
- }
47786
- const session = isProtocolV2
47787
- ? yield getProtocolV2WalletSession(this.device, {
47788
- expectedPassphraseState: this.params.passphraseState,
47789
- })
47790
- : yield getPassphraseStateWithRefreshDeviceInfo(this.device, {
47791
- expectPassphraseState: this.params.passphraseState,
47792
- });
47793
- const deviceId = requireDeviceId();
47794
- if (session.passphraseState !== this.params.passphraseState) {
47795
- this.device.clearInternalState();
47796
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckPassphraseStateError);
47797
- }
47798
- return Object.assign(Object.assign({ protocol, walletType: 'hidden', deviceId }, requireHiddenWalletResponse(session)), { resumed: wasResumed(session) || (!isProtocolV2 && session.newSession === cachedSessionId) });
47799
- }
47800
47857
  this.device.passphraseState = undefined;
47801
47858
  const walletStatus = yield ensureProtocolV2WalletStatus();
47802
47859
  if (isProtocolV2 && walletStatus.status.passphraseProtection !== true) {
@@ -49207,6 +49264,14 @@ class DeviceVerify extends BaseMethod {
49207
49264
  this.unlockPolicy = 'unlock-before-run';
49208
49265
  this.protocolV2PreUnlockPinType = hdTransport.DeviceSessionPinType.Any;
49209
49266
  this.useDevicePassphraseState = false;
49267
+ this.protocolV2UiInteraction = {
49268
+ request: 'button',
49269
+ source: 'method-lifecycle',
49270
+ reason: 'device-management',
49271
+ completion: 'operation-completed',
49272
+ deviceOnly: true,
49273
+ operation: 'deviceVerify',
49274
+ };
49210
49275
  validateParams(this.payload, [{ name: 'dataHex', type: 'hexString' }]);
49211
49276
  this.params = {
49212
49277
  data: formatAnyHex(this.payload.dataHex),
@@ -52646,6 +52711,7 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
52646
52711
  this.protocolV2InstallDisconnectObserved = false;
52647
52712
  this.protocolV2InstallTerminalSuccessObserved = false;
52648
52713
  this.protocolV2LastTransferProgressAt = 0;
52714
+ this.protocolV2LastTransferredBytes = 0;
52649
52715
  }
52650
52716
  getSupportedProtocols() {
52651
52717
  return ['V2'];
@@ -53808,6 +53874,7 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
53808
53874
  this.postTipMessage(exports.FirmwareUpdateTipMessage.StartTransferData);
53809
53875
  this.protocolV2LastTransferProgress = undefined;
53810
53876
  this.protocolV2LastTransferProgressAt = 0;
53877
+ this.protocolV2LastTransferredBytes = 0;
53811
53878
  const transferStartedAt = Date.now();
53812
53879
  let processedSize = 0;
53813
53880
  for (const resource of resourcesToSync) {
@@ -53890,13 +53957,15 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
53890
53957
  const now = Date.now();
53891
53958
  const elapsedMs = Math.max(now - transferStartedAt, 0);
53892
53959
  const progress = Math.min(Math.ceil((transferredBytes / totalSize) * 100), 99);
53893
- const shouldPostProgress = progress !== this.protocolV2LastTransferProgress ||
53894
- now - this.protocolV2LastTransferProgressAt >=
53895
- PROTOCOL_V2_TRANSFER_PROGRESS_HEARTBEAT_MS ||
53896
- chunkEnd === source.size;
53960
+ const shouldPostProgress = transferredBytes >= this.protocolV2LastTransferredBytes &&
53961
+ (progress !== this.protocolV2LastTransferProgress ||
53962
+ now - this.protocolV2LastTransferProgressAt >=
53963
+ PROTOCOL_V2_TRANSFER_PROGRESS_HEARTBEAT_MS ||
53964
+ chunkEnd === source.size);
53897
53965
  if (shouldPostProgress) {
53898
53966
  this.protocolV2LastTransferProgress = progress;
53899
53967
  this.protocolV2LastTransferProgressAt = now;
53968
+ this.protocolV2LastTransferredBytes = transferredBytes;
53900
53969
  this.postProgressMessage(progress, 'transferData', {
53901
53970
  transferredBytes,
53902
53971
  totalBytes: totalSize,
@@ -55455,16 +55524,16 @@ const FILESYSTEM_FILE_WRITE_MESSAGE_TYPE = 60805;
55455
55524
  const PORTFOLIO_UPDATE_MESSAGE_TYPE = 61400;
55456
55525
  class UploadPortfolio extends FileWrite {
55457
55526
  init() {
55458
- const { packageBase64, timeoutMs } = this.payload;
55527
+ const { packageBase64, timeoutMs, uiMode = 'silent' } = this.payload;
55459
55528
  const packageBytes = decodeCanonicalBase64({
55460
55529
  value: packageBase64,
55461
55530
  parameterName: 'packageBase64',
55462
55531
  maxBytes: PORTFOLIO_PACKAGE_MAX_BYTES,
55463
55532
  });
55464
- this.payload = Object.assign(Object.assign({}, this.payload), { path: PORTFOLIO_PENDING_PATH, offset: 0, data: packageBytes, chunkSize: PORTFOLIO_CHUNK_SIZE, overwrite: true, append: false, emitProgress: false, timeoutMs });
55533
+ this.payload = Object.assign(Object.assign({}, this.payload), { path: PORTFOLIO_PENDING_PATH, offset: 0, data: packageBytes, chunkSize: PORTFOLIO_CHUNK_SIZE, overwrite: true, append: false, emitProgress: uiMode === 'progress', timeoutMs });
55465
55534
  super.init();
55466
55535
  this.unlockPolicy = 'none';
55467
- this.protocolV2UiMode = 'none';
55536
+ this.protocolV2UiMode = uiMode === 'progress' ? 'auto' : 'none';
55468
55537
  }
55469
55538
  run() {
55470
55539
  const _super = Object.create(null, {
@@ -55925,6 +55994,8 @@ class AllNetworkGetAddressBase extends BaseMethod {
55925
55994
  constructor() {
55926
55995
  super(...arguments);
55927
55996
  this.abortController = null;
55997
+ this.loadingCleanupInBackground = false;
55998
+ this.protocolV2ResumedSeedDomains = new Set();
55928
55999
  }
55929
56000
  getSupportedProtocols() {
55930
56001
  return ['V1', 'V2'];
@@ -55960,7 +56031,20 @@ class AllNetworkGetAddressBase extends BaseMethod {
55960
56031
  _originalIndex: originalIndex,
55961
56032
  };
55962
56033
  }
55963
- callMethod(methodName, params, rootFingerprint) {
56034
+ hasProtocolV2WalletResume(deriveCardano) {
56035
+ if (deriveCardano) {
56036
+ return this.protocolV2ResumedSeedDomains.has('cardano');
56037
+ }
56038
+ return (this.protocolV2ResumedSeedDomains.has('standard') ||
56039
+ this.protocolV2ResumedSeedDomains.has('cardano'));
56040
+ }
56041
+ markProtocolV2WalletResumed(deriveCardano) {
56042
+ this.protocolV2ResumedSeedDomains.add('standard');
56043
+ if (deriveCardano) {
56044
+ this.protocolV2ResumedSeedDomains.add('cardano');
56045
+ }
56046
+ }
56047
+ callMethod(methodName, params, rootFingerprint, postMessage = this.postMessage) {
55964
56048
  var _a, _b, _c;
55965
56049
  return __awaiter(this, void 0, void 0, function* () {
55966
56050
  const method = findMethod({
@@ -55969,7 +56053,7 @@ class AllNetworkGetAddressBase extends BaseMethod {
55969
56053
  payload: Object.assign({ connectId: this.payload.connectId, deviceId: this.payload.deviceId, method: methodName }, params),
55970
56054
  });
55971
56055
  method.connector = this.connector;
55972
- method.postMessage = this.postMessage;
56056
+ method.postMessage = postMessage;
55973
56057
  if (this.context) {
55974
56058
  (_a = method.setContext) === null || _a === void 0 ? void 0 : _a.call(method, this.context);
55975
56059
  }
@@ -56022,11 +56106,14 @@ class AllNetworkGetAddressBase extends BaseMethod {
56022
56106
  const useEmptyPassphrase = this.payload.useEmptyPassphrase === true;
56023
56107
  const deriveCardano = method.name.startsWith('cardano') ? true : undefined;
56024
56108
  const shouldResumeWalletSession = useEmptyPassphrase || !!this.payload.passphraseState;
56025
- if (this.device.isProtocolV2() && shouldResumeWalletSession) {
56109
+ if (this.device.isProtocolV2() &&
56110
+ shouldResumeWalletSession &&
56111
+ !this.hasProtocolV2WalletResume(deriveCardano)) {
56026
56112
  const passphraseStateSafety = yield this.device.checkPassphraseStateSafety(this.payload.passphraseState, useEmptyPassphrase, this.payload.skipPassphraseCheck, deriveCardano, (_d = this.protocolV2UnlockContext) === null || _d === void 0 ? void 0 : _d.preflightMainPinSelected);
56027
56113
  if (!passphraseStateSafety) {
56028
56114
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckPassphraseStateError);
56029
56115
  }
56116
+ this.markProtocolV2WalletResumed(deriveCardano);
56030
56117
  }
56031
56118
  }),
56032
56119
  });
@@ -56062,27 +56149,63 @@ class AllNetworkGetAddressBase extends BaseMethod {
56062
56149
  return result;
56063
56150
  });
56064
56151
  }
56065
- run() {
56152
+ stopAllNetworkLoading(canSend = true) {
56066
56153
  return __awaiter(this, void 0, void 0, function* () {
56067
- const res = yield this.device.commands.typedCall('GetPublicKey', 'PublicKey', {
56068
- address_n: [toHardened(44), toHardened(1), toHardened(0)],
56069
- coin_name: 'Testnet',
56070
- script_type: 'SPENDADDRESS',
56071
- show_display: false,
56072
- });
56073
- if (!this.device.isProtocolV2()) {
56074
- this.postMessage(createUiMessage(UI_REQUEST.CLOSE_UI_PIN_WINDOW));
56154
+ const commands = this.loadingCommands;
56155
+ this.loadingCommands = undefined;
56156
+ if (!canSend || !commands || commands.disposed || commands !== this.device.commands)
56157
+ return;
56158
+ try {
56159
+ yield commands.typedCall('DeviceAnimationControl', 'Success', {
56160
+ action: hdTransport.Messages.DeviceAnimationAction.AnimationAction_Stop,
56161
+ });
56075
56162
  }
56076
- if (res.message.root_fingerprint == null) {
56077
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter);
56163
+ catch (_a) {
56164
+ }
56165
+ });
56166
+ }
56167
+ run() {
56168
+ return __awaiter(this, void 0, void 0, function* () {
56169
+ this.loadingCleanupInBackground = false;
56170
+ try {
56171
+ if (this.device.isProtocolV2() &&
56172
+ (this.device.getCurrentDeviceType() === hdShared.EDeviceType.Pro2 ||
56173
+ this.device.getCurrentDeviceType() === hdShared.EDeviceType.Neo)) {
56174
+ const protocolInfo = yield this.device.ensureProtocolV2RuntimeContext();
56175
+ if (supportsProtocolV2Message(protocolInfo, 60461)) {
56176
+ const { commands } = this.device;
56177
+ yield commands.typedCall('DeviceAnimationControl', 'Success', {
56178
+ action: hdTransport.Messages.DeviceAnimationAction.AnimationAction_Start,
56179
+ });
56180
+ this.loadingCommands = commands;
56181
+ }
56182
+ }
56183
+ const res = yield this.device.commands.typedCall('GetPublicKey', 'PublicKey', {
56184
+ address_n: [toHardened(44), toHardened(1), toHardened(0)],
56185
+ coin_name: 'Testnet',
56186
+ script_type: 'SPENDADDRESS',
56187
+ show_display: false,
56188
+ });
56189
+ if (!this.device.isProtocolV2()) {
56190
+ this.postMessage(createUiMessage(UI_REQUEST.CLOSE_UI_PIN_WINDOW));
56191
+ }
56192
+ if (res.message.root_fingerprint == null) {
56193
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter);
56194
+ }
56195
+ this.abortController = new AbortController();
56196
+ return yield this.getAllNetworkAddress(res.message.root_fingerprint);
56078
56197
  }
56079
- this.abortController = new AbortController();
56080
- return this.getAllNetworkAddress(res.message.root_fingerprint).catch(e => {
56198
+ catch (e) {
56199
+ yield this.stopAllNetworkLoading(false);
56081
56200
  if (e instanceof hdShared.HardwareError && e.errorCode === hdShared.HardwareErrorCode.RepeatUnlocking) {
56082
56201
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RepeatUnlocking, e.message);
56083
56202
  }
56084
56203
  throw e;
56085
- });
56204
+ }
56205
+ finally {
56206
+ if (!this.loadingCleanupInBackground)
56207
+ yield this.stopAllNetworkLoading();
56208
+ }
56086
56209
  });
56087
56210
  }
56088
56211
  }
@@ -56143,57 +56266,83 @@ function handleSkippableHardwareError(e, device, method) {
56143
56266
  }
56144
56267
 
56145
56268
  class AllNetworkGetAddress extends AllNetworkGetAddressBase {
56269
+ checkAborted() {
56270
+ var _a;
56271
+ if ((_a = this.abortController) === null || _a === void 0 ? void 0 : _a.signal.aborted) {
56272
+ throw new Error(hdShared.HardwareErrorCodeMessage[hdShared.HardwareErrorCode.RepeatUnlocking]);
56273
+ }
56274
+ }
56275
+ callAddressGroup(methodName, params, rootFingerprint) {
56276
+ return __awaiter(this, void 0, void 0, function* () {
56277
+ const methodCallParams = { bundle: params.map(param => (Object.assign({}, param.params))) };
56278
+ if (!this.device.isProtocolV2() || params.length === 1) {
56279
+ return this.callMethod(methodName, methodCallParams, rootFingerprint);
56280
+ }
56281
+ const postedAddressCounts = new Map();
56282
+ let runningIndividually = false;
56283
+ const postMessage = message => {
56284
+ var _a;
56285
+ if (message.type === UI_REQUEST.PREVIOUS_ADDRESS_RESULT) {
56286
+ const { path, address } = message.payload.data;
56287
+ const key = JSON.stringify([path, address]);
56288
+ const count = (_a = postedAddressCounts.get(key)) !== null && _a !== void 0 ? _a : 0;
56289
+ if (runningIndividually && count > 0) {
56290
+ postedAddressCounts.set(key, count - 1);
56291
+ return;
56292
+ }
56293
+ if (!runningIndividually)
56294
+ postedAddressCounts.set(key, count + 1);
56295
+ }
56296
+ this.postMessage(message);
56297
+ };
56298
+ if (params.every(param => param._originRequestParams.showOnOneKey === false)) {
56299
+ const response = yield this.callMethod(methodName, methodCallParams, rootFingerprint, postMessage);
56300
+ if (response.some(item => item.success))
56301
+ return response;
56302
+ }
56303
+ runningIndividually = true;
56304
+ const responses = [];
56305
+ for (const param of params) {
56306
+ this.checkAborted();
56307
+ const response = yield this.callMethod(methodName, { bundle: [Object.assign({}, param.params)] }, rootFingerprint, postMessage);
56308
+ responses.push(...response);
56309
+ }
56310
+ return responses;
56311
+ });
56312
+ }
56146
56313
  getAllNetworkAddress(rootFingerprint) {
56147
- var _a, _b, _c, _d;
56148
56314
  return __awaiter(this, void 0, void 0, function* () {
56149
56315
  const responses = [];
56150
- const resultMap = {};
56151
56316
  const { bundle } = this.payload;
56152
56317
  const methodParams = bundle.map((param, index) => this.generateMethodName({
56153
56318
  network: param.network,
56154
56319
  payload: param,
56155
56320
  originalIndex: index,
56156
56321
  }));
56157
- const groupedMethodParams = methodParams.reduce((groups, param) => {
56322
+ const methodGroups = methodParams.reduce((groups, param) => {
56158
56323
  var _a;
56159
56324
  const group = (_a = groups.get(param.methodName)) !== null && _a !== void 0 ? _a : [];
56160
56325
  group.push(param);
56161
56326
  groups.set(param.methodName, group);
56162
56327
  return groups;
56163
56328
  }, new Map());
56164
- const requiresProtocolV2WalletHandoff = this.device.isProtocolV2() &&
56165
- (this.payload.useEmptyPassphrase === true || !!this.payload.passphraseState);
56166
- const methodGroups = requiresProtocolV2WalletHandoff
56167
- ? methodParams.map(param => [param.methodName, [param]])
56168
- : Array.from(groupedMethodParams.entries());
56169
- let i = 0;
56170
- for (const [methodName, params] of methodGroups) {
56171
- const methodParams = {
56172
- bundle: params.map(param => (Object.assign({}, param.params))),
56173
- };
56174
- if ((_a = this.abortController) === null || _a === void 0 ? void 0 : _a.signal.aborted) {
56175
- throw new Error(hdShared.HardwareErrorCodeMessage[hdShared.HardwareErrorCode.RepeatUnlocking]);
56176
- }
56177
- const response = yield this.callMethod(methodName, methodParams, rootFingerprint);
56178
- if ((_b = this.abortController) === null || _b === void 0 ? void 0 : _b.signal.aborted) {
56179
- throw new Error(hdShared.HardwareErrorCodeMessage[hdShared.HardwareErrorCode.RepeatUnlocking]);
56329
+ let processed = 0;
56330
+ for (const [methodName, params] of methodGroups.entries()) {
56331
+ this.checkAborted();
56332
+ const response = yield this.callAddressGroup(methodName, params, rootFingerprint);
56333
+ this.checkAborted();
56334
+ for (let index = 0; index < params.length; index++) {
56335
+ const { _originRequestParams, _originalIndex } = params[index];
56336
+ responses[_originalIndex] = Object.assign(Object.assign({}, _originRequestParams), response[index]);
56180
56337
  }
56181
- for (let i = 0; i < params.length; i++) {
56182
- const { _originRequestParams, _originalIndex } = params[i];
56183
- const responseKey = `${_originalIndex}`;
56184
- resultMap[responseKey] = Object.assign(Object.assign({}, _originRequestParams), response[i]);
56185
- }
56186
- if (((_d = (_c = this.payload) === null || _c === void 0 ? void 0 : _c.bundle) === null || _d === void 0 ? void 0 : _d.length) > 1) {
56187
- const progress = Math.round(((i + 1) / this.payload.bundle.length) * 100);
56338
+ processed += params.length;
56339
+ if (bundle.length > 1) {
56340
+ const progress = Math.round((processed / bundle.length) * 100);
56188
56341
  this.postMessage(createUiMessage(UI_REQUEST.DEVICE_PROGRESS, { progress }));
56189
56342
  }
56190
- i++;
56191
- }
56192
- for (let i = 0; i < bundle.length; i++) {
56193
- responses.push(resultMap[i]);
56194
56343
  }
56195
56344
  this.abortController = null;
56196
- return Promise.resolve(responses);
56345
+ return responses;
56197
56346
  });
56198
56347
  }
56199
56348
  }
@@ -56209,6 +56358,7 @@ class AllNetworkGetAddressByLoop extends AllNetworkGetAddressBase {
56209
56358
  throw new Error('callbackIdFinish is required');
56210
56359
  }
56211
56360
  const bundle = this.payload.bundle || [this.payload];
56361
+ this.loadingCleanupInBackground = true;
56212
56362
  const callbackPromise = this.processCallbacksInBackground(bundle, rootFingerprint, callbackId, callbackIdFinish);
56213
56363
  this.device.pendingCallbackPromise = hdShared.createDeferred(callbackPromise);
56214
56364
  if (this.context && this.payload.connectId) {
@@ -56249,6 +56399,7 @@ class AllNetworkGetAddressByLoop extends AllNetworkGetAddressBase {
56249
56399
  });
56250
56400
  }
56251
56401
  catch (error) {
56402
+ yield this.stopAllNetworkLoading(false);
56252
56403
  let errorCode = error.errorCode || error.code;
56253
56404
  let errorMessage = error.message;
56254
56405
  if (error instanceof hdShared.HardwareError) {
@@ -56276,6 +56427,7 @@ class AllNetworkGetAddressByLoop extends AllNetworkGetAddressBase {
56276
56427
  });
56277
56428
  }
56278
56429
  finally {
56430
+ yield this.stopAllNetworkLoading();
56279
56431
  (_c = this.context) === null || _c === void 0 ? void 0 : _c.cancelCallbackTasks(this.payload.connectId);
56280
56432
  this.abortController = null;
56281
56433
  }
@@ -59510,6 +59662,23 @@ class SolSignTransaction extends BaseMethod {
59510
59662
  }
59511
59663
  }
59512
59664
 
59665
+ const SOLANA_PUBLIC_KEY_LENGTH = 32;
59666
+ const SOLANA_APPLICATION_DOMAIN_LENGTH = 32;
59667
+ const normalizeRequiredSigners = (requiredSigners = []) => {
59668
+ const normalized = requiredSigners.map((signer, index) => {
59669
+ if (typeof signer !== 'string' ||
59670
+ !isHexString(addHexPrefix(signer), SOLANA_PUBLIC_KEY_LENGTH)) {
59671
+ throw invalidParameter(`Parameter [requiredSigners][${index}] must be a ${SOLANA_PUBLIC_KEY_LENGTH}-byte hex public key.`);
59672
+ }
59673
+ return stripHexPrefix(signer).toLowerCase();
59674
+ });
59675
+ for (let index = 1; index < normalized.length; index += 1) {
59676
+ if (normalized[index - 1] >= normalized[index]) {
59677
+ throw invalidParameter('Parameter [requiredSigners] must be strictly sorted and unique.');
59678
+ }
59679
+ }
59680
+ return normalized;
59681
+ };
59513
59682
  class SolSignOffchainMessage extends BaseMethod {
59514
59683
  getSupportedProtocols() {
59515
59684
  return ['V1', 'V2'];
@@ -59524,15 +59693,21 @@ class SolSignOffchainMessage extends BaseMethod {
59524
59693
  { name: 'messageVersion', type: 'number', required: false },
59525
59694
  { name: 'messageFormat', type: 'number', required: false },
59526
59695
  { name: 'applicationDomainHex', type: 'hexString', required: false },
59696
+ { name: 'requiredSigners', type: 'array', required: false, allowEmpty: true },
59527
59697
  ]);
59528
- const { path, messageHex, messageVersion, messageFormat, applicationDomainHex } = this.payload;
59698
+ const { path, messageHex, messageVersion, messageFormat, applicationDomainHex, requiredSigners, } = this.payload;
59529
59699
  const addressN = validatePath(path, 3);
59700
+ if (applicationDomainHex !== undefined &&
59701
+ !isHexString(addHexPrefix(applicationDomainHex), SOLANA_APPLICATION_DOMAIN_LENGTH)) {
59702
+ throw invalidParameter('Parameter [applicationDomainHex] must be 32 bytes.');
59703
+ }
59530
59704
  this.params = {
59531
59705
  address_n: addressN,
59532
59706
  message: stripHexPrefix(messageHex),
59533
59707
  message_version: messageVersion !== null && messageVersion !== void 0 ? messageVersion : undefined,
59534
59708
  message_format: messageFormat !== null && messageFormat !== void 0 ? messageFormat : undefined,
59535
- application_domain: applicationDomainHex !== null && applicationDomainHex !== void 0 ? applicationDomainHex : undefined,
59709
+ application_domain: applicationDomainHex ? stripHexPrefix(applicationDomainHex) : undefined,
59710
+ required_signers: normalizeRequiredSigners(requiredSigners),
59536
59711
  };
59537
59712
  }
59538
59713
  getVersionRange() {
@@ -65578,6 +65753,29 @@ class RequestQueue {
65578
65753
  getTask(requestId) {
65579
65754
  return this.requestQueue.get(requestId);
65580
65755
  }
65756
+ waitForTask(task, pending) {
65757
+ return __awaiter(this, void 0, void 0, function* () {
65758
+ const signal = task.method.abortSignal;
65759
+ const cancellationError = () => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled);
65760
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
65761
+ throw cancellationError();
65762
+ let onAbort;
65763
+ try {
65764
+ const cancelled = new Promise((_, reject) => {
65765
+ onAbort = () => reject(cancellationError());
65766
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onAbort, { once: true });
65767
+ });
65768
+ const result = yield Promise.race([pending(), cancelled]);
65769
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
65770
+ throw cancellationError();
65771
+ return result;
65772
+ }
65773
+ finally {
65774
+ if (onAbort)
65775
+ signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
65776
+ }
65777
+ });
65778
+ }
65581
65779
  getAbortController(requestId) {
65582
65780
  var _a;
65583
65781
  return (_a = this.requestQueue.get(requestId)) === null || _a === void 0 ? void 0 : _a.abortController;
@@ -65591,10 +65789,17 @@ class RequestQueue {
65591
65789
  }
65592
65790
  return false;
65593
65791
  }
65792
+ isRequestForConnectId(request, connectId) {
65793
+ var _a, _b;
65794
+ const { method } = request;
65795
+ return (method.connectId === connectId ||
65796
+ ((_a = method.device) === null || _a === void 0 ? void 0 : _a.mainId) === connectId ||
65797
+ ((_b = method.device) === null || _b === void 0 ? void 0 : _b.getConnectId()) === connectId);
65798
+ }
65594
65799
  abortRequestsByConnectId(connectId) {
65595
65800
  let count = 0;
65596
65801
  this.requestQueue.forEach((request, _) => {
65597
- if (request.abortController && request.method.connectId === connectId) {
65802
+ if (request.abortController && this.isRequestForConnectId(request, connectId)) {
65598
65803
  request.abortController.abort();
65599
65804
  request.abortController = undefined;
65600
65805
  count++;
@@ -65602,6 +65807,11 @@ class RequestQueue {
65602
65807
  });
65603
65808
  return count;
65604
65809
  }
65810
+ getRequestTasksIdByConnectId(connectId) {
65811
+ return Array.from(this.requestQueue.values())
65812
+ .filter(request => this.isRequestForConnectId(request, connectId))
65813
+ .map(request => request.id);
65814
+ }
65605
65815
  abortAllRequests() {
65606
65816
  let count = 0;
65607
65817
  this.requestQueue.forEach(request => {
@@ -65765,7 +65975,8 @@ const createUiProgressMessageFilter = (intervalMs = DEFAULT_UI_PROGRESS_INTERVAL
65765
65975
 
65766
65976
  const Log = getLogger(exports.LoggerNames.Core);
65767
65977
  const PRE_INITIALIZE_TTL_MS = 60 * 1000;
65768
- const PRE_PENDING_CALL_TIMEOUT_MS = 15 * 1000;
65978
+ const PRE_PENDING_CALL_TIMEOUT_MS = 5 * 1000;
65979
+ const PRO2_USB_SIGNING_COOLDOWN_MS = 1000;
65769
65980
  const preWarmInflight = new Map();
65770
65981
  const preWarmDoneAt = new Map();
65771
65982
  function resolveDeriveCardano(method) {
@@ -65844,6 +66055,7 @@ const callAPI = (context, message) => __awaiter(void 0, void 0, void 0, function
65844
66055
  }
65845
66056
  };
65846
66057
  (_a = method.setContext) === null || _a === void 0 ? void 0 : _a.call(method, context);
66058
+ method.context = context;
65847
66059
  method.requestContext = createRequestContext(method.responseID, method.name, {
65848
66060
  sdkInstanceId: context.sdkInstanceId,
65849
66061
  connectId: method.connectId,
@@ -65861,7 +66073,11 @@ const callAPI = (context, message) => __awaiter(void 0, void 0, void 0, function
65861
66073
  if (!method.useDevice) {
65862
66074
  updateMethodRequestContext(method, { status: 'running' });
65863
66075
  try {
65864
- const response = yield method.run();
66076
+ const env = DataManager.getSettings('env');
66077
+ const response = method.name === 'searchDevices' &&
66078
+ (DataManager.isBrowserWebUsb(env) || DataManager.isDesktopWebUsb(env))
66079
+ ? yield context.methodSynchronize(() => method.run(), 'webusb-discovery')
66080
+ : yield method.run();
65865
66081
  completeMethodRequestContext(method);
65866
66082
  return createResponseMessage(method.responseID, true, response);
65867
66083
  }
@@ -65933,6 +66149,7 @@ const waitForPendingPromise = (connectId, getPrePendingCallPromise, removePrePen
65933
66149
  Log.debug('pre pending call promise before call method, wait for it');
65934
66150
  let timer;
65935
66151
  let timedOut = false;
66152
+ let completed = false;
65936
66153
  try {
65937
66154
  yield Promise.race([
65938
66155
  pendingPromise,
@@ -65943,13 +66160,13 @@ const waitForPendingPromise = (connectId, getPrePendingCallPromise, removePrePen
65943
66160
  }, PRE_PENDING_CALL_TIMEOUT_MS);
65944
66161
  }),
65945
66162
  ]);
65946
- }
65947
- catch (error) {
66163
+ completed = !timedOut;
65948
66164
  }
65949
66165
  finally {
65950
66166
  if (timer)
65951
66167
  clearTimeout(timer);
65952
- removePrePendingCallPromise === null || removePrePendingCallPromise === void 0 ? void 0 : removePrePendingCallPromise(connectId, pendingPromise);
66168
+ if (timedOut || completed)
66169
+ removePrePendingCallPromise === null || removePrePendingCallPromise === void 0 ? void 0 : removePrePendingCallPromise(connectId, pendingPromise);
65953
66170
  }
65954
66171
  if (timedOut) {
65955
66172
  Log.warn('pre pending call promise timed out before call method', { connectId });
@@ -65957,8 +66174,19 @@ const waitForPendingPromise = (connectId, getPrePendingCallPromise, removePrePen
65957
66174
  Log.debug('pre pending call promise before call method done');
65958
66175
  }
65959
66176
  });
66177
+ function getPostCallPendingPromise(method, device) {
66178
+ const cleanupPromise = device.waitForRunCleanup();
66179
+ const env = DataManager.getSettings('env');
66180
+ const deviceType = device.getCurrentDeviceType();
66181
+ const requiresSigningCooldown = method.name.includes('Sign') &&
66182
+ (deviceType === hdShared.EDeviceType.Pro2 || deviceType === hdShared.EDeviceType.Neo) &&
66183
+ (DataManager.isBrowserWebUsb(env) || DataManager.isDesktopWebUsb(env) || env === 'node-usb');
66184
+ return requiresSigningCooldown
66185
+ ? cleanupPromise.then(() => wait(PRO2_USB_SIGNING_COOLDOWN_MS)).then(() => undefined)
66186
+ : cleanupPromise;
66187
+ }
65960
66188
  const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, void 0, function* () {
65961
- var _d, _e, _f, _g, _h, _j, _k;
66189
+ var _d, _e, _f, _g, _h, _j;
65962
66190
  let messageResponse;
65963
66191
  const { requestQueue, getPrePendingCallPromise, removePrePendingCallPromise } = context;
65964
66192
  updateMethodRequestContext(method, { status: 'running' });
@@ -65972,21 +66200,42 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
65972
66200
  Log.debug('passphrase state change, clear device cache');
65973
66201
  DevicePool.clearDeviceCache(method.payload.connectId);
65974
66202
  }
65975
- if (method.connectId) {
65976
- yield context.waitForCallbackTasks(method.connectId);
65977
- }
65978
- yield waitForPendingPromise((_d = method.connectId) !== null && _d !== void 0 ? _d : '', getPrePendingCallPromise, removePrePendingCallPromise);
65979
66203
  const task = requestQueue.createTask(method);
65980
66204
  let preWarmCallbackTask;
65981
- if (method.isPreWarmSignal && method.connectId) {
65982
- preWarmCallbackTask = hdShared.createDeferred();
65983
- context.registerCallbackTask(method.connectId, preWarmCallbackTask);
65984
- }
65985
66205
  let device;
65986
66206
  try {
65987
- const connectId = (_e = method.connectId) !== null && _e !== void 0 ? _e : '';
66207
+ const connectId = (_d = method.connectId) !== null && _d !== void 0 ? _d : '';
66208
+ if (connectId) {
66209
+ yield requestQueue.waitForTask(task, () => context.waitForCallbackTasks(connectId));
66210
+ }
66211
+ yield requestQueue.waitForTask(task, () => {
66212
+ var _a;
66213
+ return waitForPendingPromise((_a = method.connectId) !== null && _a !== void 0 ? _a : '', getPrePendingCallPromise, removePrePendingCallPromise);
66214
+ });
66215
+ if (method.isPreWarmSignal && method.connectId) {
66216
+ preWarmCallbackTask = hdShared.createDeferred();
66217
+ context.registerCallbackTask(method.connectId, preWarmCallbackTask);
66218
+ }
65988
66219
  const pollingId = pollingManager.start(connectId);
65989
- device = yield ensureConnected(context, method, connectId, pollingId, (_f = task.abortController) === null || _f === void 0 ? void 0 : _f.signal);
66220
+ const env = DataManager.getSettings('env');
66221
+ const connect = () => ensureConnected(context, method, connectId, pollingId, method.abortSignal);
66222
+ if (DataManager.isBrowserWebUsb(env) || DataManager.isDesktopWebUsb(env)) {
66223
+ const connectPromise = context.methodSynchronize(() => __awaiter(void 0, void 0, void 0, function* () {
66224
+ var _k;
66225
+ if ((_k = method.abortSignal) === null || _k === void 0 ? void 0 : _k.aborted) {
66226
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled);
66227
+ }
66228
+ return connect();
66229
+ }), 'webusb-discovery');
66230
+ connectPromise.catch(() => undefined);
66231
+ device = yield requestQueue.waitForTask(task, () => connectPromise);
66232
+ }
66233
+ else {
66234
+ device = yield connect();
66235
+ }
66236
+ if ((_e = method.abortSignal) === null || _e === void 0 ? void 0 : _e.aborted) {
66237
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled);
66238
+ }
65990
66239
  }
65991
66240
  catch (e) {
65992
66241
  preWarmCallbackTask === null || preWarmCallbackTask === void 0 ? void 0 : preWarmCallbackTask.resolve();
@@ -66001,7 +66250,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66001
66250
  requestQueue.releaseTask(method.responseID);
66002
66251
  return createResponseMessage(method.responseID, false, { error: e });
66003
66252
  }
66004
- if ((_g = method.payload) === null || _g === void 0 ? void 0 : _g.onlyConnectBleDevice) {
66253
+ if ((_f = method.payload) === null || _f === void 0 ? void 0 : _f.onlyConnectBleDevice) {
66005
66254
  preWarmCallbackTask === null || preWarmCallbackTask === void 0 ? void 0 : preWarmCallbackTask.resolve();
66006
66255
  Log.debug('Call API - only connect ble device: ', device === null || device === void 0 ? void 0 : device.mainId);
66007
66256
  completeMethodRequestContext(method);
@@ -66009,11 +66258,11 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66009
66258
  return createResponseMessage(method.responseID, true, null);
66010
66259
  }
66011
66260
  Log.debug('Call API - setDevice: ', device.mainId);
66012
- (_h = method.setDevice) === null || _h === void 0 ? void 0 : _h.call(method, device);
66261
+ (_g = method.setDevice) === null || _g === void 0 ? void 0 : _g.call(method, device);
66013
66262
  method.context = context;
66014
66263
  updateMethodRequestContext(method, {
66015
66264
  deviceInstanceId: device.instanceId,
66016
- commandsInstanceId: (_j = device.commands) === null || _j === void 0 ? void 0 : _j.instanceId,
66265
+ commandsInstanceId: (_h = device.commands) === null || _h === void 0 ? void 0 : _h.instanceId,
66017
66266
  });
66018
66267
  const activeRequests = getActiveRequestsByDeviceInstance(device.instanceId);
66019
66268
  if (activeRequests.length > 0) {
@@ -66039,10 +66288,14 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66039
66288
  device.beginProtocolV2UiInteraction();
66040
66289
  device.on(DEVICE.SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE, onSelectDeviceForSwitchFirmwareWebDeviceHandler);
66041
66290
  try {
66042
- if (method.connectId) {
66043
- yield context.waitForCallbackTasks(method.connectId, preWarmCallbackTask);
66291
+ const { connectId } = method;
66292
+ if (connectId) {
66293
+ yield requestQueue.waitForTask(task, () => context.waitForCallbackTasks(connectId, preWarmCallbackTask));
66044
66294
  }
66045
- yield waitForPendingPromise((_k = method.connectId) !== null && _k !== void 0 ? _k : '', getPrePendingCallPromise, removePrePendingCallPromise);
66295
+ yield requestQueue.waitForTask(task, () => {
66296
+ var _a;
66297
+ return waitForPendingPromise((_a = method.connectId) !== null && _a !== void 0 ? _a : '', getPrePendingCallPromise, removePrePendingCallPromise);
66298
+ });
66046
66299
  const inner = () => __awaiter(void 0, void 0, void 0, function* () {
66047
66300
  var _l, _m;
66048
66301
  method.assertProtocolSupported(device.getProtocol(), device.getCurrentFirmwareType());
@@ -66169,6 +66422,9 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66169
66422
  }),
66170
66423
  });
66171
66424
  messageResponse = createResponseMessage(method.responseID, true, response);
66425
+ if (method.connectId) {
66426
+ context.setPrePendingCallPromise(method.connectId, getPostCallPendingPromise(method, device));
66427
+ }
66172
66428
  requestQueue.resolveRequest(method.responseID, messageResponse);
66173
66429
  completeMethodRequestContext(method);
66174
66430
  }
@@ -66179,6 +66435,9 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66179
66435
  }
66180
66436
  Log.debug(`Call API - Inner Method Run Error`, error);
66181
66437
  messageResponse = createResponseMessage(method.responseID, false, { error });
66438
+ if (method.connectId) {
66439
+ context.setPrePendingCallPromise(method.connectId, getPostCallPendingPromise(method, device));
66440
+ }
66182
66441
  requestQueue.resolveRequest(method.responseID, messageResponse);
66183
66442
  completeMethodRequestContext(method, error);
66184
66443
  if (error instanceof hdShared.HardwareError &&
@@ -66197,6 +66456,9 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66197
66456
  });
66198
66457
  Log.debug('Call API - Device Run: ', device.mainId);
66199
66458
  const runOptions = Object.assign({ keepSession: method.payload.keepSession, skipInitialize: canSkipInitialize(method, device) }, parseInitOptions(method));
66459
+ if ((_j = method.abortSignal) === null || _j === void 0 ? void 0 : _j.aborted) {
66460
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled);
66461
+ }
66200
66462
  const deviceRun = () => device.run(inner, runOptions);
66201
66463
  task.callPromise = hdShared.createDeferred(deviceRun);
66202
66464
  try {
@@ -66215,6 +66477,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
66215
66477
  requestQueue.rejectRequest(method.responseID, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodError, error.message));
66216
66478
  Log.debug('Call API - Run Error: ', error);
66217
66479
  completeMethodRequestContext(method, error);
66480
+ return messageResponse;
66218
66481
  }
66219
66482
  finally {
66220
66483
  preWarmCallbackTask === null || preWarmCallbackTask === void 0 ? void 0 : preWarmCallbackTask.resolve();
@@ -66364,11 +66627,15 @@ function isRetryableBleProtocolV2ProbeError(method, error) {
66364
66627
  message.includes('did not respond to expected protocol'));
66365
66628
  }
66366
66629
  function isRetryableBleConnectionError(method, error) {
66367
- var _a;
66630
+ var _a, _b;
66368
66631
  if ((_a = method.device) === null || _a === void 0 ? void 0 : _a.wasInterruptedByUser()) {
66369
66632
  return false;
66370
66633
  }
66371
66634
  const typedError = error;
66635
+ if ((typedError === null || typedError === void 0 ? void 0 : typedError.errorCode) === hdShared.HardwareErrorCode.BleTimeoutError &&
66636
+ ((_b = typedError.params) === null || _b === void 0 ? void 0 : _b.acquireDeadlineExceeded) === true) {
66637
+ return false;
66638
+ }
66372
66639
  return ((typedError === null || typedError === void 0 ? void 0 : typedError.errorCode) === hdShared.HardwareErrorCode.BleTimeoutError ||
66373
66640
  (typedError === null || typedError === void 0 ? void 0 : typedError.errorCode) === hdShared.HardwareErrorCode.BleConnectedError ||
66374
66641
  isRetryableBleProtocolV2ProbeError(method, error) ||
@@ -66381,10 +66648,11 @@ function isMissingDetectedProtocolV2Error(method, error) {
66381
66648
  typeof typedError.message === 'string' &&
66382
66649
  typedError.message.includes('Device protocol has not been detected'));
66383
66650
  }
66384
- function isProtocolV2PeerRemovedPairingError(method, error) {
66385
- return (method.payload.connectProtocol === 'V2' &&
66386
- (error === null || error === void 0 ? void 0 : error.errorCode) ===
66387
- hdShared.HardwareErrorCode.BlePeerRemovedPairingInformation);
66651
+ function isTerminalBleStaleBondError(error) {
66652
+ return hdShared.isBleStaleBondHardwareError(error);
66653
+ }
66654
+ function isDeviceIdentityMismatchError(error) {
66655
+ return ((error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.DeviceCheckDeviceIdError);
66388
66656
  }
66389
66657
  const BLE_ACQUIRE_DEADLINE_MS = 60 * 1000;
66390
66658
  function raceBleAcquire(acquirePromise, abortSignal) {
@@ -66399,7 +66667,7 @@ function raceBleAcquire(acquirePromise, abortSignal) {
66399
66667
  fn();
66400
66668
  };
66401
66669
  const onAbort = () => settle(() => reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled)));
66402
- const deadline = setTimeout(() => settle(() => reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE acquire exceeded ${BLE_ACQUIRE_DEADLINE_MS}ms deadline`))), BLE_ACQUIRE_DEADLINE_MS);
66670
+ const deadline = setTimeout(() => settle(() => reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE acquire exceeded ${BLE_ACQUIRE_DEADLINE_MS}ms deadline`, { acquireDeadlineExceeded: true }))), BLE_ACQUIRE_DEADLINE_MS);
66403
66671
  acquirePromise.then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
66404
66672
  if (abortSignal) {
66405
66673
  if (abortSignal.aborted) {
@@ -66414,7 +66682,7 @@ function connectDeviceForBle(method, device, abortSignal, retryCount = 0) {
66414
66682
  var _a;
66415
66683
  return __awaiter(this, void 0, void 0, function* () {
66416
66684
  try {
66417
- if (device.wasInterruptedByUser()) {
66685
+ if ((abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) || device.wasInterruptedByUser()) {
66418
66686
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
66419
66687
  }
66420
66688
  if (method.payload.forceProtocolDetection && device.hasDeviceAcquire()) {
@@ -66470,6 +66738,9 @@ function connectDeviceForBle(method, device, abortSignal, retryCount = 0) {
66470
66738
  }
66471
66739
  }
66472
66740
  catch (err) {
66741
+ if ((abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) || device.wasInterruptedByUser()) {
66742
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
66743
+ }
66473
66744
  const requiresColdReconnect = isMissingDetectedProtocolV2Error(method, err);
66474
66745
  if ((hdShared.ERROR_CODES_REQUIRE_DISCONNECT.includes(err.errorCode) || requiresColdReconnect) &&
66475
66746
  device.mainId &&
@@ -66502,6 +66773,7 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66502
66773
  const POLL_INTERVAL_TIME = (method.payload && method.payload.pollIntervalTime) || 1000;
66503
66774
  const TIME_OUT = (method.payload && method.payload.timeout) || 10000;
66504
66775
  let timer = null;
66776
+ let lastInitializeError;
66505
66777
  Log.debug(`EnsureConnected function start, MAX_RETRY_COUNT=${MAX_RETRY_COUNT}, POLL_INTERVAL_TIME=${POLL_INTERVAL_TIME} `);
66506
66778
  const poll = (time = POLL_INTERVAL_TIME) => __awaiter(void 0, void 0, void 0, function* () {
66507
66779
  return new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () {
@@ -66534,8 +66806,10 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66534
66806
  Log.debug('EnsureConnected function try count: ', tryCount, ' poll interval time: ', time);
66535
66807
  try {
66536
66808
  yield initDeviceList(method);
66809
+ lastInitializeError = undefined;
66537
66810
  }
66538
66811
  catch (error) {
66812
+ lastInitializeError = error;
66539
66813
  Log.debug('device list error: ', error);
66540
66814
  if ([
66541
66815
  hdShared.HardwareErrorCode.BridgeNotInstalled,
@@ -66548,6 +66822,7 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66548
66822
  }
66549
66823
  if (error.errorCode === hdShared.HardwareErrorCode.TransportNotConfigured) {
66550
66824
  yield TransportManager.configure();
66825
+ lastInitializeError = undefined;
66551
66826
  }
66552
66827
  }
66553
66828
  if (abort()) {
@@ -66606,6 +66881,7 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66606
66881
  hdShared.HardwareErrorCode.BleDeviceBondedCanceled,
66607
66882
  hdShared.HardwareErrorCode.BleCharacteristicNotifyError,
66608
66883
  hdShared.HardwareErrorCode.BleTimeoutError,
66884
+ hdShared.HardwareErrorCode.PollingTimeout,
66609
66885
  hdShared.HardwareErrorCode.BleWriteCharacteristicError,
66610
66886
  hdShared.HardwareErrorCode.BleAlreadyConnected,
66611
66887
  hdShared.HardwareErrorCode.FirmwareUpdateLimitOneDevice,
@@ -66616,7 +66892,10 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66616
66892
  hdShared.HardwareErrorCode.DeviceInterruptedFromUser,
66617
66893
  hdShared.HardwareErrorCode.CallQueueActionCancelled,
66618
66894
  ].includes(error.errorCode) ||
66619
- isProtocolV2PeerRemovedPairingError(method, error)) {
66895
+ (env === 'react-native' &&
66896
+ [hdShared.HardwareErrorCode.BleDeviceDisconnected, hdShared.HardwareErrorCode.PollingTimeout].includes(error.errorCode)) ||
66897
+ isTerminalBleStaleBondError(error) ||
66898
+ isDeviceIdentityMismatchError(error)) {
66620
66899
  reject(error);
66621
66900
  return;
66622
66901
  }
@@ -66626,13 +66905,16 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66626
66905
  clearTimeout(timer);
66627
66906
  }
66628
66907
  Log.debug('EnsureConnected get to max try count, will return: ', tryCount);
66629
- if (DataManager.isBrowserWebUsb(env) && !((_u = method.payload) === null || _u === void 0 ? void 0 : _u.skipWebDevicePrompt)) {
66908
+ const preserveWebUsbInitError = DataManager.isBrowserWebUsb(env) || DataManager.isDesktopWebUsb(env);
66909
+ const needsPermissionPrompt = DataManager.isBrowserWebUsb(env) && !((_u = method.payload) === null || _u === void 0 ? void 0 : _u.skipWebDevicePrompt);
66910
+ const fallbackError = needsPermissionPrompt
66911
+ ? hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.WebDeviceNotFoundOrNeedsPermission)
66912
+ : hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound);
66913
+ const errorToReject = preserveWebUsbInitError && lastInitializeError ? lastInitializeError : fallbackError;
66914
+ if (needsPermissionPrompt && errorToReject === fallbackError) {
66630
66915
  postMessage(createUiMessage(UI_REQUEST.WEB_DEVICE_PROMPT_ACCESS_PERMISSION));
66631
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.WebDeviceNotFoundOrNeedsPermission));
66632
- }
66633
- else {
66634
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound));
66635
66916
  }
66917
+ reject(errorToReject);
66636
66918
  return;
66637
66919
  }
66638
66920
  if (abort()) {
@@ -66644,14 +66926,14 @@ const ensureConnected = (_context, method, connectId, pollingId, abortSignal) =>
66644
66926
  return poll();
66645
66927
  });
66646
66928
  const cancel = (context, connectId) => {
66647
- var _a, _b, _c;
66929
+ var _a, _b;
66648
66930
  const { requestQueue, setPrePendingCallPromise } = context;
66649
66931
  if (connectId) {
66650
66932
  try {
66651
66933
  requestQueue.cancelCallbackTasks(connectId);
66652
- const requestIds = requestQueue.getRequestTasksId();
66934
+ const requestIds = requestQueue.getRequestTasksIdByConnectId(connectId);
66653
66935
  Log.debug(`Cancel Api connect requestQueues: length:${requestIds.length} requestIds:${requestIds.join(',')}`);
66654
- requestQueue.abortAllRequests();
66936
+ requestQueue.abortRequestsByConnectId(connectId);
66655
66937
  const canceledDevices = [];
66656
66938
  const interruptDevice = (device, deviceConnectId) => {
66657
66939
  if (!device || canceledDevices.includes(device)) {
@@ -66664,7 +66946,7 @@ const cancel = (context, connectId) => {
66664
66946
  const task = requestQueue.getTask(requestId);
66665
66947
  Log.debug('Cancel Api connect task: ', task);
66666
66948
  if (task) {
66667
- interruptDevice((_a = task.method) === null || _a === void 0 ? void 0 : _a.device, (_b = task.method.connectId) !== null && _b !== void 0 ? _b : connectId);
66949
+ interruptDevice((_a = task.method) === null || _a === void 0 ? void 0 : _a.device, connectId);
66668
66950
  interruptDevice(deviceCacheMap.get(connectId), connectId);
66669
66951
  requestQueue.rejectRequest(requestId, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled));
66670
66952
  }
@@ -66678,9 +66960,9 @@ const cancel = (context, connectId) => {
66678
66960
  }
66679
66961
  else {
66680
66962
  const env = DataManager.getSettings('env');
66963
+ requestQueue.abortAllRequests();
66681
66964
  if (DataManager.isBleConnect(env)) {
66682
66965
  Log.debug('Cancel Api all _deviceList: ');
66683
- requestQueue.abortAllRequests();
66684
66966
  const canceledDevices = [];
66685
66967
  const interruptDevice = (device) => {
66686
66968
  if (!device || canceledDevices.includes(device)) {
@@ -66693,7 +66975,7 @@ const cancel = (context, connectId) => {
66693
66975
  const task = requestQueue.getTask(requestId);
66694
66976
  Log.debug('Cancel Api connect task: ', task);
66695
66977
  if (task) {
66696
- interruptDevice((_c = task.method) === null || _c === void 0 ? void 0 : _c.device);
66978
+ interruptDevice((_b = task.method) === null || _b === void 0 ? void 0 : _b.device);
66697
66979
  if (task.method.connectId) {
66698
66980
  interruptDevice(deviceCacheMap.get(task.method.connectId));
66699
66981
  pollingManager.stop(task.method.connectId);
@@ -66716,8 +66998,10 @@ const cancel = (context, connectId) => {
66716
66998
  });
66717
66999
  }
66718
67000
  }
66719
- cleanup();
66720
- closePopup();
67001
+ cleanup(connectId);
67002
+ if (!connectId || _uiPromises.length === 0) {
67003
+ closePopup();
67004
+ }
66721
67005
  };
66722
67006
  const checkPassphraseEnableState = (method, features) => {
66723
67007
  if (!method.useDevicePassphraseState)
@@ -66747,9 +67031,13 @@ const shouldCheckPassphraseState = (method, device) => {
66747
67031
  }
66748
67032
  return device.hasUsePassphrase();
66749
67033
  };
66750
- const cleanup = () => {
66751
- const pendingUiPromises = _uiPromises;
66752
- _uiPromises = [];
67034
+ const cleanup = (connectId) => {
67035
+ const pendingUiPromises = connectId
67036
+ ? _uiPromises.filter(uiPromise => { var _a, _b; return ((_a = uiPromise.data) === null || _a === void 0 ? void 0 : _a.mainId) === connectId || ((_b = uiPromise.data) === null || _b === void 0 ? void 0 : _b.getConnectId()) === connectId; })
67037
+ : _uiPromises;
67038
+ _uiPromises = connectId
67039
+ ? _uiPromises.filter(uiPromise => !pendingUiPromises.includes(uiPromise))
67040
+ : [];
66753
67041
  rejectUiPromises(pendingUiPromises, hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ActionCancelled, 'UI request was cancelled'));
66754
67042
  };
66755
67043
  const removeDeviceListener = (device) => {
@@ -66905,7 +67193,14 @@ class Core extends events.exports {
66905
67193
  this.prePendingCallPromises.delete(connectId);
66906
67194
  return;
66907
67195
  }
66908
- this.prePendingCallPromises.set(connectId, promise);
67196
+ const previous = this.prePendingCallPromises.get(connectId);
67197
+ const cleanupPromise = previous && previous !== promise
67198
+ ? Promise.all([previous, promise]).then(() => undefined)
67199
+ : promise;
67200
+ this.prePendingCallPromises.set(connectId, cleanupPromise);
67201
+ cleanupPromise.catch(error => {
67202
+ Log.warn('Device cancellation cleanup failed', { errorCode: error === null || error === void 0 ? void 0 : error.errorCode });
67203
+ });
66909
67204
  },
66910
67205
  removePrePendingCallPromise: (connectId, promise) => {
66911
67206
  if (this.prePendingCallPromises.get(connectId) === promise) {