@onekeyfe/hd-core 1.1.26-alpha.12 → 1.1.26-alpha.30

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 (145) hide show
  1. package/__tests__/protocol-v2.test.ts +912 -0
  2. package/dist/api/DirList.d.ts +10 -0
  3. package/dist/api/DirList.d.ts.map +1 -0
  4. package/dist/api/DirMake.d.ts +9 -0
  5. package/dist/api/DirMake.d.ts.map +1 -0
  6. package/dist/api/DirRemove.d.ts +9 -0
  7. package/dist/api/DirRemove.d.ts.map +1 -0
  8. package/dist/api/FileDelete.d.ts +9 -0
  9. package/dist/api/FileDelete.d.ts.map +1 -0
  10. package/dist/api/FileRead.d.ts +19 -0
  11. package/dist/api/FileRead.d.ts.map +1 -0
  12. package/dist/api/FileWrite.d.ts +23 -0
  13. package/dist/api/FileWrite.d.ts.map +1 -0
  14. package/dist/api/FirmwareUpdateV3.d.ts +1 -0
  15. package/dist/api/FirmwareUpdateV3.d.ts.map +1 -1
  16. package/dist/api/FirmwareUpdateV4.d.ts +32 -0
  17. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -0
  18. package/dist/api/GetOnekeyFeatures.d.ts.map +1 -1
  19. package/dist/api/PathInfo.d.ts +9 -0
  20. package/dist/api/PathInfo.d.ts.map +1 -0
  21. package/dist/api/SearchDevices.d.ts +2 -1
  22. package/dist/api/SearchDevices.d.ts.map +1 -1
  23. package/dist/api/device/DeviceRebootToBoardloader.d.ts +1 -1
  24. package/dist/api/device/DeviceRebootToBoardloader.d.ts.map +1 -1
  25. package/dist/api/device/DeviceRebootToBootloader.d.ts.map +1 -1
  26. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts +10 -2
  27. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts.map +1 -1
  28. package/dist/api/index.d.ts +26 -0
  29. package/dist/api/index.d.ts.map +1 -1
  30. package/dist/api/protocol-v2/DevFirmwareUpdate.d.ts +7 -0
  31. package/dist/api/protocol-v2/DevFirmwareUpdate.d.ts.map +1 -0
  32. package/dist/api/protocol-v2/DevGetDeviceInfo.d.ts +7 -0
  33. package/dist/api/protocol-v2/DevGetDeviceInfo.d.ts.map +1 -0
  34. package/dist/api/protocol-v2/DevGetFirmwareUpdateStatus.d.ts +6 -0
  35. package/dist/api/protocol-v2/DevGetFirmwareUpdateStatus.d.ts.map +1 -0
  36. package/dist/api/protocol-v2/DevGetOnboardingStatus.d.ts +6 -0
  37. package/dist/api/protocol-v2/DevGetOnboardingStatus.d.ts.map +1 -0
  38. package/dist/api/protocol-v2/DevReboot.d.ts +7 -0
  39. package/dist/api/protocol-v2/DevReboot.d.ts.map +1 -0
  40. package/dist/api/protocol-v2/FactoryDeviceInfoSettings.d.ts +7 -0
  41. package/dist/api/protocol-v2/FactoryDeviceInfoSettings.d.ts.map +1 -0
  42. package/dist/api/protocol-v2/FactoryGetDeviceInfo.d.ts +6 -0
  43. package/dist/api/protocol-v2/FactoryGetDeviceInfo.d.ts.map +1 -0
  44. package/dist/api/protocol-v2/FilesystemFixPermission.d.ts +6 -0
  45. package/dist/api/protocol-v2/FilesystemFixPermission.d.ts.map +1 -0
  46. package/dist/api/protocol-v2/FilesystemFormat.d.ts +6 -0
  47. package/dist/api/protocol-v2/FilesystemFormat.d.ts.map +1 -0
  48. package/dist/api/protocol-v2/GetProtoVersion.d.ts +6 -0
  49. package/dist/api/protocol-v2/GetProtoVersion.d.ts.map +1 -0
  50. package/dist/api/protocol-v2/Ping.d.ts +8 -0
  51. package/dist/api/protocol-v2/Ping.d.ts.map +1 -0
  52. package/dist/api/protocol-v2/helpers.d.ts +49 -0
  53. package/dist/api/protocol-v2/helpers.d.ts.map +1 -0
  54. package/dist/core/index.d.ts.map +1 -1
  55. package/dist/data-manager/DataManager.d.ts +4 -2
  56. package/dist/data-manager/DataManager.d.ts.map +1 -1
  57. package/dist/data-manager/TransportManager.d.ts +2 -1
  58. package/dist/data-manager/TransportManager.d.ts.map +1 -1
  59. package/dist/device/Device.d.ts +5 -3
  60. package/dist/device/Device.d.ts.map +1 -1
  61. package/dist/device/DeviceCommands.d.ts +8 -8
  62. package/dist/device/DeviceCommands.d.ts.map +1 -1
  63. package/dist/device/DeviceConnector.d.ts +2 -1
  64. package/dist/device/DeviceConnector.d.ts.map +1 -1
  65. package/dist/events/ui-request.d.ts +8 -0
  66. package/dist/events/ui-request.d.ts.map +1 -1
  67. package/dist/index.d.ts +187 -20
  68. package/dist/index.js +2664 -182
  69. package/dist/inject.d.ts.map +1 -1
  70. package/dist/protocols/protocol-v2/features.d.ts +56 -0
  71. package/dist/protocols/protocol-v2/features.d.ts.map +1 -0
  72. package/dist/protocols/protocol-v2/firmware.d.ts +12 -0
  73. package/dist/protocols/protocol-v2/firmware.d.ts.map +1 -0
  74. package/dist/protocols/protocol-v2/index.d.ts +3 -0
  75. package/dist/protocols/protocol-v2/index.d.ts.map +1 -0
  76. package/dist/types/api/export.d.ts +1 -1
  77. package/dist/types/api/export.d.ts.map +1 -1
  78. package/dist/types/api/firmwareUpdate.d.ts +7 -0
  79. package/dist/types/api/firmwareUpdate.d.ts.map +1 -1
  80. package/dist/types/api/index.d.ts +28 -1
  81. package/dist/types/api/index.d.ts.map +1 -1
  82. package/dist/types/api/protocolV2.d.ts +123 -0
  83. package/dist/types/api/protocolV2.d.ts.map +1 -0
  84. package/dist/types/api/searchDevices.d.ts +2 -2
  85. package/dist/types/api/searchDevices.d.ts.map +1 -1
  86. package/dist/types/device.d.ts +1 -1
  87. package/dist/types/device.d.ts.map +1 -1
  88. package/dist/types/params.d.ts +2 -0
  89. package/dist/types/params.d.ts.map +1 -1
  90. package/dist/types/settings.d.ts +1 -1
  91. package/dist/types/settings.d.ts.map +1 -1
  92. package/dist/utils/deviceInfoUtils.d.ts.map +1 -1
  93. package/dist/utils/patch.d.ts +1 -1
  94. package/dist/utils/patch.d.ts.map +1 -1
  95. package/dist/utils/versionUtils.d.ts +1 -1
  96. package/package.json +4 -4
  97. package/src/api/DirList.ts +25 -0
  98. package/src/api/DirMake.ts +20 -0
  99. package/src/api/DirRemove.ts +20 -0
  100. package/src/api/FileDelete.ts +20 -0
  101. package/src/api/FileRead.ts +161 -0
  102. package/src/api/FileWrite.ts +191 -0
  103. package/src/api/FirmwareUpdateV3.ts +21 -4
  104. package/src/api/FirmwareUpdateV4.ts +810 -0
  105. package/src/api/GetOnekeyFeatures.ts +75 -3
  106. package/src/api/PathInfo.ts +24 -0
  107. package/src/api/SearchDevices.ts +7 -2
  108. package/src/api/device/DeviceRebootToBoardloader.ts +10 -1
  109. package/src/api/device/DeviceRebootToBootloader.ts +10 -1
  110. package/src/api/firmware/FirmwareUpdateBaseMethod.ts +27 -4
  111. package/src/api/index.ts +28 -0
  112. package/src/api/protocol-v2/DevFirmwareUpdate.ts +33 -0
  113. package/src/api/protocol-v2/DevGetDeviceInfo.ts +35 -0
  114. package/src/api/protocol-v2/DevGetFirmwareUpdateStatus.ts +18 -0
  115. package/src/api/protocol-v2/DevGetOnboardingStatus.ts +18 -0
  116. package/src/api/protocol-v2/DevReboot.ts +22 -0
  117. package/src/api/protocol-v2/FactoryDeviceInfoSettings.ts +27 -0
  118. package/src/api/protocol-v2/FactoryGetDeviceInfo.ts +18 -0
  119. package/src/api/protocol-v2/FilesystemFixPermission.ts +14 -0
  120. package/src/api/protocol-v2/FilesystemFormat.ts +14 -0
  121. package/src/api/protocol-v2/GetProtoVersion.ts +14 -0
  122. package/src/api/protocol-v2/Ping.ts +16 -0
  123. package/src/api/protocol-v2/helpers.ts +140 -0
  124. package/src/core/index.ts +19 -2
  125. package/src/data/messages/messages-pro2.json +733 -0
  126. package/src/data-manager/DataManager.ts +6 -2
  127. package/src/data-manager/TransportManager.ts +29 -3
  128. package/src/device/Device.ts +66 -8
  129. package/src/device/DeviceCommands.ts +156 -26
  130. package/src/device/DeviceConnector.ts +29 -4
  131. package/src/device/DevicePool.ts +1 -1
  132. package/src/events/ui-request.ts +8 -0
  133. package/src/inject.ts +43 -1
  134. package/src/protocols/protocol-v2/features.ts +259 -0
  135. package/src/protocols/protocol-v2/firmware.ts +26 -0
  136. package/src/protocols/protocol-v2/index.ts +2 -0
  137. package/src/types/api/export.ts +1 -0
  138. package/src/types/api/firmwareUpdate.ts +12 -0
  139. package/src/types/api/index.ts +63 -1
  140. package/src/types/api/protocolV2.ts +221 -0
  141. package/src/types/api/searchDevices.ts +2 -2
  142. package/src/types/device.ts +3 -1
  143. package/src/types/params.ts +7 -0
  144. package/src/types/settings.ts +1 -1
  145. package/src/utils/deviceInfoUtils.ts +9 -5
package/dist/index.js CHANGED
@@ -119,7 +119,7 @@ const inject = ({ call, cancel, dispose, eventEmitter, init, updateSettings, swi
119
119
  };
120
120
  const createCoreApi = (call) => ({
121
121
  getLogs: () => call({ method: 'getLogs' }),
122
- searchDevices: () => call({ method: 'searchDevices' }),
122
+ searchDevices: params => call(Object.assign(Object.assign({}, params), { method: 'searchDevices' })),
123
123
  getFeatures: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getFeatures' })),
124
124
  getOnekeyFeatures: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getOnekeyFeatures' })),
125
125
  checkFirmwareRelease: connectId => call({ connectId, method: 'checkFirmwareRelease' }),
@@ -136,6 +136,31 @@ const createCoreApi = (call) => ({
136
136
  deviceFlags: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceFlags' })),
137
137
  deviceRebootToBoardloader: connectId => call({ connectId, method: 'deviceRebootToBoardloader' }),
138
138
  deviceRebootToBootloader: connectId => call({ connectId, method: 'deviceRebootToBootloader' }),
139
+ getProtoVersion: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getProtoVersion' })),
140
+ ping: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'ping' })),
141
+ devReboot: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devReboot' })),
142
+ devGetDeviceInfo: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devGetDeviceInfo' })),
143
+ devGetOnboardingStatus: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devGetOnboardingStatus' })),
144
+ devFirmwareUpdate: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devFirmwareUpdate' })),
145
+ devGetFirmwareUpdateStatus: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'devGetFirmwareUpdateStatus' })),
146
+ factoryDeviceInfoSettings: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'factoryDeviceInfoSettings' })),
147
+ factoryGetDeviceInfo: connectId => call({ connectId, method: 'factoryGetDeviceInfo' }),
148
+ filesystemFixPermission: connectId => call({ connectId, method: 'filesystemFixPermission' }),
149
+ fileRead: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'fileRead' })),
150
+ fileWrite: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'fileWrite' })),
151
+ fileDelete: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'fileDelete' })),
152
+ dirList: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'dirList' })),
153
+ dirMake: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'dirMake' })),
154
+ dirRemove: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'dirRemove' })),
155
+ pathInfo: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'pathInfo' })),
156
+ filesystemFileRead: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemFileRead' })),
157
+ filesystemFileWrite: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemFileWrite' })),
158
+ filesystemFileDelete: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemFileDelete' })),
159
+ filesystemDirList: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemDirList' })),
160
+ filesystemDirMake: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemDirMake' })),
161
+ filesystemDirRemove: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemDirRemove' })),
162
+ filesystemPathInfoQuery: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'filesystemPathInfoQuery' })),
163
+ filesystemFormat: connectId => call({ connectId, method: 'filesystemFormat' }),
139
164
  deviceRecovery: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceRecovery' })),
140
165
  deviceReset: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceReset' })),
141
166
  deviceSettings: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceSettings' })),
@@ -196,6 +221,7 @@ const createCoreApi = (call) => ({
196
221
  firmwareUpdate: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdate' })),
197
222
  firmwareUpdateV2: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdateV2' })),
198
223
  firmwareUpdateV3: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdateV3' })),
224
+ firmwareUpdateV4: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'firmwareUpdateV4' })),
199
225
  promptWebDeviceAccess: params => call(Object.assign(Object.assign({}, params), { method: 'promptWebDeviceAccess' })),
200
226
  tronGetAddress: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tronGetAddress' })),
201
227
  tronSignMessage: (connectId, deviceId, params) => call(Object.assign(Object.assign({}, params), { connectId, deviceId, method: 'tronSignMessage' })),
@@ -788,7 +814,7 @@ const createLogMessage = (type, payload) => ({
788
814
 
789
815
  const MAX_ENTRIES = 500;
790
816
  let postMessage$1;
791
- class Log$g {
817
+ class Log$h {
792
818
  constructor(prefix, enabled) {
793
819
  this.prefix = prefix;
794
820
  this.enabled = enabled;
@@ -840,7 +866,7 @@ class Log$g {
840
866
  }
841
867
  const _logs = {};
842
868
  const initLog = (prefix, enabled) => {
843
- const instance = new Log$g(prefix, !!enabled);
869
+ const instance = new Log$h(prefix, !!enabled);
844
870
  _logs[prefix] = instance;
845
871
  return instance;
846
872
  };
@@ -1038,7 +1064,7 @@ function patchFeatures(response) {
1038
1064
  return response;
1039
1065
  }
1040
1066
 
1041
- const Log$f = getLogger(exports.LoggerNames.Core);
1067
+ const Log$g = getLogger(exports.LoggerNames.Core);
1042
1068
  let globalInstanceCounter = 0;
1043
1069
  let sdkInstanceCounter = 0;
1044
1070
  function generateSdkInstanceId() {
@@ -1098,7 +1124,7 @@ function completeRequestContext(responseID, error) {
1098
1124
  context.status = error ? 'error' : 'success';
1099
1125
  if (error) {
1100
1126
  context.error = error.message;
1101
- Log$f.error(`[RequestContext] [completeRequestContext] Error: ${formatRequestContext(context)}`);
1127
+ Log$g.error(`[RequestContext] [completeRequestContext] Error: ${formatRequestContext(context)}`);
1102
1128
  }
1103
1129
  globalActiveRequests.delete(responseID);
1104
1130
  if (context.sdkInstanceId) {
@@ -1165,6 +1191,7 @@ const DeviceTypeToModels = {
1165
1191
  [hdShared.EDeviceType.Mini]: ['model_mini'],
1166
1192
  [hdShared.EDeviceType.Touch]: ['model_touch'],
1167
1193
  [hdShared.EDeviceType.Pro]: ['model_touch'],
1194
+ [hdShared.EDeviceType.Pro2]: [],
1168
1195
  [hdShared.EDeviceType.Unknown]: [],
1169
1196
  };
1170
1197
 
@@ -1185,6 +1212,9 @@ const getDeviceType = (features) => {
1185
1212
  return hdShared.EDeviceType.Touch;
1186
1213
  case 'PRO':
1187
1214
  return hdShared.EDeviceType.Pro;
1215
+ case 'PRO2':
1216
+ case 'pro2':
1217
+ return hdShared.EDeviceType.Pro2;
1188
1218
  case 'PURE':
1189
1219
  return hdShared.EDeviceType.ClassicPure;
1190
1220
  default:
@@ -1216,15 +1246,17 @@ const getDeviceType = (features) => {
1216
1246
  const getDeviceTypeByBleName = (name) => {
1217
1247
  if (!name)
1218
1248
  return hdShared.EDeviceType.Unknown;
1219
- if (name.startsWith('BixinKey'))
1249
+ if (/^BixinKey/i.test(name))
1220
1250
  return hdShared.EDeviceType.Classic;
1221
- if (name.startsWith('K'))
1251
+ if (/^K/i.test(name))
1222
1252
  return hdShared.EDeviceType.Classic;
1223
- if (name.startsWith('T'))
1253
+ if (/^T/i.test(name))
1224
1254
  return hdShared.EDeviceType.Touch;
1225
- if (name.startsWith('Touch'))
1255
+ if (/^Touch/i.test(name))
1226
1256
  return hdShared.EDeviceType.Touch;
1227
- if (name.startsWith('Pro'))
1257
+ if (/\bPro\s*2\b/i.test(name) || /^Pro2/i.test(name))
1258
+ return hdShared.EDeviceType.Pro2;
1259
+ if (/\bPro\b/i.test(name) || /^Pro/i.test(name))
1228
1260
  return hdShared.EDeviceType.Pro;
1229
1261
  return hdShared.EDeviceType.Unknown;
1230
1262
  };
@@ -1457,7 +1489,7 @@ const validatePath = (path, length = 0, base = false) => {
1457
1489
  return base ? valid.splice(0, 3) : valid;
1458
1490
  };
1459
1491
 
1460
- var nested$1 = {
1492
+ var nested$2 = {
1461
1493
  AlephiumGetAddress: {
1462
1494
  fields: {
1463
1495
  address_n: {
@@ -14901,10 +14933,10 @@ var nested$1 = {
14901
14933
  }
14902
14934
  };
14903
14935
  var MessagesJSON = {
14904
- nested: nested$1
14936
+ nested: nested$2
14905
14937
  };
14906
14938
 
14907
- var nested = {
14939
+ var nested$1 = {
14908
14940
  AlgorandGetAddress: {
14909
14941
  fields: {
14910
14942
  address_n: {
@@ -25280,6 +25312,747 @@ var nested = {
25280
25312
  }
25281
25313
  };
25282
25314
  var MessagesLegacyV1JSON = {
25315
+ nested: nested$1
25316
+ };
25317
+
25318
+ var nested = {
25319
+ GetProtoVersion: {
25320
+ fields: {
25321
+ }
25322
+ },
25323
+ ProtoVersion: {
25324
+ fields: {
25325
+ proto_version: {
25326
+ rule: "required",
25327
+ type: "uint32",
25328
+ id: 1
25329
+ }
25330
+ }
25331
+ },
25332
+ Ping: {
25333
+ fields: {
25334
+ message: {
25335
+ type: "string",
25336
+ id: 1,
25337
+ options: {
25338
+ "default": ""
25339
+ }
25340
+ }
25341
+ }
25342
+ },
25343
+ Success: {
25344
+ fields: {
25345
+ message: {
25346
+ type: "string",
25347
+ id: 1,
25348
+ options: {
25349
+ "default": ""
25350
+ }
25351
+ }
25352
+ }
25353
+ },
25354
+ Failure: {
25355
+ fields: {
25356
+ code: {
25357
+ type: "FailureType",
25358
+ id: 1
25359
+ },
25360
+ message: {
25361
+ type: "string",
25362
+ id: 2
25363
+ }
25364
+ },
25365
+ nested: {
25366
+ FailureType: {
25367
+ values: {
25368
+ Failure_UnexpectedMessage: 1,
25369
+ Failure_ButtonExpected: 2,
25370
+ Failure_DataError: 3,
25371
+ Failure_ActionCancelled: 4,
25372
+ Failure_PinExpected: 5,
25373
+ Failure_PinCancelled: 6,
25374
+ Failure_PinInvalid: 7,
25375
+ Failure_InvalidSignature: 8,
25376
+ Failure_ProcessError: 9,
25377
+ Failure_NotEnoughFunds: 10,
25378
+ Failure_NotInitialized: 11,
25379
+ Failure_PinMismatch: 12,
25380
+ Failure_WipeCodeMismatch: 13,
25381
+ Failure_InvalidSession: 14,
25382
+ Failure_FirmwareError: 99
25383
+ }
25384
+ }
25385
+ }
25386
+ },
25387
+ DevRebootType: {
25388
+ values: {
25389
+ Normal: 0,
25390
+ Boardloader: 1,
25391
+ Bootloader: 2
25392
+ }
25393
+ },
25394
+ DevReboot: {
25395
+ fields: {
25396
+ reboot_type: {
25397
+ rule: "required",
25398
+ type: "DevRebootType",
25399
+ id: 1
25400
+ }
25401
+ }
25402
+ },
25403
+ DeviceType: {
25404
+ values: {
25405
+ CLASSIC1: 0,
25406
+ CLASSIC1S: 1,
25407
+ MINI: 2,
25408
+ TOUCH: 3,
25409
+ PRO: 5,
25410
+ CLASSIC1S_PURE: 6
25411
+ }
25412
+ },
25413
+ DevSeType: {
25414
+ values: {
25415
+ THD89: 0,
25416
+ SE608A: 1
25417
+ }
25418
+ },
25419
+ DevSEState: {
25420
+ values: {
25421
+ BOOT: 0,
25422
+ APP_FACTORY: 51,
25423
+ APP: 85
25424
+ }
25425
+ },
25426
+ DevFirmwareImageInfo: {
25427
+ fields: {
25428
+ version: {
25429
+ type: "string",
25430
+ id: 10
25431
+ },
25432
+ build_id: {
25433
+ type: "string",
25434
+ id: 20
25435
+ },
25436
+ hash: {
25437
+ type: "bytes",
25438
+ id: 30
25439
+ }
25440
+ }
25441
+ },
25442
+ DevHardwareInfo: {
25443
+ fields: {
25444
+ device_type: {
25445
+ type: "DeviceType",
25446
+ id: 10
25447
+ },
25448
+ serial_no: {
25449
+ type: "string",
25450
+ id: 11
25451
+ },
25452
+ hardware_version: {
25453
+ type: "string",
25454
+ id: 100
25455
+ },
25456
+ hardware_version_raw_adc: {
25457
+ type: "uint32",
25458
+ id: 101
25459
+ }
25460
+ }
25461
+ },
25462
+ DevMainMcuInfo: {
25463
+ fields: {
25464
+ board: {
25465
+ type: "DevFirmwareImageInfo",
25466
+ id: 10
25467
+ },
25468
+ boot: {
25469
+ type: "DevFirmwareImageInfo",
25470
+ id: 20
25471
+ },
25472
+ app: {
25473
+ type: "DevFirmwareImageInfo",
25474
+ id: 30
25475
+ }
25476
+ }
25477
+ },
25478
+ DevBluetoothInfo: {
25479
+ fields: {
25480
+ boot: {
25481
+ type: "DevFirmwareImageInfo",
25482
+ id: 20
25483
+ },
25484
+ app: {
25485
+ type: "DevFirmwareImageInfo",
25486
+ id: 30
25487
+ },
25488
+ adv_name: {
25489
+ type: "string",
25490
+ id: 100
25491
+ },
25492
+ mac: {
25493
+ type: "bytes",
25494
+ id: 110
25495
+ }
25496
+ }
25497
+ },
25498
+ DevSEInfo: {
25499
+ fields: {
25500
+ boot: {
25501
+ type: "DevFirmwareImageInfo",
25502
+ id: 20
25503
+ },
25504
+ app: {
25505
+ type: "DevFirmwareImageInfo",
25506
+ id: 30
25507
+ },
25508
+ type: {
25509
+ type: "DevSeType",
25510
+ id: 100
25511
+ },
25512
+ state: {
25513
+ type: "DevSEState",
25514
+ id: 110
25515
+ }
25516
+ }
25517
+ },
25518
+ DevInfoTargets: {
25519
+ fields: {
25520
+ hw: {
25521
+ type: "bool",
25522
+ id: 100
25523
+ },
25524
+ fw: {
25525
+ type: "bool",
25526
+ id: 200
25527
+ },
25528
+ bt: {
25529
+ type: "bool",
25530
+ id: 300
25531
+ },
25532
+ se1: {
25533
+ type: "bool",
25534
+ id: 400
25535
+ },
25536
+ se2: {
25537
+ type: "bool",
25538
+ id: 410
25539
+ },
25540
+ se3: {
25541
+ type: "bool",
25542
+ id: 420
25543
+ },
25544
+ se4: {
25545
+ type: "bool",
25546
+ id: 430
25547
+ },
25548
+ status: {
25549
+ type: "bool",
25550
+ id: 10000
25551
+ }
25552
+ }
25553
+ },
25554
+ DevInfoTypes: {
25555
+ fields: {
25556
+ version: {
25557
+ type: "bool",
25558
+ id: 10
25559
+ },
25560
+ build_id: {
25561
+ type: "bool",
25562
+ id: 20
25563
+ },
25564
+ hash: {
25565
+ type: "bool",
25566
+ id: 30
25567
+ },
25568
+ specific: {
25569
+ type: "bool",
25570
+ id: 40
25571
+ }
25572
+ }
25573
+ },
25574
+ DevStatus: {
25575
+ fields: {
25576
+ language: {
25577
+ type: "string",
25578
+ id: 100
25579
+ },
25580
+ bt_enable: {
25581
+ type: "bool",
25582
+ id: 101
25583
+ },
25584
+ init_states: {
25585
+ type: "bool",
25586
+ id: 102
25587
+ },
25588
+ backup_required: {
25589
+ type: "bool",
25590
+ id: 200
25591
+ },
25592
+ passphrase_protection: {
25593
+ type: "bool",
25594
+ id: 201
25595
+ },
25596
+ label: {
25597
+ type: "string",
25598
+ id: 300
25599
+ }
25600
+ }
25601
+ },
25602
+ DevGetDeviceInfo: {
25603
+ fields: {
25604
+ targets: {
25605
+ type: "DevInfoTargets",
25606
+ id: 1
25607
+ },
25608
+ types: {
25609
+ type: "DevInfoTypes",
25610
+ id: 2
25611
+ }
25612
+ }
25613
+ },
25614
+ DeviceInfo: {
25615
+ fields: {
25616
+ protocol_version: {
25617
+ rule: "required",
25618
+ type: "uint32",
25619
+ id: 1
25620
+ },
25621
+ hw: {
25622
+ type: "DevHardwareInfo",
25623
+ id: 100
25624
+ },
25625
+ fw: {
25626
+ type: "DevMainMcuInfo",
25627
+ id: 200
25628
+ },
25629
+ bt: {
25630
+ type: "DevBluetoothInfo",
25631
+ id: 300
25632
+ },
25633
+ se1: {
25634
+ type: "DevSEInfo",
25635
+ id: 400
25636
+ },
25637
+ se2: {
25638
+ type: "DevSEInfo",
25639
+ id: 410
25640
+ },
25641
+ se3: {
25642
+ type: "DevSEInfo",
25643
+ id: 420
25644
+ },
25645
+ se4: {
25646
+ type: "DevSEInfo",
25647
+ id: 430
25648
+ },
25649
+ status: {
25650
+ type: "DevStatus",
25651
+ id: 10000
25652
+ }
25653
+ }
25654
+ },
25655
+ DevGetOnboardingStatus: {
25656
+ fields: {
25657
+ }
25658
+ },
25659
+ DevOnboardingStatus: {
25660
+ fields: {
25661
+ page_index: {
25662
+ type: "uint32",
25663
+ id: 1
25664
+ },
25665
+ page_count: {
25666
+ type: "uint32",
25667
+ id: 2
25668
+ },
25669
+ page_name: {
25670
+ type: "string",
25671
+ id: 3
25672
+ }
25673
+ }
25674
+ },
25675
+ DevFirmwareTargetType: {
25676
+ values: {
25677
+ TARGET_MAIN_APP: 0,
25678
+ TARGET_MAIN_BOOT: 1,
25679
+ TARGET_BT: 2,
25680
+ TARGET_SE1: 3,
25681
+ TARGET_SE2: 4,
25682
+ TARGET_SE3: 5,
25683
+ TARGET_SE4: 6,
25684
+ TARGET_RESOURCE: 10
25685
+ }
25686
+ },
25687
+ DevFirmwareTarget: {
25688
+ fields: {
25689
+ target_id: {
25690
+ rule: "required",
25691
+ type: "DevFirmwareTargetType",
25692
+ id: 1
25693
+ },
25694
+ path: {
25695
+ rule: "required",
25696
+ type: "string",
25697
+ id: 2
25698
+ }
25699
+ }
25700
+ },
25701
+ DevFirmwareUpdate: {
25702
+ fields: {
25703
+ targets: {
25704
+ rule: "repeated",
25705
+ type: "DevFirmwareTarget",
25706
+ id: 1
25707
+ }
25708
+ }
25709
+ },
25710
+ DevFirmwareInstallProgress: {
25711
+ fields: {
25712
+ target_id: {
25713
+ rule: "required",
25714
+ type: "DevFirmwareTargetType",
25715
+ id: 1
25716
+ },
25717
+ progress: {
25718
+ rule: "required",
25719
+ type: "uint32",
25720
+ id: 2
25721
+ },
25722
+ stage: {
25723
+ type: "string",
25724
+ id: 3
25725
+ }
25726
+ }
25727
+ },
25728
+ DevFirmwareUpdateStatusEntry: {
25729
+ fields: {
25730
+ target_id: {
25731
+ rule: "required",
25732
+ type: "DevFirmwareTargetType",
25733
+ id: 1
25734
+ },
25735
+ status: {
25736
+ rule: "required",
25737
+ type: "uint32",
25738
+ id: 2
25739
+ }
25740
+ }
25741
+ },
25742
+ DevGetFirmwareUpdateStatus: {
25743
+ fields: {
25744
+ }
25745
+ },
25746
+ DevFirmwareUpdateStatus: {
25747
+ fields: {
25748
+ targets: {
25749
+ rule: "repeated",
25750
+ type: "DevFirmwareUpdateStatusEntry",
25751
+ id: 1
25752
+ }
25753
+ }
25754
+ },
25755
+ FactoryDeviceInfoSettings: {
25756
+ fields: {
25757
+ serial_no: {
25758
+ type: "string",
25759
+ id: 1
25760
+ },
25761
+ cpu_info: {
25762
+ type: "string",
25763
+ id: 2
25764
+ },
25765
+ pre_firmware: {
25766
+ type: "string",
25767
+ id: 3
25768
+ }
25769
+ }
25770
+ },
25771
+ FactoryGetDeviceInfo: {
25772
+ fields: {
25773
+ }
25774
+ },
25775
+ FactoryDeviceInfo: {
25776
+ fields: {
25777
+ serial_no: {
25778
+ type: "string",
25779
+ id: 1
25780
+ },
25781
+ spi_flash_info: {
25782
+ type: "string",
25783
+ id: 2
25784
+ },
25785
+ se_info: {
25786
+ type: "string",
25787
+ id: 3
25788
+ },
25789
+ nft_voucher: {
25790
+ type: "bytes",
25791
+ id: 4
25792
+ },
25793
+ cpu_info: {
25794
+ type: "string",
25795
+ id: 5
25796
+ },
25797
+ pre_firmware: {
25798
+ type: "string",
25799
+ id: 6
25800
+ }
25801
+ }
25802
+ },
25803
+ FilesystemFixPermission: {
25804
+ fields: {
25805
+ }
25806
+ },
25807
+ FilesystemPathInfo: {
25808
+ fields: {
25809
+ exist: {
25810
+ rule: "required",
25811
+ type: "bool",
25812
+ id: 1
25813
+ },
25814
+ size: {
25815
+ rule: "required",
25816
+ type: "uint64",
25817
+ id: 2
25818
+ },
25819
+ year: {
25820
+ rule: "required",
25821
+ type: "uint32",
25822
+ id: 3
25823
+ },
25824
+ month: {
25825
+ rule: "required",
25826
+ type: "uint32",
25827
+ id: 4
25828
+ },
25829
+ day: {
25830
+ rule: "required",
25831
+ type: "uint32",
25832
+ id: 5
25833
+ },
25834
+ hour: {
25835
+ rule: "required",
25836
+ type: "uint32",
25837
+ id: 6
25838
+ },
25839
+ minute: {
25840
+ rule: "required",
25841
+ type: "uint32",
25842
+ id: 7
25843
+ },
25844
+ second: {
25845
+ rule: "required",
25846
+ type: "uint32",
25847
+ id: 8
25848
+ },
25849
+ readonly: {
25850
+ rule: "required",
25851
+ type: "bool",
25852
+ id: 9
25853
+ },
25854
+ hidden: {
25855
+ rule: "required",
25856
+ type: "bool",
25857
+ id: 10
25858
+ },
25859
+ system: {
25860
+ rule: "required",
25861
+ type: "bool",
25862
+ id: 11
25863
+ },
25864
+ archive: {
25865
+ rule: "required",
25866
+ type: "bool",
25867
+ id: 12
25868
+ },
25869
+ directory: {
25870
+ rule: "required",
25871
+ type: "bool",
25872
+ id: 13
25873
+ }
25874
+ }
25875
+ },
25876
+ FilesystemPathInfoQuery: {
25877
+ fields: {
25878
+ path: {
25879
+ rule: "required",
25880
+ type: "string",
25881
+ id: 1
25882
+ }
25883
+ }
25884
+ },
25885
+ FilesystemFile: {
25886
+ fields: {
25887
+ path: {
25888
+ rule: "required",
25889
+ type: "string",
25890
+ id: 1
25891
+ },
25892
+ offset: {
25893
+ rule: "required",
25894
+ type: "uint32",
25895
+ id: 2
25896
+ },
25897
+ total_size: {
25898
+ rule: "required",
25899
+ type: "uint32",
25900
+ id: 3
25901
+ },
25902
+ data: {
25903
+ type: "bytes",
25904
+ id: 4
25905
+ },
25906
+ data_hash: {
25907
+ type: "uint32",
25908
+ id: 5
25909
+ },
25910
+ processed_byte: {
25911
+ type: "uint32",
25912
+ id: 6
25913
+ }
25914
+ }
25915
+ },
25916
+ FilesystemFileRead: {
25917
+ fields: {
25918
+ file: {
25919
+ rule: "required",
25920
+ type: "FilesystemFile",
25921
+ id: 1
25922
+ },
25923
+ chunk_len: {
25924
+ type: "uint32",
25925
+ id: 2
25926
+ },
25927
+ ui_percentage: {
25928
+ type: "uint32",
25929
+ id: 3
25930
+ }
25931
+ }
25932
+ },
25933
+ FilesystemFileWrite: {
25934
+ fields: {
25935
+ file: {
25936
+ rule: "required",
25937
+ type: "FilesystemFile",
25938
+ id: 1
25939
+ },
25940
+ overwrite: {
25941
+ rule: "required",
25942
+ type: "bool",
25943
+ id: 2
25944
+ },
25945
+ append: {
25946
+ rule: "required",
25947
+ type: "bool",
25948
+ id: 3
25949
+ },
25950
+ ui_percentage: {
25951
+ type: "uint32",
25952
+ id: 4
25953
+ }
25954
+ }
25955
+ },
25956
+ FilesystemFileDelete: {
25957
+ fields: {
25958
+ path: {
25959
+ rule: "required",
25960
+ type: "string",
25961
+ id: 1
25962
+ }
25963
+ }
25964
+ },
25965
+ FilesystemDir: {
25966
+ fields: {
25967
+ path: {
25968
+ rule: "required",
25969
+ type: "string",
25970
+ id: 1
25971
+ },
25972
+ child_dirs: {
25973
+ type: "string",
25974
+ id: 2
25975
+ },
25976
+ child_files: {
25977
+ type: "string",
25978
+ id: 3
25979
+ }
25980
+ }
25981
+ },
25982
+ FilesystemDirList: {
25983
+ fields: {
25984
+ path: {
25985
+ rule: "required",
25986
+ type: "string",
25987
+ id: 1
25988
+ },
25989
+ depth: {
25990
+ type: "uint32",
25991
+ id: 2,
25992
+ options: {
25993
+ "default": 0
25994
+ }
25995
+ }
25996
+ }
25997
+ },
25998
+ FilesystemDirMake: {
25999
+ fields: {
26000
+ path: {
26001
+ rule: "required",
26002
+ type: "string",
26003
+ id: 1
26004
+ }
26005
+ }
26006
+ },
26007
+ FilesystemDirRemove: {
26008
+ fields: {
26009
+ path: {
26010
+ rule: "required",
26011
+ type: "string",
26012
+ id: 1
26013
+ }
26014
+ }
26015
+ },
26016
+ FilesystemFormat: {
26017
+ fields: {
26018
+ }
26019
+ },
26020
+ MessageType: {
26021
+ values: {
26022
+ MessageType_FactoryDeviceInfoSettings: 60000,
26023
+ MessageType_FactoryGetDeviceInfo: 60001,
26024
+ MessageType_FactoryDeviceInfo: 60002,
26025
+ MessageType_GetProtoVersion: 60200,
26026
+ MessageType_ProtoVersion: 60201,
26027
+ MessageType_StartSession: 60205,
26028
+ MessageType_Ping: 60206,
26029
+ MessageType_Success: 60207,
26030
+ MessageType_Failure: 60208,
26031
+ MessageType_DevReboot: 60400,
26032
+ MessageType_DevGetDeviceInfo: 60600,
26033
+ MessageType_DeviceInfo: 60601,
26034
+ MessageType_DevGetOnboardingStatus: 60602,
26035
+ MessageType_DevOnboardingStatus: 60603,
26036
+ MessageType_FilesystemFixPermission: 60800,
26037
+ MessageType_FilesystemPathInfo: 60801,
26038
+ MessageType_FilesystemPathInfoQuery: 60802,
26039
+ MessageType_FilesystemFile: 60803,
26040
+ MessageType_FilesystemFileRead: 60804,
26041
+ MessageType_FilesystemFileWrite: 60805,
26042
+ MessageType_FilesystemFileDelete: 60806,
26043
+ MessageType_FilesystemDir: 60807,
26044
+ MessageType_FilesystemDirList: 60808,
26045
+ MessageType_FilesystemDirMake: 60809,
26046
+ MessageType_FilesystemDirRemove: 60810,
26047
+ MessageType_FilesystemFormat: 60811,
26048
+ MessageType_DevFirmwareUpdate: 61000,
26049
+ MessageType_DevFirmwareInstallProgress: 61001,
26050
+ MessageType_DevGetFirmwareUpdateStatus: 61002,
26051
+ MessageType_DevFirmwareUpdateStatus: 61003
26052
+ }
26053
+ }
26054
+ };
26055
+ var MessagesPro2JSON = {
25283
26056
  nested: nested
25284
26057
  };
25285
26058
 
@@ -25308,7 +26081,7 @@ const findLatestRelease = (releases) => {
25308
26081
  };
25309
26082
 
25310
26083
  var _a$1;
25311
- const Log$e = getLogger(exports.LoggerNames.Core);
26084
+ const Log$f = getLogger(exports.LoggerNames.Core);
25312
26085
  const FIRMWARE_FIELDS = [
25313
26086
  'firmware',
25314
26087
  'firmware-v2',
@@ -25370,37 +26143,37 @@ class DataManager {
25370
26143
  let data = null;
25371
26144
  let fetchMethod = 'none';
25372
26145
  if (settings.configFetcher) {
25373
- Log$e.debug('[DataConfig] Trying configFetcher (client-side fetcher)...');
26146
+ Log$f.debug('[DataConfig] Trying configFetcher (client-side fetcher)...');
25374
26147
  try {
25375
26148
  data = yield settings.configFetcher(urlWithCache);
25376
26149
  if (data) {
25377
26150
  fetchMethod = 'configFetcher';
25378
- Log$e.log('[DataConfig] ConfigFetcher success');
26151
+ Log$f.log('[DataConfig] ConfigFetcher success');
25379
26152
  }
25380
26153
  else {
25381
- Log$e.debug('[DataConfig] ConfigFetcher returned null, will fallback to axios');
26154
+ Log$f.debug('[DataConfig] ConfigFetcher returned null, will fallback to axios');
25382
26155
  }
25383
26156
  }
25384
26157
  catch (e) {
25385
- Log$e.warn('[DataConfig] ConfigFetcher error, will fallback to axios:', e);
26158
+ Log$f.warn('[DataConfig] ConfigFetcher error, will fallback to axios:', e);
25386
26159
  }
25387
26160
  }
25388
26161
  if (!data) {
25389
- Log$e.debug('[DataConfig] Trying axios (SDK default fetcher)...');
26162
+ Log$f.debug('[DataConfig] Trying axios (SDK default fetcher)...');
25390
26163
  try {
25391
26164
  const response = yield axios__default["default"].get(urlWithCache, {
25392
26165
  timeout: 7000,
25393
26166
  });
25394
26167
  data = response.data;
25395
26168
  fetchMethod = 'axios';
25396
- Log$e.log('[DataConfig] Axios fetch success');
26169
+ Log$f.log('[DataConfig] Axios fetch success');
25397
26170
  }
25398
26171
  catch (e) {
25399
- Log$e.warn('[DataConfig] Axios fetch error:', e);
26172
+ Log$f.warn('[DataConfig] Axios fetch error:', e);
25400
26173
  }
25401
26174
  }
25402
26175
  if (data) {
25403
- Log$e.log(`[DataConfig] Config loaded successfully via [${fetchMethod}]`);
26176
+ Log$f.log(`[DataConfig] Config loaded successfully via [${fetchMethod}]`);
25404
26177
  this.deviceMap = {
25405
26178
  [hdShared.EDeviceType.Classic]: this.enrichFirmwareReleaseInfo(data.classic),
25406
26179
  [hdShared.EDeviceType.Classic1s]: this.enrichFirmwareReleaseInfo(data.classic1s),
@@ -25414,7 +26187,7 @@ class DataManager {
25414
26187
  };
25415
26188
  }
25416
26189
  else {
25417
- Log$e.warn('[DataConfig] All fetch methods failed, using built-in default config');
26190
+ Log$f.warn('[DataConfig] All fetch methods failed, using built-in default config');
25418
26191
  }
25419
26192
  });
25420
26193
  }
@@ -25477,6 +26250,7 @@ DataManager.assets = null;
25477
26250
  DataManager.messages = {
25478
26251
  latest: MessagesJSON,
25479
26252
  v1: MessagesLegacyV1JSON,
26253
+ protocolV2: MessagesPro2JSON,
25480
26254
  };
25481
26255
  DataManager.lastCheckTimestamp = 0;
25482
26256
  DataManager.getFirmwareStatus = (features, firmwareType) => {
@@ -26682,7 +27456,7 @@ const LogBlockEvent = new Set([
26682
27456
  UI_RESPONSE.RECEIVE_PASSPHRASE,
26683
27457
  ]);
26684
27458
 
26685
- const Log$d = getLogger(exports.LoggerNames.DevicePool);
27459
+ const Log$e = getLogger(exports.LoggerNames.DevicePool);
26686
27460
  const getDiff = (current, descriptors) => {
26687
27461
  const connected = descriptors.filter(d => current.find(x => x.path === d.path) === undefined);
26688
27462
  const disconnected = current.filter(d => descriptors.find(x => x.path === d.path) === undefined);
@@ -26740,7 +27514,7 @@ class DevicePool extends events.exports {
26740
27514
  yield this._checkDevicePool(initOptions);
26741
27515
  return { devices, deviceList };
26742
27516
  }
26743
- Log$d.debug('found device in cache, but path is different: ', connectId);
27517
+ Log$e.debug('found device in cache, but path is different: ', connectId);
26744
27518
  }
26745
27519
  }
26746
27520
  try {
@@ -26783,7 +27557,7 @@ class DevicePool extends events.exports {
26783
27557
  if (!device) {
26784
27558
  device = Device.fromDescriptor(descriptor);
26785
27559
  device.deviceConnector = this.connector;
26786
- yield device.connect();
27560
+ yield device.connect(initOptions === null || initOptions === void 0 ? void 0 : initOptions.connectProtocol);
26787
27561
  yield device.initialize(initOptions);
26788
27562
  yield device.release();
26789
27563
  }
@@ -26801,7 +27575,7 @@ class DevicePool extends events.exports {
26801
27575
  for (let i = this.connectedPool.length - 1; i >= 0; i--) {
26802
27576
  const descriptor = this.connectedPool[i];
26803
27577
  const device = yield this._createDevice(descriptor, initOptions);
26804
- Log$d.debug('emit DEVICE.CONNECT: ', device === null || device === void 0 ? void 0 : device.features);
27578
+ Log$e.debug('emit DEVICE.CONNECT: ', device === null || device === void 0 ? void 0 : device.features);
26805
27579
  this.emitter.emit(DEVICE.CONNECT, device);
26806
27580
  this.connectedPool.splice(i, 1);
26807
27581
  }
@@ -26821,9 +27595,9 @@ class DevicePool extends events.exports {
26821
27595
  const diff = getDiff(this.current || [], upcoming);
26822
27596
  this.upcoming = upcoming;
26823
27597
  this.current = this.upcoming;
26824
- Log$d.debug('device pool -> current: ', this.current);
26825
- Log$d.debug('device pool -> upcomming: ', this.upcoming);
26826
- Log$d.debug('DeviceCache.reportDeviceChange diff: ', diff);
27598
+ Log$e.debug('device pool -> current: ', this.current);
27599
+ Log$e.debug('device pool -> upcomming: ', this.upcoming);
27600
+ Log$e.debug('DeviceCache.reportDeviceChange diff: ', diff);
26827
27601
  if (!diff.didUpdate) {
26828
27602
  return;
26829
27603
  }
@@ -26833,7 +27607,7 @@ class DevicePool extends events.exports {
26833
27607
  this._addConnectedDeviceToPool(d);
26834
27608
  return;
26835
27609
  }
26836
- Log$d.debug('emit DEVICE.CONNECT: ', device.features);
27610
+ Log$e.debug('emit DEVICE.CONNECT: ', device.features);
26837
27611
  this.emitter.emit(DEVICE.CONNECT, device);
26838
27612
  });
26839
27613
  diff.disconnected.forEach(d => {
@@ -26843,7 +27617,7 @@ class DevicePool extends events.exports {
26843
27617
  this._addDisconnectedDeviceToPool(d);
26844
27618
  return;
26845
27619
  }
26846
- Log$d.debug('emit DEVICE.DISCONNECT: ', device.features);
27620
+ Log$e.debug('emit DEVICE.DISCONNECT: ', device.features);
26847
27621
  this.emitter.emit(DEVICE.DISCONNECT, device);
26848
27622
  });
26849
27623
  }
@@ -26879,7 +27653,7 @@ class DevicePool extends events.exports {
26879
27653
  this.disconnectPool = [];
26880
27654
  this.devicesCache = {};
26881
27655
  this.emitter.removeAllListeners();
26882
- Log$d.debug('DevicePool state has been reset');
27656
+ Log$e.debug('DevicePool state has been reset');
26883
27657
  }
26884
27658
  }
26885
27659
  DevicePool.current = null;
@@ -26889,16 +27663,17 @@ DevicePool.disconnectPool = [];
26889
27663
  DevicePool.devicesCache = {};
26890
27664
  DevicePool.emitter = new events.exports();
26891
27665
 
26892
- const Log$c = getLogger(exports.LoggerNames.Transport);
27666
+ const Log$d = getLogger(exports.LoggerNames.Transport);
26893
27667
  const BleLogger = getLogger(exports.LoggerNames.HdBleTransport);
26894
27668
  const HttpLogger = getLogger(exports.LoggerNames.HdTransportHttp);
26895
27669
  const LowLevelLogger = getLogger(exports.LoggerNames.HdTransportLowLevel);
26896
27670
  const NodeUsbLogger = getLogger(exports.LoggerNames.HdTransportNodeUsb);
26897
27671
  const WebBleLogger = getLogger(exports.LoggerNames.HdWebBleTransport);
26898
27672
  const WebUsbLogger = getLogger(exports.LoggerNames.HdTransportWebUsb);
27673
+ const REACT_NATIVE_BLE_SCAN_TIMEOUT_MS = 8000;
26899
27674
  class TransportManager {
26900
27675
  static load() {
26901
- Log$c.debug('transport manager load');
27676
+ Log$d.debug('transport manager load');
26902
27677
  this.defaultMessages = DataManager.getProtobufMessages();
26903
27678
  this.currentMessages = this.defaultMessages;
26904
27679
  this.messageVersion = 'latest';
@@ -26907,14 +27682,14 @@ class TransportManager {
26907
27682
  return __awaiter(this, void 0, void 0, function* () {
26908
27683
  try {
26909
27684
  const env = DataManager.getSettings('env');
26910
- Log$c.debug('Initializing transports', env);
27685
+ Log$d.debug('Initializing transports', env);
26911
27686
  if (env === 'react-native') {
26912
27687
  if (!this.reactNativeInit) {
26913
27688
  yield this.transport.init(BleLogger, DevicePool.emitter);
26914
27689
  this.reactNativeInit = true;
26915
27690
  }
26916
27691
  else {
26917
- Log$c.debug('React Native Do Not Initializing transports');
27692
+ Log$d.debug('React Native Do Not Initializing transports');
26918
27693
  }
26919
27694
  }
26920
27695
  else if (env === 'node-usb') {
@@ -26935,12 +27710,15 @@ class TransportManager {
26935
27710
  else {
26936
27711
  yield this.transport.init(HttpLogger);
26937
27712
  }
26938
- Log$c.debug('Configuring transports');
27713
+ Log$d.debug('Configuring transports');
26939
27714
  yield this.transport.configure(JSON.stringify(this.defaultMessages));
26940
- Log$c.debug('Configuring transports done');
27715
+ this.currentMessages = this.defaultMessages;
27716
+ this.messageVersion = 'latest';
27717
+ yield this.configureProtocolV2Messages();
27718
+ Log$d.debug('Configuring transports done');
26941
27719
  }
26942
27720
  catch (error) {
26943
- Log$c.debug('Initializing transports error: ', error);
27721
+ Log$d.debug('Initializing transports error: ', error);
26944
27722
  if (error.code === 'ECONNABORTED') {
26945
27723
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BridgeTimeoutError);
26946
27724
  }
@@ -26949,12 +27727,14 @@ class TransportManager {
26949
27727
  }
26950
27728
  static reconfigure(features) {
26951
27729
  return __awaiter(this, void 0, void 0, function* () {
26952
- Log$c.debug(`Begin reconfiguring transports`);
27730
+ if (!features) {
27731
+ return;
27732
+ }
26953
27733
  const { messageVersion, messages } = getSupportMessageVersion(features);
26954
27734
  if (this.currentMessages === messages || !messages) {
26955
27735
  return;
26956
27736
  }
26957
- Log$c.debug(`Reconfiguring transports version:${messageVersion}`);
27737
+ Log$d.debug(`Reconfiguring transports version:${messageVersion}`);
26958
27738
  try {
26959
27739
  yield this.transport.configure(JSON.stringify(messages));
26960
27740
  this.currentMessages = messages;
@@ -26968,20 +27748,32 @@ class TransportManager {
26968
27748
  static setTransport(TransportConstructor, plugin) {
26969
27749
  const env = DataManager.getSettings('env');
26970
27750
  if (env === 'react-native') {
26971
- this.transport = new TransportConstructor({ scanTimeout: 3000 });
27751
+ this.transport = new TransportConstructor({
27752
+ scanTimeout: REACT_NATIVE_BLE_SCAN_TIMEOUT_MS,
27753
+ });
26972
27754
  }
26973
27755
  else {
26974
27756
  this.transport = new TransportConstructor();
26975
27757
  }
26976
27758
  if (plugin) {
26977
27759
  this.plugin = plugin;
26978
- Log$c.debug('set transport plugin: ', this.plugin);
27760
+ Log$d.debug('set transport plugin: ', this.plugin);
26979
27761
  }
26980
- Log$c.debug('set transport: ', this.transport.name, this.transport.version, this.transport.configured);
27762
+ Log$d.debug('set transport: ', this.transport.name, this.transport.version, this.transport.configured);
26981
27763
  }
26982
27764
  static getTransport() {
26983
27765
  return this.transport;
26984
27766
  }
27767
+ static configureProtocolV2Messages() {
27768
+ return __awaiter(this, void 0, void 0, function* () {
27769
+ const protocolV2Messages = DataManager.getProtobufMessages('protocolV2');
27770
+ const { configureProtocolV2 } = this.transport;
27771
+ if (protocolV2Messages && typeof configureProtocolV2 === 'function') {
27772
+ yield configureProtocolV2.call(this.transport, JSON.stringify(protocolV2Messages));
27773
+ Log$d.debug('Protocol V2 messages configured');
27774
+ }
27775
+ });
27776
+ }
26985
27777
  static getDefaultMessages() {
26986
27778
  return this.defaultMessages;
26987
27779
  }
@@ -26996,6 +27788,88 @@ TransportManager.reactNativeInit = false;
26996
27788
  TransportManager.messageVersion = 'latest';
26997
27789
  TransportManager.plugin = null;
26998
27790
 
27791
+ const MAX_DEBUG_ARRAY_ITEMS = 20;
27792
+ const MAX_DEBUG_OBJECT_KEYS = 40;
27793
+ const MAX_DEBUG_STRING_LENGTH = 512;
27794
+ const MAX_DEBUG_DEPTH = 4;
27795
+ const HIGH_VOLUME_DEBUG_CALLS = new Set([
27796
+ 'FilesystemFileWrite',
27797
+ 'FileWrite',
27798
+ 'EmmcFileWrite',
27799
+ 'FirmwareUpload',
27800
+ 'ResourceAck',
27801
+ ]);
27802
+ function shouldReduceDebugForCall(type) {
27803
+ return HIGH_VOLUME_DEBUG_CALLS.has(type);
27804
+ }
27805
+ function getBinaryByteLength(value) {
27806
+ if (value instanceof ArrayBuffer) {
27807
+ return value.byteLength;
27808
+ }
27809
+ if (ArrayBuffer.isView(value)) {
27810
+ return value.byteLength;
27811
+ }
27812
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
27813
+ return value.size;
27814
+ }
27815
+ return undefined;
27816
+ }
27817
+ function summarizeRedactedData(value) {
27818
+ const byteLength = getBinaryByteLength(value);
27819
+ if (byteLength !== undefined) {
27820
+ return `[redacted data: ${byteLength} bytes]`;
27821
+ }
27822
+ if (typeof value === 'string') {
27823
+ return `[redacted data: string length=${value.length}]`;
27824
+ }
27825
+ if (Array.isArray(value)) {
27826
+ return `[redacted data: array length=${value.length}]`;
27827
+ }
27828
+ if (value && typeof value === 'object') {
27829
+ return `[redacted data: object keys=${Object.keys(value).length}]`;
27830
+ }
27831
+ return `[redacted data: ${typeof value}]`;
27832
+ }
27833
+ function sanitizeDebugPayload(value, key = '', depth = 0) {
27834
+ if (key === 'data' && value !== null && value !== undefined) {
27835
+ return summarizeRedactedData(value);
27836
+ }
27837
+ const byteLength = getBinaryByteLength(value);
27838
+ if (byteLength !== undefined) {
27839
+ return `[binary: ${byteLength} bytes]`;
27840
+ }
27841
+ if (typeof value === 'string') {
27842
+ return value.length > MAX_DEBUG_STRING_LENGTH
27843
+ ? `${value.slice(0, MAX_DEBUG_STRING_LENGTH)}... (len=${value.length})`
27844
+ : value;
27845
+ }
27846
+ if (!value || typeof value !== 'object') {
27847
+ return value;
27848
+ }
27849
+ if (depth >= MAX_DEBUG_DEPTH) {
27850
+ return Array.isArray(value)
27851
+ ? `[array length=${value.length}]`
27852
+ : `[object keys=${Object.keys(value).length}]`;
27853
+ }
27854
+ if (Array.isArray(value)) {
27855
+ const items = value
27856
+ .slice(0, MAX_DEBUG_ARRAY_ITEMS)
27857
+ .map(item => sanitizeDebugPayload(item, key, depth + 1));
27858
+ if (value.length > MAX_DEBUG_ARRAY_ITEMS) {
27859
+ items.push(`... (${value.length - MAX_DEBUG_ARRAY_ITEMS} more)`);
27860
+ }
27861
+ return items;
27862
+ }
27863
+ const entries = Object.entries(value).slice(0, MAX_DEBUG_OBJECT_KEYS);
27864
+ const sanitized = {};
27865
+ entries.forEach(([entryKey, entryValue]) => {
27866
+ sanitized[entryKey] = sanitizeDebugPayload(entryValue, entryKey, depth + 1);
27867
+ });
27868
+ if (Object.keys(value).length > MAX_DEBUG_OBJECT_KEYS) {
27869
+ sanitized.__truncated__ = `${Object.keys(value).length - MAX_DEBUG_OBJECT_KEYS} more keys`;
27870
+ }
27871
+ return sanitized;
27872
+ }
26999
27873
  const assertType = (res, resType) => {
27000
27874
  const splitResTypes = Array.isArray(resType) ? resType : resType.split('|');
27001
27875
  if (!splitResTypes.includes(res.type)) {
@@ -27065,7 +27939,7 @@ const cancelDeviceWithInitialize = (device) => {
27065
27939
  },
27066
27940
  }));
27067
27941
  };
27068
- const Log$b = getLogger(exports.LoggerNames.DeviceCommands);
27942
+ const Log$c = getLogger(exports.LoggerNames.DeviceCommands);
27069
27943
  const LogCore = getLogger(exports.LoggerNames.Core);
27070
27944
  class DeviceCommands {
27071
27945
  constructor(device, mainId) {
@@ -27074,7 +27948,7 @@ class DeviceCommands {
27074
27948
  this.transport = TransportManager.getTransport();
27075
27949
  this.disposed = false;
27076
27950
  this.instanceId = generateInstanceId('DeviceCommands', device.sdkInstanceId);
27077
- Log$b.debug(`[DeviceCommands] Created: ${this.instanceId}, device: ${this.device.instanceId}`);
27951
+ Log$c.debug(`[DeviceCommands] Created: ${this.instanceId}, device: ${this.device.instanceId}`);
27078
27952
  }
27079
27953
  dispose(_cancelRequest) {
27080
27954
  var _a, _b;
@@ -27139,18 +28013,21 @@ class DeviceCommands {
27139
28013
  }
27140
28014
  });
27141
28015
  }
27142
- call(type, msg = {}) {
28016
+ call(type, msg, options) {
27143
28017
  var _a;
27144
28018
  return __awaiter(this, void 0, void 0, function* () {
27145
- Log$b.debug('[DeviceCommands] [call] Sending', type);
28019
+ const shouldReduceDebug = shouldReduceDebugForCall(type);
28020
+ if (!shouldReduceDebug) {
28021
+ Log$c.debug('[DeviceCommands] [call] Sending', type);
28022
+ }
27146
28023
  try {
27147
- const promise = this.transport.call(this.mainId, type, msg);
28024
+ const promise = this.transport.call(this.mainId, type, msg !== null && msg !== void 0 ? msg : {}, options);
27148
28025
  this.callPromise = promise;
27149
28026
  const res = yield promise;
27150
28027
  if (res.type === 'Failure') {
27151
28028
  LogCore.debug('[DeviceCommands] [call] Received', res.type, res.message);
27152
28029
  }
27153
- else {
28030
+ else if (!shouldReduceDebug) {
27154
28031
  LogCore.debug('[DeviceCommands] [call] Received', res.type);
27155
28032
  }
27156
28033
  return res;
@@ -27176,7 +28053,7 @@ class DeviceCommands {
27176
28053
  }
27177
28054
  }
27178
28055
  if (responseData) {
27179
- Log$b.debug('error response', responseData);
28056
+ Log$c.debug('error response', responseData);
27180
28057
  }
27181
28058
  if (responseError === 'device disconnected during action') {
27182
28059
  return { type: 'BridgeDeviceDisconnected', message: { error: responseError } };
@@ -27193,7 +28070,7 @@ class DeviceCommands {
27193
28070
  }
27194
28071
  });
27195
28072
  }
27196
- typedCall(type, resType, msg) {
28073
+ typedCall(type, resType, msg, options) {
27197
28074
  return __awaiter(this, void 0, void 0, function* () {
27198
28075
  if (this.disposed) {
27199
28076
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'typedCall: DeviceCommands already disposed');
@@ -27205,21 +28082,32 @@ class DeviceCommands {
27205
28082
  'PassphraseAck',
27206
28083
  'Cancel',
27207
28084
  'BixinPinInputOnDevice',
28085
+ 'FilesystemFileWrite',
28086
+ 'FileWrite',
28087
+ 'EmmcFileWrite',
28088
+ 'FirmwareUpload',
28089
+ 'ResourceAck',
27208
28090
  ];
27209
28091
  if (!skipTypes.includes(type) && msg) {
27210
- Log$b.debug('[DeviceCommands] [typedCall] Sending payload', type, msg);
28092
+ Log$c.debug('[DeviceCommands] [typedCall] Sending payload', type, sanitizeDebugPayload(msg));
27211
28093
  }
27212
28094
  }
27213
28095
  catch (e) {
27214
28096
  }
27215
- const response = yield this._commonCall(type, msg);
28097
+ const response = yield this._commonCall(type, msg, options);
27216
28098
  try {
27217
28099
  assertType(response, resType);
27218
28100
  }
27219
28101
  catch (error) {
27220
- Log$b.debug('DeviceCommands typedcall error: ', error);
28102
+ Log$c.debug('DeviceCommands typedcall error: ', error);
27221
28103
  if (error instanceof hdShared.HardwareError) {
27222
28104
  if (error.errorCode === hdShared.HardwareErrorCode.ResponseUnexpectTypeError) {
28105
+ Log$c.debug('[DeviceCommands] [typedCall] Unexpected response type', {
28106
+ request: type,
28107
+ expected: resType,
28108
+ received: response.type,
28109
+ response: sanitizeDebugPayload(response.message),
28110
+ });
27223
28111
  if (error.message.indexOf('BridgeNetworkError') > -1) {
27224
28112
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BridgeNetworkError);
27225
28113
  }
@@ -27229,7 +28117,7 @@ class DeviceCommands {
27229
28117
  if (error.message.indexOf('BridgeDeviceDisconnected') > -1) {
27230
28118
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BridgeDeviceDisconnected);
27231
28119
  }
27232
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.ResponseUnexpectTypeError);
28120
+ throw error;
27233
28121
  }
27234
28122
  }
27235
28123
  else {
@@ -27239,19 +28127,21 @@ class DeviceCommands {
27239
28127
  return response;
27240
28128
  });
27241
28129
  }
27242
- _commonCall(type, msg) {
28130
+ _commonCall(type, msg, options) {
27243
28131
  return __awaiter(this, void 0, void 0, function* () {
27244
- const resp = yield this.call(type, msg);
27245
- return this._filterCommonTypes(resp, type);
28132
+ const resp = yield this.call(type, msg, options);
28133
+ return this._filterCommonTypes(resp, type, options);
27246
28134
  });
27247
28135
  }
27248
- _filterCommonTypes(res, callType) {
28136
+ _filterCommonTypes(res, callType, options) {
27249
28137
  try {
27250
- if (DataManager.getSettings('env') === 'react-native') {
27251
- Log$b.debug('_filterCommonTypes: ', JSON.stringify(res));
28138
+ if (shouldReduceDebugForCall(callType)) {
28139
+ }
28140
+ else if (DataManager.getSettings('env') === 'react-native') {
28141
+ Log$c.debug('_filterCommonTypes: ', JSON.stringify(sanitizeDebugPayload(res)));
27252
28142
  }
27253
28143
  else {
27254
- Log$b.debug('_filterCommonTypes: ', res);
28144
+ Log$c.debug('_filterCommonTypes: ', sanitizeDebugPayload(res));
27255
28145
  }
27256
28146
  }
27257
28147
  catch (error) {
@@ -27331,18 +28221,18 @@ class DeviceCommands {
27331
28221
  else {
27332
28222
  this.device.emit(DEVICE.BUTTON, this.device, res.message);
27333
28223
  }
27334
- return this._commonCall('ButtonAck', {});
28224
+ return this._commonCall('ButtonAck', {}, options);
27335
28225
  }
27336
28226
  if (res.type === 'EntropyRequest') ;
27337
28227
  if (res.type === 'PinMatrixRequest') {
27338
28228
  return this._promptPin(res.message.type).then(pin => {
27339
28229
  if (pin === '@@ONEKEY_INPUT_PIN_IN_DEVICE') {
27340
28230
  this.device.setCancelableAction(() => this.cancelDeviceOnOneKeyDevice());
27341
- return this._commonCall('BixinPinInputOnDevice').finally(() => {
28231
+ return this._commonCall('BixinPinInputOnDevice', {}, options).finally(() => {
27342
28232
  this.device.clearCancelableAction();
27343
28233
  });
27344
28234
  }
27345
- return this._commonCall('PinMatrixAck', { pin });
28235
+ return this._commonCall('PinMatrixAck', { pin }, options);
27346
28236
  }, error => Promise.reject(error));
27347
28237
  }
27348
28238
  if (res.type === 'PassphraseRequest') {
@@ -27352,11 +28242,11 @@ class DeviceCommands {
27352
28242
  }).then(response => {
27353
28243
  const { passphrase, passphraseOnDevice, attachPinOnDevice } = response;
27354
28244
  if (attachPinOnDevice && existsAttachPinUser) {
27355
- return this._commonCall('PassphraseAck', { on_device_attach_pin: true });
28245
+ return this._commonCall('PassphraseAck', { on_device_attach_pin: true }, options);
27356
28246
  }
27357
28247
  return !passphraseOnDevice
27358
- ? this._commonCall('PassphraseAck', { passphrase })
27359
- : this._commonCall('PassphraseAck', { on_device: true });
28248
+ ? this._commonCall('PassphraseAck', { passphrase }, options)
28249
+ : this._commonCall('PassphraseAck', { on_device: true }, options);
27360
28250
  });
27361
28251
  }
27362
28252
  if (res.type === 'Deprecated_PassphraseStateRequest') ;
@@ -27380,7 +28270,7 @@ class DeviceCommands {
27380
28270
  reject(error);
27381
28271
  });
27382
28272
  const listenerCount = this.device.listenerCount(DEVICE.PIN);
27383
- Log$b.debug(`[${this.instanceId}] _promptPin called`, {
28273
+ Log$c.debug(`[${this.instanceId}] _promptPin called`, {
27384
28274
  responseID: this.currentResponseID,
27385
28275
  deviceInstanceId: this.device.instanceId,
27386
28276
  listenerCount,
@@ -27447,12 +28337,178 @@ class DeviceCommands {
27447
28337
  }
27448
28338
  }
27449
28339
 
28340
+ const PROTOCOL_V2_DEVICE_INFO_REQUEST = {
28341
+ targets: {
28342
+ hw: true,
28343
+ fw: true,
28344
+ bt: true,
28345
+ se1: true,
28346
+ se2: true,
28347
+ se3: true,
28348
+ se4: true,
28349
+ status: true,
28350
+ },
28351
+ types: {
28352
+ version: true,
28353
+ build_id: true,
28354
+ hash: true,
28355
+ specific: true,
28356
+ },
28357
+ };
28358
+ function parseVersion(version) {
28359
+ if (!version)
28360
+ return [0, 0, 0];
28361
+ const [major = 0, minor = 0, patch = 0] = version.split('.').map(part => Number(part) || 0);
28362
+ return [major, minor, patch];
28363
+ }
28364
+ function bytesToHex$1(value) {
28365
+ if (!value)
28366
+ return undefined;
28367
+ if (typeof value === 'string')
28368
+ return value;
28369
+ if (value instanceof Uint8Array) {
28370
+ return Array.from(value)
28371
+ .map(byte => byte.toString(16).padStart(2, '0'))
28372
+ .join('');
28373
+ }
28374
+ if (Array.isArray(value)) {
28375
+ return value.map(byte => Number(byte).toString(16).padStart(2, '0')).join('');
28376
+ }
28377
+ return undefined;
28378
+ }
28379
+ function getDescriptorId(descriptor) {
28380
+ return descriptor.path || descriptor.id || '';
28381
+ }
28382
+ function getImageVersion(image) {
28383
+ return (image === null || image === void 0 ? void 0 : image.version) || undefined;
28384
+ }
28385
+ function getImageBuildId(image) {
28386
+ return (image === null || image === void 0 ? void 0 : image.build_id) || undefined;
28387
+ }
28388
+ function getImageHash(image) {
28389
+ return bytesToHex$1(image === null || image === void 0 ? void 0 : image.hash);
28390
+ }
28391
+ function getSeState(se) {
28392
+ switch (se === null || se === void 0 ? void 0 : se.state) {
28393
+ case 0:
28394
+ return 'BOOT';
28395
+ case 51:
28396
+ return 'APP_FACTORY';
28397
+ case 85:
28398
+ return 'APP';
28399
+ default:
28400
+ return null;
28401
+ }
28402
+ }
28403
+ function createBaseFeatures(descriptor) {
28404
+ const descriptorId = getDescriptorId(descriptor);
28405
+ return {
28406
+ vendor: 'onekey.so',
28407
+ major_version: 0,
28408
+ minor_version: 0,
28409
+ patch_version: 0,
28410
+ bootloader_mode: false,
28411
+ device_id: descriptorId,
28412
+ pin_protection: null,
28413
+ passphrase_protection: false,
28414
+ language: null,
28415
+ label: null,
28416
+ initialized: false,
28417
+ revision: null,
28418
+ bootloader_hash: null,
28419
+ imported: null,
28420
+ unlocked: false,
28421
+ firmware_present: false,
28422
+ needs_backup: null,
28423
+ flags: null,
28424
+ model: 'pro2',
28425
+ fw_major: 0,
28426
+ fw_minor: 0,
28427
+ fw_patch: 0,
28428
+ fw_vendor: null,
28429
+ unfinished_backup: null,
28430
+ no_backup: null,
28431
+ recovery_mode: null,
28432
+ capabilities: [],
28433
+ backup_type: null,
28434
+ sd_card_present: null,
28435
+ sd_protection: null,
28436
+ wipe_code_protection: null,
28437
+ session_id: null,
28438
+ passphrase_always_on_device: null,
28439
+ safety_checks: null,
28440
+ auto_lock_delay_ms: null,
28441
+ display_rotation: null,
28442
+ experimental_features: null,
28443
+ onekey_device_type: hdShared.EDeviceType.Pro2,
28444
+ onekey_serial_no: descriptorId,
28445
+ serial_no: descriptorId,
28446
+ };
28447
+ }
28448
+ function normalizeProtocolV2Features(descriptor, deviceInfo) {
28449
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
28450
+ const features = createBaseFeatures(descriptor);
28451
+ if (!deviceInfo)
28452
+ return features;
28453
+ const serialNo = ((_a = deviceInfo.hw) === null || _a === void 0 ? void 0 : _a.serial_no) || features.onekey_serial_no || getDescriptorId(descriptor);
28454
+ const firmwareVersion = getImageVersion((_b = deviceInfo.fw) === null || _b === void 0 ? void 0 : _b.app);
28455
+ const [fwMajor, fwMinor, fwPatch] = parseVersion(firmwareVersion);
28456
+ return Object.assign(Object.assign({}, features), { major_version: fwMajor, minor_version: fwMinor, patch_version: fwPatch, fw_major: fwMajor, fw_minor: fwMinor, fw_patch: fwPatch, device_id: serialNo, serial_no: serialNo, onekey_serial_no: serialNo, label: (_d = (_c = deviceInfo.status) === null || _c === void 0 ? void 0 : _c.label) !== null && _d !== void 0 ? _d : features.label, language: (_f = (_e = deviceInfo.status) === null || _e === void 0 ? void 0 : _e.language) !== null && _f !== void 0 ? _f : features.language, initialized: (_h = (_g = deviceInfo.status) === null || _g === void 0 ? void 0 : _g.init_states) !== null && _h !== void 0 ? _h : features.initialized, passphrase_protection: (_k = (_j = deviceInfo.status) === null || _j === void 0 ? void 0 : _j.passphrase_protection) !== null && _k !== void 0 ? _k : features.passphrase_protection, needs_backup: (_m = (_l = deviceInfo.status) === null || _l === void 0 ? void 0 : _l.backup_required) !== null && _m !== void 0 ? _m : features.needs_backup, ble_enable: (_o = deviceInfo.status) === null || _o === void 0 ? void 0 : _o.bt_enable, onekey_ble_name: (_p = deviceInfo.bt) === null || _p === void 0 ? void 0 : _p.adv_name, ble_name: (_q = deviceInfo.bt) === null || _q === void 0 ? void 0 : _q.adv_name, onekey_firmware_version: firmwareVersion, onekey_firmware_build_id: getImageBuildId((_r = deviceInfo.fw) === null || _r === void 0 ? void 0 : _r.app), onekey_firmware_hash: getImageHash((_s = deviceInfo.fw) === null || _s === void 0 ? void 0 : _s.app), onekey_boot_version: getImageVersion((_t = deviceInfo.fw) === null || _t === void 0 ? void 0 : _t.boot), bootloader_version: getImageVersion((_u = deviceInfo.fw) === null || _u === void 0 ? void 0 : _u.boot), onekey_boot_build_id: getImageBuildId((_v = deviceInfo.fw) === null || _v === void 0 ? void 0 : _v.boot), onekey_boot_hash: getImageHash((_w = deviceInfo.fw) === null || _w === void 0 ? void 0 : _w.boot), onekey_board_version: getImageVersion((_x = deviceInfo.fw) === null || _x === void 0 ? void 0 : _x.board), onekey_board_hash: getImageHash((_y = deviceInfo.fw) === null || _y === void 0 ? void 0 : _y.board), onekey_ble_version: getImageVersion((_z = deviceInfo.bt) === null || _z === void 0 ? void 0 : _z.app), ble_ver: getImageVersion((_0 = deviceInfo.bt) === null || _0 === void 0 ? void 0 : _0.app), onekey_ble_build_id: getImageBuildId((_1 = deviceInfo.bt) === null || _1 === void 0 ? void 0 : _1.app), onekey_ble_hash: getImageHash((_2 = deviceInfo.bt) === null || _2 === void 0 ? void 0 : _2.app), onekey_se01_version: getImageVersion((_3 = deviceInfo.se1) === null || _3 === void 0 ? void 0 : _3.app), onekey_se01_hash: getImageHash((_4 = deviceInfo.se1) === null || _4 === void 0 ? void 0 : _4.app), onekey_se01_build_id: getImageBuildId((_5 = deviceInfo.se1) === null || _5 === void 0 ? void 0 : _5.app), onekey_se01_state: getSeState(deviceInfo.se1), onekey_se02_version: getImageVersion((_6 = deviceInfo.se2) === null || _6 === void 0 ? void 0 : _6.app), onekey_se02_state: getSeState(deviceInfo.se2), onekey_se03_version: getImageVersion((_7 = deviceInfo.se3) === null || _7 === void 0 ? void 0 : _7.app), onekey_se03_state: getSeState(deviceInfo.se3), onekey_se04_version: getImageVersion((_8 = deviceInfo.se4) === null || _8 === void 0 ? void 0 : _8.app), onekey_se04_state: getSeState(deviceInfo.se4) });
28457
+ }
28458
+ function getProtocolV2Features({ commands, descriptor, onDeviceInfoError, timeoutMs, }) {
28459
+ return __awaiter(this, void 0, void 0, function* () {
28460
+ const callOptions = timeoutMs ? { timeoutMs } : undefined;
28461
+ if (callOptions) {
28462
+ yield commands.typedCall('Ping', 'Success', { message: 'init' }, callOptions);
28463
+ }
28464
+ else {
28465
+ yield commands.typedCall('Ping', 'Success', { message: 'init' });
28466
+ }
28467
+ try {
28468
+ const { message } = callOptions
28469
+ ? yield commands.typedCall('DevGetDeviceInfo', 'DeviceInfo', PROTOCOL_V2_DEVICE_INFO_REQUEST, callOptions)
28470
+ : yield commands.typedCall('DevGetDeviceInfo', 'DeviceInfo', PROTOCOL_V2_DEVICE_INFO_REQUEST);
28471
+ return normalizeProtocolV2Features(descriptor, message);
28472
+ }
28473
+ catch (error) {
28474
+ onDeviceInfoError === null || onDeviceInfoError === void 0 ? void 0 : onDeviceInfoError(error);
28475
+ throw error;
28476
+ }
28477
+ });
28478
+ }
28479
+
28480
+ const ProtocolV2FirmwareTargetType = {
28481
+ TARGET_MAIN_APP: 0,
28482
+ TARGET_MAIN_BOOT: 1,
28483
+ TARGET_BT: 2,
28484
+ TARGET_SE1: 3,
28485
+ TARGET_SE2: 4,
28486
+ TARGET_SE3: 5,
28487
+ TARGET_SE4: 6,
28488
+ TARGET_RESOURCE: 10,
28489
+ };
28490
+ function protocolV2FileNameToTargetId(fileName) {
28491
+ if (fileName.includes('ble'))
28492
+ return ProtocolV2FirmwareTargetType.TARGET_BT;
28493
+ if (fileName.includes('bootloader'))
28494
+ return ProtocolV2FirmwareTargetType.TARGET_MAIN_BOOT;
28495
+ if (fileName.includes('se1'))
28496
+ return ProtocolV2FirmwareTargetType.TARGET_SE1;
28497
+ if (fileName.includes('se2'))
28498
+ return ProtocolV2FirmwareTargetType.TARGET_SE2;
28499
+ if (fileName.includes('se3'))
28500
+ return ProtocolV2FirmwareTargetType.TARGET_SE3;
28501
+ if (fileName.includes('se4'))
28502
+ return ProtocolV2FirmwareTargetType.TARGET_SE4;
28503
+ return ProtocolV2FirmwareTargetType.TARGET_MAIN_APP;
28504
+ }
28505
+
27450
28506
  const parseRunOptions = (options) => {
27451
28507
  if (!options)
27452
28508
  options = {};
27453
28509
  return options;
27454
28510
  };
27455
- const Log$a = getLogger(exports.LoggerNames.Device);
28511
+ const Log$b = getLogger(exports.LoggerNames.Device);
27456
28512
  const deviceSessionCache = {};
27457
28513
  function preloadSessionCache(deviceId, passphraseState, sessionId) {
27458
28514
  const key = `${deviceId}@${passphraseState}`;
@@ -27476,7 +28532,7 @@ class Device extends events.exports {
27476
28532
  this.sdkInstanceId = sdkInstanceId;
27477
28533
  this.instanceId = generateInstanceId('Device', this.sdkInstanceId);
27478
28534
  this.createdAt = Date.now();
27479
- Log$a.debug(`[Device] Created: ${this.instanceId}${this.sdkInstanceId ? ` for SDK: ${this.sdkInstanceId}` : ''}`);
28535
+ Log$b.debug(`[Device] Created: ${this.instanceId}${this.sdkInstanceId ? ` for SDK: ${this.sdkInstanceId}` : ''}`);
27480
28536
  }
27481
28537
  static fromDescriptor(originalDescriptor, sdkInstanceId) {
27482
28538
  const descriptor = Object.assign({}, originalDescriptor);
@@ -27510,12 +28566,12 @@ class Device extends events.exports {
27510
28566
  unavailableCapabilities: this.unavailableCapabilities,
27511
28567
  };
27512
28568
  }
27513
- connect() {
28569
+ connect(connectProtocol) {
27514
28570
  const env = DataManager.getSettings('env');
27515
28571
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
27516
28572
  if (DataManager.isBleConnect(env)) {
27517
28573
  try {
27518
- yield this.acquire();
28574
+ yield this.acquire(connectProtocol);
27519
28575
  resolve(true);
27520
28576
  }
27521
28577
  catch (error) {
@@ -27525,7 +28581,7 @@ class Device extends events.exports {
27525
28581
  }
27526
28582
  if (!this.mainId || (!this.isUsedHere() && this.originalDescriptor)) {
27527
28583
  try {
27528
- yield this.acquire();
28584
+ yield this.acquire(connectProtocol);
27529
28585
  resolve(true);
27530
28586
  }
27531
28587
  catch (error) {
@@ -27540,27 +28596,32 @@ class Device extends events.exports {
27540
28596
  resolve(false);
27541
28597
  }));
27542
28598
  }
27543
- acquire() {
27544
- var _a, _b, _c, _d;
28599
+ acquire(connectProtocol) {
28600
+ var _a, _b, _c, _d, _e, _f;
27545
28601
  return __awaiter(this, void 0, void 0, function* () {
27546
28602
  const env = DataManager.getSettings('env');
27547
28603
  const mainIdKey = DataManager.isBleConnect(env) ? 'id' : 'session';
28604
+ const expectedProtocol = connectProtocol !== null && connectProtocol !== void 0 ? connectProtocol : this.originalDescriptor.protocolType;
27548
28605
  try {
27549
28606
  if (DataManager.isBleConnect(env)) {
27550
- const res = yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.originalDescriptor.id));
28607
+ const res = yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.originalDescriptor.id, undefined, true, expectedProtocol));
27551
28608
  this.mainId = (_b = res.uuid) !== null && _b !== void 0 ? _b : '';
27552
- Log$a.debug('Expected uuid:', this.mainId);
28609
+ Log$b.debug('Expected uuid:', this.mainId);
27553
28610
  }
27554
28611
  else {
27555
- this.mainId = yield ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.originalDescriptor.path, this.originalDescriptor.session));
27556
- Log$a.debug('Expected session id:', this.mainId);
28612
+ this.mainId = yield ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.originalDescriptor.path, this.originalDescriptor.session, undefined, expectedProtocol));
28613
+ Log$b.debug('Expected session id:', this.mainId);
27557
28614
  }
27558
28615
  this.deviceAcquired = true;
27559
28616
  this.updateDescriptor({ [mainIdKey]: this.mainId });
28617
+ const detectedProtocol = (_e = (_d = TransportManager.transport) === null || _d === void 0 ? void 0 : _d.getProtocolType) === null || _e === void 0 ? void 0 : _e.call(_d, DataManager.isBleConnect(env) ? this.originalDescriptor.id : this.originalDescriptor.path);
28618
+ if (detectedProtocol) {
28619
+ this.originalDescriptor.protocolType = detectedProtocol;
28620
+ }
27560
28621
  if (this.commands) {
27561
28622
  yield this.commands.dispose(false);
27562
28623
  }
27563
- this.commands = new DeviceCommands(this, (_d = this.mainId) !== null && _d !== void 0 ? _d : '');
28624
+ this.commands = new DeviceCommands(this, (_f = this.mainId) !== null && _f !== void 0 ? _f : '');
27564
28625
  }
27565
28626
  catch (error) {
27566
28627
  if (this.runPromise) {
@@ -27581,11 +28642,11 @@ class Device extends events.exports {
27581
28642
  (this.mainId && DataManager.isBleConnect(env))) {
27582
28643
  if (this.pendingCallbackPromise) {
27583
28644
  try {
27584
- Log$a.debug('Waiting for callback tasks to complete before releasing device (in release method)');
28645
+ Log$b.debug('Waiting for callback tasks to complete before releasing device (in release method)');
27585
28646
  yield this.pendingCallbackPromise.promise;
27586
28647
  }
27587
28648
  catch (error) {
27588
- Log$a.error('Error waiting for callback tasks in release method:', error);
28649
+ Log$b.error('Error waiting for callback tasks in release method:', error);
27589
28650
  }
27590
28651
  }
27591
28652
  if (this.commands) {
@@ -27604,7 +28665,7 @@ class Device extends events.exports {
27604
28665
  this.updateDescriptor({ session: null });
27605
28666
  }
27606
28667
  catch (err) {
27607
- Log$a.error('[Device] release error: ', err);
28668
+ Log$b.error('[Device] release error: ', err);
27608
28669
  }
27609
28670
  finally {
27610
28671
  this.needReloadDevice = true;
@@ -27624,8 +28685,8 @@ class Device extends events.exports {
27624
28685
  }
27625
28686
  getInternalState(_deviceId) {
27626
28687
  var _a, _b;
27627
- Log$a.debug('getInternalState session cache: ', deviceSessionCache);
27628
- Log$a.debug('getInternalState session param: ', `device_id: ${_deviceId}`, `features.device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
28688
+ Log$b.debug('getInternalState session cache: ', deviceSessionCache);
28689
+ Log$b.debug('getInternalState session param: ', `device_id: ${_deviceId}`, `features.device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
27629
28690
  const deviceId = _deviceId || ((_b = this.features) === null || _b === void 0 ? void 0 : _b.device_id);
27630
28691
  if (!deviceId)
27631
28692
  return undefined;
@@ -27635,7 +28696,7 @@ class Device extends events.exports {
27635
28696
  return deviceSessionCache[usePassKey];
27636
28697
  }
27637
28698
  updateInternalState(enablePassphrase, passphraseState, deviceId, sessionId = null, featuresSessionId = null) {
27638
- Log$a.debug('updateInternalState session param: ', `device_id: ${deviceId}`, `enablePassphrase: ${enablePassphrase}`, `passphraseState: ${passphraseState}`, `sessionId: ${sessionId}`, `featuresSessionId: ${featuresSessionId}`);
28699
+ Log$b.debug('updateInternalState session param: ', `device_id: ${deviceId}`, `enablePassphrase: ${enablePassphrase}`, `passphraseState: ${passphraseState}`, `sessionId: ${sessionId}`, `featuresSessionId: ${featuresSessionId}`);
27639
28700
  if (enablePassphrase) {
27640
28701
  if (sessionId) {
27641
28702
  deviceSessionCache[this.generateStateKey(deviceId, passphraseState)] = sessionId;
@@ -27648,11 +28709,11 @@ class Device extends events.exports {
27648
28709
  if (deviceSessionCache[oldKey]) {
27649
28710
  delete deviceSessionCache[oldKey];
27650
28711
  }
27651
- Log$a.debug('updateInternalState session cache: ', deviceSessionCache);
28712
+ Log$b.debug('updateInternalState session cache: ', deviceSessionCache);
27652
28713
  }
27653
28714
  setInternalState(state, initSession) {
27654
28715
  var _a, _b;
27655
- Log$a.debug('setInternalState session param: ', `state: ${state}`, `initSession: ${initSession}`, `device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
28716
+ Log$b.debug('setInternalState session param: ', `state: ${state}`, `initSession: ${initSession}`, `device_id: ${(_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id}`, `passphraseState: ${this.passphraseState}`);
27656
28717
  if (!this.features)
27657
28718
  return;
27658
28719
  if (!this.passphraseState && !initSession)
@@ -27664,11 +28725,11 @@ class Device extends events.exports {
27664
28725
  if (state) {
27665
28726
  deviceSessionCache[key] = state;
27666
28727
  }
27667
- Log$a.debug('setInternalState done session cache: ', deviceSessionCache);
28728
+ Log$b.debug('setInternalState done session cache: ', deviceSessionCache);
27668
28729
  }
27669
28730
  clearInternalState(_deviceId) {
27670
28731
  var _a;
27671
- Log$a.debug('clearInternalState param: ', _deviceId);
28732
+ Log$b.debug('clearInternalState param: ', _deviceId);
27672
28733
  const deviceId = _deviceId || ((_a = this.features) === null || _a === void 0 ? void 0 : _a.device_id);
27673
28734
  if (!deviceId)
27674
28735
  return;
@@ -27681,6 +28742,10 @@ class Device extends events.exports {
27681
28742
  }
27682
28743
  initialize(options) {
27683
28744
  return __awaiter(this, void 0, void 0, function* () {
28745
+ if (this.originalDescriptor.protocolType === 'V2') {
28746
+ yield this._initializeProtocolV2();
28747
+ return;
28748
+ }
27684
28749
  this.passphraseState = options === null || options === void 0 ? void 0 : options.passphraseState;
27685
28750
  if (options === null || options === void 0 ? void 0 : options.initSession) {
27686
28751
  this.clearInternalState(options === null || options === void 0 ? void 0 : options.deviceId);
@@ -27695,7 +28760,7 @@ class Device extends events.exports {
27695
28760
  }
27696
28761
  payload.passphrase_state = options === null || options === void 0 ? void 0 : options.passphraseState;
27697
28762
  payload.is_contains_attach = true;
27698
- Log$a.debug('Initialize device begin:', {
28763
+ Log$b.debug('Initialize device begin:', {
27699
28764
  deviceId: options === null || options === void 0 ? void 0 : options.deviceId,
27700
28765
  passphraseState: options === null || options === void 0 ? void 0 : options.passphraseState,
27701
28766
  initSession: options === null || options === void 0 ? void 0 : options.initSession,
@@ -27710,12 +28775,40 @@ class Device extends events.exports {
27710
28775
  }, 25 * 1000);
27711
28776
  }),
27712
28777
  ]);
27713
- Log$a.debug('Initialize device end: ', message);
28778
+ Log$b.debug('Initialize device end: ', message);
27714
28779
  this._updateFeatures(message, options === null || options === void 0 ? void 0 : options.initSession);
27715
28780
  yield TransportManager.reconfigure(this.features);
27716
28781
  }
27717
28782
  catch (error) {
27718
- Log$a.error('Initialization failed:', error);
28783
+ Log$b.error('Initialization failed:', error);
28784
+ throw error;
28785
+ }
28786
+ });
28787
+ }
28788
+ _initializeProtocolV2() {
28789
+ return __awaiter(this, void 0, void 0, function* () {
28790
+ Log$b.debug('Initialize device via Protocol V2 feature adapter');
28791
+ try {
28792
+ const features = yield Promise.race([
28793
+ getProtocolV2Features({
28794
+ commands: this.commands,
28795
+ descriptor: this.originalDescriptor,
28796
+ onDeviceInfoError: error => {
28797
+ Log$b.debug('Protocol V2 DevGetDeviceInfo failed:', error);
28798
+ },
28799
+ timeoutMs: 10 * 1000,
28800
+ }),
28801
+ new Promise((_, reject) => {
28802
+ setTimeout(() => {
28803
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInitializeFailed));
28804
+ }, 10 * 1000);
28805
+ }),
28806
+ ]);
28807
+ Log$b.debug('Protocol V2 normalized features:', features);
28808
+ this._updateFeatures(features);
28809
+ }
28810
+ catch (error) {
28811
+ Log$b.error('Protocol V2 initialization failed:', error);
27719
28812
  throw error;
27720
28813
  }
27721
28814
  });
@@ -27766,7 +28859,7 @@ class Device extends events.exports {
27766
28859
  return __awaiter(this, void 0, void 0, function* () {
27767
28860
  if (this.runPromise) {
27768
28861
  yield this.interruptionFromOutside();
27769
- Log$a.debug('[Device] run error:', 'Device is running, but will cancel previous operate');
28862
+ Log$b.debug('[Device] run error:', 'Device is running, but will cancel previous operate');
27770
28863
  }
27771
28864
  options = parseRunOptions(options);
27772
28865
  this.runPromise = hdShared.createDeferred(this._runInner.bind(this, fn, options));
@@ -27780,7 +28873,7 @@ class Device extends events.exports {
27780
28873
  const env = DataManager.getSettings('env');
27781
28874
  if (env !== 'react-native') {
27782
28875
  try {
27783
- yield this.acquire();
28876
+ yield this.acquire(options.connectProtocol);
27784
28877
  }
27785
28878
  catch (error) {
27786
28879
  this.runPromise = null;
@@ -27822,7 +28915,7 @@ class Device extends events.exports {
27822
28915
  yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.disconnect(this.mainId));
27823
28916
  }
27824
28917
  yield this.release();
27825
- Log$a.debug(`error code ${e.errorCode} release device, mainId: ${this.mainId}`);
28918
+ Log$b.debug(`error code ${e.errorCode} release device, mainId: ${this.mainId}`);
27826
28919
  }
27827
28920
  this.runPromise = null;
27828
28921
  return;
@@ -27832,7 +28925,7 @@ class Device extends events.exports {
27832
28925
  options.keepSession === false) {
27833
28926
  this.keepSession = false;
27834
28927
  yield this.release();
27835
- Log$a.debug('release device, mainId: ', this.mainId);
28928
+ Log$b.debug('release device, mainId: ', this.mainId);
27836
28929
  }
27837
28930
  if (this.runPromise) {
27838
28931
  this.runPromise.resolve();
@@ -27865,7 +28958,7 @@ class Device extends events.exports {
27865
28958
  setCancelableAction(callback) {
27866
28959
  this.cancelableAction = (e) => callback(e)
27867
28960
  .catch(e2 => {
27868
- Log$a.debug('cancelableAction error', e2);
28961
+ Log$b.debug('cancelableAction error', e2);
27869
28962
  })
27870
28963
  .finally(() => {
27871
28964
  this.clearCancelableAction();
@@ -28020,7 +29113,7 @@ class Device extends events.exports {
28020
29113
  }
28021
29114
  const mainWalletUseAttachPin = unlockedAttachPin && useEmptyPassphrase;
28022
29115
  const useErrorAttachPin = unlockedAttachPin && passphraseState && passphraseState !== newPassphraseState;
28023
- Log$a.debug('Check passphrase state safety: ', {
29116
+ Log$b.debug('Check passphrase state safety: ', {
28024
29117
  passphraseState,
28025
29118
  newPassphraseState,
28026
29119
  unlockedAttachPin,
@@ -28120,7 +29213,7 @@ const getBootloaderReleaseInfo = ({ features, willUpdateFirmwareVersion, firmwar
28120
29213
  };
28121
29214
  };
28122
29215
 
28123
- const Log$9 = getLogger(exports.LoggerNames.Method);
29216
+ const Log$a = getLogger(exports.LoggerNames.Method);
28124
29217
  class BaseMethod {
28125
29218
  constructor(message) {
28126
29219
  this.shouldEnsureConnected = true;
@@ -28150,7 +29243,7 @@ class BaseMethod {
28150
29243
  setContext(context) {
28151
29244
  this.sdkInstanceId = context.sdkInstanceId;
28152
29245
  this.instanceId = generateInstanceId('Method', this.sdkInstanceId);
28153
- Log$9.debug(`[BaseMethod] Created: ${this.instanceId}, method: ${this.name}, SDK: ${this.sdkInstanceId}`);
29246
+ Log$a.debug(`[BaseMethod] Created: ${this.instanceId}, method: ${this.name}, SDK: ${this.sdkInstanceId}`);
28154
29247
  }
28155
29248
  setDevice(device) {
28156
29249
  var _a, _b;
@@ -28170,7 +29263,7 @@ class BaseMethod {
28170
29263
  if (device.commands) {
28171
29264
  device.commands.currentResponseID = this.responseID;
28172
29265
  }
28173
- Log$9.debug(`[${this.instanceId}] setDevice: ${device.instanceId}, commands: ${(_b = device.commands) === null || _b === void 0 ? void 0 : _b.instanceId}`);
29266
+ Log$a.debug(`[${this.instanceId}] setDevice: ${device.instanceId}, commands: ${(_b = device.commands) === null || _b === void 0 ? void 0 : _b.instanceId}`);
28174
29267
  }
28175
29268
  checkFirmwareRelease() {
28176
29269
  if (!this.device || !this.device.features)
@@ -28223,7 +29316,7 @@ class BaseMethod {
28223
29316
  checkFlag = true;
28224
29317
  }
28225
29318
  if (checkFlag && ((_c = this.device.features) === null || _c === void 0 ? void 0 : _c.safety_checks) === 'Strict') {
28226
- Log$9.debug('will change safety_checks level');
29319
+ Log$a.debug('will change safety_checks level');
28227
29320
  yield this.device.commands.typedCall('ApplySettings', 'Success', {
28228
29321
  safety_checks: 'PromptTemporarily',
28229
29322
  });
@@ -28261,7 +29354,7 @@ class SearchDevices extends BaseMethod {
28261
29354
  this.skipForceUpdateCheck = true;
28262
29355
  }
28263
29356
  run() {
28264
- var _a, _b, _c, _d;
29357
+ var _a, _b, _c, _d, _e;
28265
29358
  return __awaiter(this, void 0, void 0, function* () {
28266
29359
  yield TransportManager.configure();
28267
29360
  const deviceDiff = yield ((_a = this.connector) === null || _a === void 0 ? void 0 : _a.enumerate());
@@ -28274,12 +29367,15 @@ class SearchDevices extends BaseMethod {
28274
29367
  const lowerId = (_c = device.id) === null || _c === void 0 ? void 0 : _c.toLowerCase();
28275
29368
  if (!seenIds.has(lowerId)) {
28276
29369
  seenIds.add(lowerId);
28277
- devices.push(Object.assign(Object.assign({}, device), { connectId: device.id, deviceType: getDeviceTypeByBleName((_d = device.name) !== null && _d !== void 0 ? _d : '') }));
29370
+ const bleName = (_e = (_d = device.name) !== null && _d !== void 0 ? _d : device.localName) !== null && _e !== void 0 ? _e : '';
29371
+ devices.push(Object.assign(Object.assign({}, device), { connectId: device.id, name: bleName || device.name, deviceType: getDeviceTypeByBleName(bleName) }));
28278
29372
  }
28279
29373
  }
28280
29374
  return devices;
28281
29375
  }
28282
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor);
29376
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined, {
29377
+ connectProtocol: this.payload.connectProtocol,
29378
+ });
28283
29379
  return deviceList.map(device => device.toMessageObject());
28284
29380
  });
28285
29381
  }
@@ -28304,6 +29400,70 @@ class GetFeatures extends BaseMethod {
28304
29400
  }
28305
29401
  }
28306
29402
 
29403
+ const ONEKEY_FEATURE_KEYS = [
29404
+ 'onekey_device_type',
29405
+ 'onekey_board_version',
29406
+ 'onekey_boot_version',
29407
+ 'onekey_firmware_version',
29408
+ 'onekey_board_hash',
29409
+ 'onekey_boot_hash',
29410
+ 'onekey_firmware_hash',
29411
+ 'onekey_board_build_id',
29412
+ 'onekey_boot_build_id',
29413
+ 'onekey_firmware_build_id',
29414
+ 'onekey_serial_no',
29415
+ 'onekey_ble_name',
29416
+ 'onekey_ble_version',
29417
+ 'onekey_ble_build_id',
29418
+ 'onekey_ble_hash',
29419
+ 'onekey_se_type',
29420
+ 'onekey_se01_state',
29421
+ 'onekey_se02_state',
29422
+ 'onekey_se03_state',
29423
+ 'onekey_se04_state',
29424
+ 'onekey_se01_version',
29425
+ 'onekey_se02_version',
29426
+ 'onekey_se03_version',
29427
+ 'onekey_se04_version',
29428
+ 'onekey_se01_hash',
29429
+ 'onekey_se02_hash',
29430
+ 'onekey_se03_hash',
29431
+ 'onekey_se04_hash',
29432
+ 'onekey_se01_build_id',
29433
+ 'onekey_se02_build_id',
29434
+ 'onekey_se03_build_id',
29435
+ 'onekey_se04_build_id',
29436
+ 'onekey_se01_boot_version',
29437
+ 'onekey_se02_boot_version',
29438
+ 'onekey_se03_boot_version',
29439
+ 'onekey_se04_boot_version',
29440
+ 'onekey_se01_boot_hash',
29441
+ 'onekey_se02_boot_hash',
29442
+ 'onekey_se03_boot_hash',
29443
+ 'onekey_se04_boot_hash',
29444
+ 'onekey_se01_boot_build_id',
29445
+ 'onekey_se02_boot_build_id',
29446
+ 'onekey_se03_boot_build_id',
29447
+ 'onekey_se04_boot_build_id',
29448
+ ];
29449
+ function normalizeOnekeyFirmwareVersion(message) {
29450
+ if (message.onekey_firmware_version && !semver__default["default"].valid(message.onekey_firmware_version)) {
29451
+ message.onekey_firmware_version = fixVersion(message.onekey_firmware_version);
29452
+ }
29453
+ }
29454
+ function pickOnekeyFeatures(features) {
29455
+ const message = {};
29456
+ if (!features)
29457
+ return message;
29458
+ for (const key of ONEKEY_FEATURE_KEYS) {
29459
+ const value = features[key];
29460
+ if (value !== undefined && value !== null) {
29461
+ message[key] = value;
29462
+ }
29463
+ }
29464
+ normalizeOnekeyFirmwareVersion(message);
29465
+ return message;
29466
+ }
28307
29467
  class GetOnekeyFeatures extends BaseMethod {
28308
29468
  init() {
28309
29469
  this.allowDeviceMode = [
@@ -28315,11 +29475,13 @@ class GetOnekeyFeatures extends BaseMethod {
28315
29475
  this.skipForceUpdateCheck = true;
28316
29476
  }
28317
29477
  run() {
29478
+ var _a;
28318
29479
  return __awaiter(this, void 0, void 0, function* () {
28319
- const { message } = yield this.device.commands.typedCall('OnekeyGetFeatures', 'OnekeyFeatures');
28320
- if (!!message.onekey_firmware_version && !semver__default["default"].valid(message.onekey_firmware_version)) {
28321
- message.onekey_firmware_version = fixVersion(message.onekey_firmware_version);
29480
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
29481
+ return Promise.resolve(pickOnekeyFeatures(this.device.features));
28322
29482
  }
29483
+ const { message } = yield this.device.commands.typedCall('OnekeyGetFeatures', 'OnekeyFeatures');
29484
+ normalizeOnekeyFirmwareVersion(message);
28323
29485
  return Promise.resolve(message);
28324
29486
  });
28325
29487
  }
@@ -28864,7 +30026,14 @@ class DeviceRebootToBootloader extends BaseMethod {
28864
30026
  };
28865
30027
  }
28866
30028
  run() {
30029
+ var _a;
28867
30030
  return __awaiter(this, void 0, void 0, function* () {
30031
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
30032
+ const res = yield this.device.commands.typedCall('DevReboot', 'Success', {
30033
+ reboot_type: hdTransport.DevRebootType.Bootloader,
30034
+ });
30035
+ return Promise.resolve(res.message);
30036
+ }
28868
30037
  const res = yield this.device.commands.typedCall('RebootToBootloader', 'Success');
28869
30038
  return Promise.resolve(res.message);
28870
30039
  });
@@ -28887,7 +30056,14 @@ class DeviceRebootToBoardloader extends BaseMethod {
28887
30056
  };
28888
30057
  }
28889
30058
  run() {
30059
+ var _a;
28890
30060
  return __awaiter(this, void 0, void 0, function* () {
30061
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
30062
+ const res = yield this.device.commands.typedCall('DevReboot', 'Success', {
30063
+ reboot_type: hdTransport.DevRebootType.Boardloader,
30064
+ });
30065
+ return Promise.resolve(res.message);
30066
+ }
28891
30067
  const res = yield this.device.commands.typedCall('BixinOutMessageSE', 'Success');
28892
30068
  return Promise.resolve(res.message);
28893
30069
  });
@@ -29327,10 +30503,10 @@ const getInfo = ({ features, updateType, targetVersion, firmwareType }) => {
29327
30503
  };
29328
30504
 
29329
30505
  const NEW_BOOT_UPRATE_FIRMWARE_VERSION = '2.4.5';
29330
- const SESSION_ERROR$1 = 'session not found';
30506
+ const SESSION_ERROR$2 = 'session not found';
29331
30507
  const FIRMWARE_UPDATE_CONFIRM$1 = 'Firmware install confirmed';
29332
- const Log$8 = getLogger(exports.LoggerNames.Method);
29333
- const isDeviceDisconnectedError$1 = (error) => {
30508
+ const Log$9 = getLogger(exports.LoggerNames.Method);
30509
+ const isDeviceDisconnectedError$2 = (error) => {
29334
30510
  const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
29335
30511
  return (message.includes('device was disconnected') ||
29336
30512
  message.includes('transferIn') ||
@@ -29378,13 +30554,13 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
29378
30554
  const newFeatures = yield typedCall('GetFeatures', 'Features', {});
29379
30555
  const deviceBootloaderVersion = getDeviceBootloaderVersion(newFeatures.message).join('.');
29380
30556
  const supportUpgradeFileHeader = semver__default["default"].gte(deviceBootloaderVersion, '2.1.0');
29381
- Log$8.debug('supportUpgradeFileHeader:', supportUpgradeFileHeader);
30557
+ Log$9.debug('supportUpgradeFileHeader:', supportUpgradeFileHeader);
29382
30558
  if (supportUpgradeFileHeader) {
29383
30559
  const HEADER_SIZE = 1024;
29384
30560
  if (payload.byteLength < HEADER_SIZE) {
29385
30561
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `firmware payload too small: ${payload.byteLength} bytes, expected at least ${HEADER_SIZE} bytes`);
29386
30562
  }
29387
- Log$8.debug('Uploading firmware header:', {
30563
+ Log$9.debug('Uploading firmware header:', {
29388
30564
  size: HEADER_SIZE,
29389
30565
  totalSize: payload.byteLength,
29390
30566
  });
@@ -29396,18 +30572,18 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
29396
30572
  });
29397
30573
  const isUnknownMessage = (_b = (_a = headerRes.message) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.includes('Failure_UnknownMessage');
29398
30574
  if (headerRes.type !== 'Success' && !isUnknownMessage) {
29399
- Log$8.error('Firmware header upload failed:', headerRes);
30575
+ Log$9.error('Firmware header upload failed:', headerRes);
29400
30576
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'failed to upload firmware header');
29401
30577
  }
29402
30578
  }
29403
30579
  catch (error) {
29404
- Log$8.error('Firmware header upload failed:', error);
30580
+ Log$9.error('Firmware header upload failed:', error);
29405
30581
  const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
29406
30582
  if (!message.includes('Failure_UnknownMessage')) {
29407
30583
  throw error;
29408
30584
  }
29409
30585
  }
29410
- Log$8.debug('Firmware header uploaded successfully');
30586
+ Log$9.debug('Firmware header uploaded successfully');
29411
30587
  }
29412
30588
  }
29413
30589
  const eraseCommand = isFirmware ? 'FirmwareErase' : 'FirmwareErase_ex';
@@ -29424,8 +30600,8 @@ const uploadFirmware = (updateType, typedCall, postMessage, device, { payload, r
29424
30600
  });
29425
30601
  }
29426
30602
  catch (error) {
29427
- if (isDeviceDisconnectedError$1(error)) {
29428
- Log$8.log('Rebooting device');
30603
+ if (isDeviceDisconnectedError$2(error)) {
30604
+ Log$9.log('Rebooting device');
29429
30605
  updateResponse = {
29430
30606
  type: 'Success',
29431
30607
  message: { message: FIRMWARE_UPDATE_CONFIRM$1 },
@@ -29510,8 +30686,8 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
29510
30686
  });
29511
30687
  }
29512
30688
  catch (error) {
29513
- if (isDeviceDisconnectedError$1(error)) {
29514
- Log$8.log('Rebooting device');
30689
+ if (isDeviceDisconnectedError$2(error)) {
30690
+ Log$9.log('Rebooting device');
29515
30691
  response = {
29516
30692
  type: 'Success',
29517
30693
  message: { message: FIRMWARE_UPDATE_CONFIRM$1 },
@@ -29542,7 +30718,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
29542
30718
  ]);
29543
30719
  }
29544
30720
  catch (e) {
29545
- Log$8.log('catch Bluetooth error when device is restarting: ', e);
30721
+ Log$9.log('catch Bluetooth error when device is restarting: ', e);
29546
30722
  }
29547
30723
  }
29548
30724
  else {
@@ -29563,7 +30739,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
29563
30739
  }
29564
30740
  catch (error) {
29565
30741
  console.error('Device reconnect failed: ', error);
29566
- Log$8.error('Device reconnect failed:', error);
30742
+ Log$9.error('Device reconnect failed:', error);
29567
30743
  yield wait(1000);
29568
30744
  }
29569
30745
  }
@@ -29588,8 +30764,8 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
29588
30764
  });
29589
30765
  if (writeRes.type !== 'EmmcFile') {
29590
30766
  if (writeRes.type === 'CallMethodError') {
29591
- if (((_s = writeRes.message.error) !== null && _s !== void 0 ? _s : '').indexOf(SESSION_ERROR$1) > -1) {
29592
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$1);
30767
+ if (((_s = writeRes.message.error) !== null && _s !== void 0 ? _s : '').indexOf(SESSION_ERROR$2) > -1) {
30768
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$2);
29593
30769
  }
29594
30770
  }
29595
30771
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -29603,7 +30779,7 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
29603
30779
  return result;
29604
30780
  }
29605
30781
  catch (error) {
29606
- Log$8.error(`emmcWrite error: `, error);
30782
+ Log$9.error(`emmcWrite error: `, error);
29607
30783
  retryCount--;
29608
30784
  if (retryCount === 0) {
29609
30785
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -29614,8 +30790,8 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
29614
30790
  yield ((_h = device.deviceConnector) === null || _h === void 0 ? void 0 : _h.acquire(device.originalDescriptor.id, null, true));
29615
30791
  yield device.initialize();
29616
30792
  }
29617
- else if (((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$1)) > -1 ||
29618
- ((_l = (_k = error === null || error === void 0 ? void 0 : error.response) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.indexOf(SESSION_ERROR$1)) > -1) {
30793
+ else if (((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$2)) > -1 ||
30794
+ ((_l = (_k = error === null || error === void 0 ? void 0 : error.response) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.indexOf(SESSION_ERROR$2)) > -1) {
29619
30795
  const deviceDiff = yield ((_m = device.deviceConnector) === null || _m === void 0 ? void 0 : _m.enumerate());
29620
30796
  const devicesDescriptor = (_o = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _o !== void 0 ? _o : [];
29621
30797
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
@@ -29745,10 +30921,10 @@ class DeviceFullyUploadResource extends BaseMethod {
29745
30921
  }
29746
30922
  }
29747
30923
 
29748
- const Log$7 = getLogger(exports.LoggerNames.Method);
29749
- const SESSION_ERROR = 'session not found';
30924
+ const Log$8 = getLogger(exports.LoggerNames.Method);
30925
+ const SESSION_ERROR$1 = 'session not found';
29750
30926
  const FIRMWARE_UPDATE_CONFIRM = 'Firmware install confirmed';
29751
- const isDeviceDisconnectedError = (error) => {
30927
+ const isDeviceDisconnectedError$1 = (error) => {
29752
30928
  const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
29753
30929
  return (message.includes('device was disconnected') ||
29754
30930
  message.includes('transferIn') ||
@@ -29771,12 +30947,9 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29771
30947
  type,
29772
30948
  }));
29773
30949
  };
29774
- this.postProgressMessage = (progress, progressType) => {
29775
- this.postMessage(createUiMessage(UI_REQUEST.FIRMWARE_PROGRESS, {
29776
- device: this.device.toMessageObject(),
29777
- progress,
29778
- progressType,
29779
- }));
30950
+ this.postProgressMessage = (progress, progressType, metadata = {}) => {
30951
+ this.postMessage(createUiMessage(UI_REQUEST.FIRMWARE_PROGRESS, Object.assign({ device: this.device.toMessageObject(), progress,
30952
+ progressType }, metadata)));
29780
30953
  };
29781
30954
  }
29782
30955
  init() { }
@@ -29824,7 +30997,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29824
30997
  this.checkPromise = hdShared.createDeferred();
29825
30998
  const env = DataManager.getSettings('env');
29826
30999
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
29827
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
31000
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
29828
31001
  let isFirstCheck = true;
29829
31002
  let checkCount = 0;
29830
31003
  let timeoutTimer;
@@ -29833,10 +31006,10 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29833
31006
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
29834
31007
  var _c, _d, _e, _f;
29835
31008
  checkCount += 1;
29836
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
31009
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
29837
31010
  if (isTouchOrProDevice && isFirstCheck) {
29838
31011
  isFirstCheck = false;
29839
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] wait 3000ms');
31012
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] wait 3000ms');
29840
31013
  yield wait(3000);
29841
31014
  }
29842
31015
  if (checkCount > 4 &&
@@ -29852,7 +31025,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29852
31025
  }
29853
31026
  }
29854
31027
  catch (e) {
29855
- Log$7.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] _promptDeviceInBootloaderForWebDevice failed: ', e);
31028
+ Log$8.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] _promptDeviceInBootloaderForWebDevice failed: ', e);
29856
31029
  (_c = this.checkPromise) === null || _c === void 0 ? void 0 : _c.reject(e);
29857
31030
  }
29858
31031
  return;
@@ -29867,7 +31040,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29867
31040
  }
29868
31041
  }
29869
31042
  catch (e) {
29870
- Log$7.log('catch Bluetooth error when device is restarting: ', e);
31043
+ Log$8.log('catch Bluetooth error when device is restarting: ', e);
29871
31044
  }
29872
31045
  }
29873
31046
  else {
@@ -29947,8 +31120,8 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29947
31120
  });
29948
31121
  }
29949
31122
  catch (error) {
29950
- if (isDeviceDisconnectedError(error)) {
29951
- Log$7.log('Rebooting device');
31123
+ if (isDeviceDisconnectedError$1(error)) {
31124
+ Log$8.log('Rebooting device');
29952
31125
  updateResponse = {
29953
31126
  type: 'Success',
29954
31127
  message: { message: FIRMWARE_UPDATE_CONFIRM },
@@ -29972,7 +31145,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29972
31145
  });
29973
31146
  });
29974
31147
  }
29975
- emmcCommonUpdateProcess({ payload, filePath, processedSize, totalSize, }) {
31148
+ emmcCommonUpdateProcess({ payload, filePath, processedSize, totalSize, transferStartTime = Date.now(), }) {
29976
31149
  return __awaiter(this, void 0, void 0, function* () {
29977
31150
  if (!filePath.startsWith('0:')) {
29978
31151
  throw new Error('filePath must start with 0:');
@@ -29982,7 +31155,6 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29982
31155
  const chunkSize = 1024 * perPackageSize;
29983
31156
  const totalChunks = Math.ceil(payload.byteLength / chunkSize);
29984
31157
  let offset = 0;
29985
- let currentFileProcessed = 0;
29986
31158
  for (let i = 0; i < totalChunks; i++) {
29987
31159
  const chunkStart = i * chunkSize;
29988
31160
  const chunkEnd = Math.min(chunkStart + chunkSize, payload.byteLength);
@@ -29991,7 +31163,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29991
31163
  const overwrite = i === 0;
29992
31164
  let progress;
29993
31165
  if (totalSize !== undefined && processedSize !== undefined) {
29994
- currentFileProcessed = processedSize + chunkEnd;
31166
+ const currentFileProcessed = processedSize + chunkEnd;
29995
31167
  progress = Math.min(Math.ceil((currentFileProcessed / totalSize) * 100), 99);
29996
31168
  }
29997
31169
  else {
@@ -29999,7 +31171,15 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
29999
31171
  }
30000
31172
  const writeRes = yield this.emmcFileWriteWithRetry(filePath, chunkLength, offset, chunk, overwrite, progress);
30001
31173
  offset += writeRes.message.processed_byte;
30002
- this.postProgressMessage(progress, 'transferData');
31174
+ const elapsedMs = Date.now() - transferStartTime;
31175
+ const transferredBytes = totalSize !== undefined && processedSize !== undefined ? processedSize + offset : offset;
31176
+ const totalBytes = totalSize !== null && totalSize !== void 0 ? totalSize : payload.byteLength;
31177
+ this.postProgressMessage(progress, 'transferData', {
31178
+ transferredBytes,
31179
+ totalBytes,
31180
+ rateBytesPerSecond: elapsedMs > 0 ? Math.round((transferredBytes / elapsedMs) * 1000) : undefined,
31181
+ elapsedMs,
31182
+ });
30003
31183
  }
30004
31184
  return totalSize !== undefined ? (processedSize !== null && processedSize !== void 0 ? processedSize : 0) + payload.byteLength : 0;
30005
31185
  });
@@ -30023,8 +31203,8 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
30023
31203
  });
30024
31204
  if (writeRes.type !== 'EmmcFile') {
30025
31205
  if (writeRes.type === 'CallMethodError') {
30026
- if (((_k = writeRes.message.error) !== null && _k !== void 0 ? _k : '').indexOf(SESSION_ERROR) > -1) {
30027
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR);
31206
+ if (((_k = writeRes.message.error) !== null && _k !== void 0 ? _k : '').indexOf(SESSION_ERROR$1) > -1) {
31207
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$1);
30028
31208
  }
30029
31209
  }
30030
31210
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -30038,7 +31218,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
30038
31218
  return result;
30039
31219
  }
30040
31220
  catch (error) {
30041
- Log$7.error(`emmcWrite error: `, error);
31221
+ Log$8.error(`emmcWrite error: `, error);
30042
31222
  retryCount--;
30043
31223
  if (retryCount === 0) {
30044
31224
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
@@ -30049,8 +31229,8 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
30049
31229
  yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true));
30050
31230
  yield this.device.initialize();
30051
31231
  }
30052
- else if (((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.indexOf(SESSION_ERROR)) > -1 ||
30053
- ((_d = (_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.indexOf(SESSION_ERROR)) > -1) {
31232
+ else if (((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.indexOf(SESSION_ERROR$1)) > -1 ||
31233
+ ((_d = (_c = error === null || error === void 0 ? void 0 : error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.indexOf(SESSION_ERROR$1)) > -1) {
30054
31234
  const deviceDiff = yield ((_e = this.device.deviceConnector) === null || _e === void 0 ? void 0 : _e.enumerate());
30055
31235
  const devicesDescriptor = (_f = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _f !== void 0 ? _f : [];
30056
31236
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
@@ -30217,7 +31397,7 @@ class GetNextU2FCounter extends BaseMethod {
30217
31397
  }
30218
31398
  }
30219
31399
 
30220
- const Log$6 = getLogger(exports.LoggerNames.Method);
31400
+ const Log$7 = getLogger(exports.LoggerNames.Method);
30221
31401
  class FirmwareUpdate extends BaseMethod {
30222
31402
  constructor() {
30223
31403
  super(...arguments);
@@ -30255,7 +31435,7 @@ class FirmwareUpdate extends BaseMethod {
30255
31435
  this.checkPromise = hdShared.createDeferred();
30256
31436
  const env = DataManager.getSettings('env');
30257
31437
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
30258
- Log$6.log('FirmwareUpdate [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
31438
+ Log$7.log('FirmwareUpdate [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
30259
31439
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
30260
31440
  var _a, _b, _c, _d, _e, _f, _g, _h;
30261
31441
  if (isBleReconnect) {
@@ -30268,7 +31448,7 @@ class FirmwareUpdate extends BaseMethod {
30268
31448
  }
30269
31449
  }
30270
31450
  catch (e) {
30271
- Log$6.log('catch Bluetooth error when device is restarting: ', e);
31451
+ Log$7.log('catch Bluetooth error when device is restarting: ', e);
30272
31452
  }
30273
31453
  }
30274
31454
  else {
@@ -30322,7 +31502,7 @@ class FirmwareUpdate extends BaseMethod {
30322
31502
  if (e instanceof hdShared.HardwareError) {
30323
31503
  return Promise.reject(e);
30324
31504
  }
30325
- Log$6.log('auto go to bootloader mode failed: ', e);
31505
+ Log$7.log('auto go to bootloader mode failed: ', e);
30326
31506
  return Promise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateAutoEnterBootFailure));
30327
31507
  }
30328
31508
  }
@@ -30359,7 +31539,7 @@ class FirmwareUpdate extends BaseMethod {
30359
31539
  }
30360
31540
  }
30361
31541
 
30362
- const Log$5 = getLogger(exports.LoggerNames.Method);
31542
+ const Log$6 = getLogger(exports.LoggerNames.Method);
30363
31543
  class FirmwareUpdateV2 extends BaseMethod {
30364
31544
  constructor() {
30365
31545
  super(...arguments);
@@ -30422,7 +31602,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30422
31602
  this.checkPromise = hdShared.createDeferred();
30423
31603
  const env = DataManager.getSettings('env');
30424
31604
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
30425
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
31605
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
30426
31606
  let isFirstCheck = true;
30427
31607
  let checkCount = 0;
30428
31608
  let timeoutTimer;
@@ -30431,10 +31611,10 @@ class FirmwareUpdateV2 extends BaseMethod {
30431
31611
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
30432
31612
  var _c, _d, _e, _f;
30433
31613
  checkCount += 1;
30434
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
31614
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
30435
31615
  if (isTouchOrProDevice && isFirstCheck) {
30436
31616
  isFirstCheck = false;
30437
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] wait 3000ms');
31617
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] wait 3000ms');
30438
31618
  yield wait(3000);
30439
31619
  }
30440
31620
  if (checkCount > 4 &&
@@ -30452,7 +31632,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30452
31632
  }
30453
31633
  }
30454
31634
  catch (e) {
30455
- Log$5.log('FirmwareUpdateV2 [checkDeviceToBootloader] promptDeviceInBootloaderForWebDevice failed: ', e);
31635
+ Log$6.log('FirmwareUpdateV2 [checkDeviceToBootloader] promptDeviceInBootloaderForWebDevice failed: ', e);
30456
31636
  (_c = this.checkPromise) === null || _c === void 0 ? void 0 : _c.reject(e);
30457
31637
  }
30458
31638
  return;
@@ -30467,7 +31647,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30467
31647
  }
30468
31648
  }
30469
31649
  catch (e) {
30470
- Log$5.log('catch Bluetooth error when device is restarting: ', e);
31650
+ Log$6.log('catch Bluetooth error when device is restarting: ', e);
30471
31651
  }
30472
31652
  }
30473
31653
  else {
@@ -30631,7 +31811,7 @@ class FirmwareUpdateV2 extends BaseMethod {
30631
31811
  }
30632
31812
  }
30633
31813
 
30634
- const Log$4 = getLogger(exports.LoggerNames.Method);
31814
+ const Log$5 = getLogger(exports.LoggerNames.Method);
30635
31815
  const MIN_UPDATE_V3_BOOTLOADER_VERSION = '2.8.0';
30636
31816
  class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30637
31817
  constructor() {
@@ -30671,6 +31851,16 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30671
31851
  };
30672
31852
  }
30673
31853
  run() {
31854
+ var _a;
31855
+ return __awaiter(this, void 0, void 0, function* () {
31856
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) === 'V2') {
31857
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Protocol V2 firmware update must use firmwareUpdateV4');
31858
+ }
31859
+ Log$5.debug('FirmwareUpdateV3 strategy: Protocol V1');
31860
+ return this.runProtocolV1();
31861
+ });
31862
+ }
31863
+ runProtocolV1() {
30674
31864
  var _a, _b;
30675
31865
  return __awaiter(this, void 0, void 0, function* () {
30676
31866
  const { device } = this;
@@ -30737,7 +31927,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30737
31927
  const resource = (yield getSysResourceBinary(resourceUrl)).binary;
30738
31928
  return resource;
30739
31929
  }
30740
- Log$4.warn('No resource url found');
31930
+ Log$5.warn('No resource url found');
30741
31931
  return null;
30742
31932
  });
30743
31933
  }
@@ -30822,6 +32012,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30822
32012
  totalSize += bootloaderBinary.byteLength;
30823
32013
  }
30824
32014
  this.postTipMessage(exports.FirmwareUpdateTipMessage.StartTransferData);
32015
+ const transferStartTime = Date.now();
30825
32016
  if (resourceBinary) {
30826
32017
  const file = yield JSZip__default["default"].loadAsync(resourceBinary);
30827
32018
  const files = Object.entries(file.files);
@@ -30834,6 +32025,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30834
32025
  filePath: `0:res/${name}`,
30835
32026
  processedSize,
30836
32027
  totalSize,
32028
+ transferStartTime,
30837
32029
  });
30838
32030
  }
30839
32031
  }
@@ -30844,6 +32036,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30844
32036
  filePath: `0:boot/bootloader.bin`,
30845
32037
  processedSize,
30846
32038
  totalSize,
32039
+ transferStartTime,
30847
32040
  });
30848
32041
  }
30849
32042
  yield this.createUpdatesFolderIfNotExists(`0:updates/`);
@@ -30854,17 +32047,16 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30854
32047
  filePath: `0:updates/${fwbinary.fileName}`,
30855
32048
  processedSize,
30856
32049
  totalSize,
32050
+ transferStartTime,
30857
32051
  });
30858
32052
  }
30859
32053
  }
30860
32054
  try {
30861
32055
  this.postTipMessage(exports.FirmwareUpdateTipMessage.ConfirmOnDevice);
30862
- yield this.startEmmcFirmwareUpdate({
30863
- path: '0:updates',
30864
- });
32056
+ yield this.startEmmcFirmwareUpdate({ path: '0:updates' });
30865
32057
  }
30866
32058
  catch (error) {
30867
- Log$4.error('triggerFirmwareUpdateEmmc error: ', error);
32059
+ Log$5.error('triggerFirmwareUpdateEmmc error: ', error);
30868
32060
  if (error === null || error === void 0 ? void 0 : error.errorCode) {
30869
32061
  const unexpectedError = [
30870
32062
  hdShared.HardwareErrorCode.ActionCancelled,
@@ -30925,7 +32117,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
30925
32117
  yield hdShared.wait(1000);
30926
32118
  }
30927
32119
  catch (error) {
30928
- Log$4.log('getFeatures error', error);
32120
+ Log$5.log('getFeatures error', error);
30929
32121
  let shouldReconnect = true;
30930
32122
  const progress = this.extractUpdateModeProgress(error);
30931
32123
  if (progress !== null) {
@@ -31023,7 +32215,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
31023
32215
  return;
31024
32216
  }
31025
32217
  catch (e) {
31026
- Log$4.log('catch Bluetooth error when device is restarting: ', e);
32218
+ Log$5.log('catch Bluetooth error when device is restarting: ', e);
31027
32219
  }
31028
32220
  }
31029
32221
  else {
@@ -31038,7 +32230,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
31038
32230
  yield this._promptDeviceForSwitchFirmwareWebDevice();
31039
32231
  }
31040
32232
  catch (e) {
31041
- Log$4.log('WebUSB re-authorization failed: ', e);
32233
+ Log$5.log('WebUSB re-authorization failed: ', e);
31042
32234
  }
31043
32235
  webUsbCheckCount = 0;
31044
32236
  }
@@ -31059,7 +32251,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
31059
32251
  }
31060
32252
  catch (error) {
31061
32253
  console.error('Device reconnect failed: ', error);
31062
- Log$4.error('Device reconnect failed:', error);
32254
+ Log$5.error('Device reconnect failed:', error);
31063
32255
  yield hdShared.wait(1000);
31064
32256
  }
31065
32257
  }
@@ -31068,6 +32260,712 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
31068
32260
  }
31069
32261
  }
31070
32262
 
32263
+ const DEV_REBOOT_TYPES = {
32264
+ Normal: hdTransport.DevRebootType.Normal,
32265
+ normal: hdTransport.DevRebootType.Normal,
32266
+ Boardloader: hdTransport.DevRebootType.Boardloader,
32267
+ boardloader: hdTransport.DevRebootType.Boardloader,
32268
+ Bootloader: hdTransport.DevRebootType.Bootloader,
32269
+ bootloader: hdTransport.DevRebootType.Bootloader,
32270
+ };
32271
+ const PROTOCOL_V2_FIRMWARE_UPDATE_OPTIONS = {
32272
+ intermediateTypes: ['DevFirmwareInstallProgress'],
32273
+ };
32274
+ const PROTOCOL_V2_FIRMWARE_UPDATE_RESPONSE_TYPES = ['Success', 'DevFirmwareUpdateStatus'];
32275
+ function normalizeRebootType(value) {
32276
+ if (typeof value === 'number')
32277
+ return value;
32278
+ if (typeof value === 'string') {
32279
+ const numeric = Number(value);
32280
+ if (Number.isFinite(numeric))
32281
+ return numeric;
32282
+ if (value in DEV_REBOOT_TYPES)
32283
+ return DEV_REBOOT_TYPES[value];
32284
+ }
32285
+ return hdTransport.DevRebootType.Normal;
32286
+ }
32287
+ function normalizeTargetId(value) {
32288
+ if (typeof value === 'number')
32289
+ return value;
32290
+ const numeric = Number(value);
32291
+ if (Number.isFinite(numeric))
32292
+ return numeric;
32293
+ return 0;
32294
+ }
32295
+ function normalizeFirmwareTargets(params) {
32296
+ var _a, _b, _c;
32297
+ const targets = (_a = params.targets) !== null && _a !== void 0 ? _a : (params.path
32298
+ ? [
32299
+ {
32300
+ target_id: (_c = (_b = params.target_id) !== null && _b !== void 0 ? _b : params.targetId) !== null && _c !== void 0 ? _c : 0,
32301
+ path: params.path,
32302
+ },
32303
+ ]
32304
+ : []);
32305
+ return targets.map(target => ({
32306
+ target_id: normalizeTargetId('target_id' in target ? target.target_id : target.targetId),
32307
+ path: target.path,
32308
+ }));
32309
+ }
32310
+ function buildTargets(params) {
32311
+ if (params.targets)
32312
+ return params.targets;
32313
+ const targets = {
32314
+ hw: params.targetHw,
32315
+ fw: params.targetFw,
32316
+ bt: params.targetBt,
32317
+ se1: params.targetSe1,
32318
+ se2: params.targetSe2,
32319
+ se3: params.targetSe3,
32320
+ se4: params.targetSe4,
32321
+ status: params.targetStatus,
32322
+ };
32323
+ return Object.values(targets).some(value => value !== undefined) ? targets : undefined;
32324
+ }
32325
+ function buildTypes(params) {
32326
+ if (params.types)
32327
+ return params.types;
32328
+ const types = {
32329
+ version: params.includeVersion,
32330
+ build_id: params.includeBuildId,
32331
+ hash: params.includeHash,
32332
+ specific: params.includeSpecific,
32333
+ };
32334
+ return Object.values(types).some(value => value !== undefined) ? types : undefined;
32335
+ }
32336
+
32337
+ const Log$4 = getLogger(exports.LoggerNames.Method);
32338
+ const SESSION_ERROR = 'session not found';
32339
+ const PROTOCOL_V2_BOOTLOADER_RECONNECT_TIMEOUT = 60 * 1000;
32340
+ const PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT = 5 * 1000;
32341
+ const PROTOCOL_V2_INSTALL_TIMEOUT = 5 * 60 * 1000;
32342
+ const PROTOCOL_V2_TARGET_STATUS_FINISHED = 0;
32343
+ const PROTOCOL_V2_TARGET_STATUS_IN_PROGRESS = 1;
32344
+ const PROTOCOL_V2_TARGET_STATUS_FAILED = 2;
32345
+ const PROTOCOL_V2_CONNECT_PROTOCOL = 'V2';
32346
+ const PROTOCOL_V2_FIRMWARE_STAGING_VOLUME = 'vol1:';
32347
+ const PROTOCOL_V2_MIN_FILE_CHUNK_SIZE = 64;
32348
+ const getUnknownErrorText = (error) => {
32349
+ if (!error) {
32350
+ return '';
32351
+ }
32352
+ if (typeof error === 'string') {
32353
+ return error;
32354
+ }
32355
+ const parts = [];
32356
+ if (error instanceof Error) {
32357
+ parts.push(error.name, error.message);
32358
+ }
32359
+ if (typeof error === 'object') {
32360
+ const record = error;
32361
+ for (const field of ['name', 'message', 'reason', 'code', 'errorCode', 'nativeErrorCode']) {
32362
+ const value = record[field];
32363
+ if (value !== undefined && value !== null) {
32364
+ parts.push(String(value));
32365
+ }
32366
+ }
32367
+ }
32368
+ const stringified = String(error);
32369
+ if (stringified && stringified !== '[object Object]') {
32370
+ parts.push(stringified);
32371
+ }
32372
+ return parts.filter(Boolean).join(' ');
32373
+ };
32374
+ const isDeviceDisconnectedError = (error) => {
32375
+ const message = getUnknownErrorText(error).toLowerCase();
32376
+ const compactMessage = message.replace(/\s+/g, '');
32377
+ return (message.includes('device was disconnected') ||
32378
+ message.includes('device disconnected') ||
32379
+ message.includes('device disconnect') ||
32380
+ message.includes('was disconnected') ||
32381
+ message.includes('bledevicedisconnected') ||
32382
+ message.includes('bleconnectederror') ||
32383
+ message.includes('connected error is always runtime error') ||
32384
+ message.includes('connection has timed out unexpectedly') ||
32385
+ message.includes('connection error has occured') ||
32386
+ message.includes('connection error has occurred') ||
32387
+ message.includes('transferIn') ||
32388
+ message.includes('transferin') ||
32389
+ message.includes('usbdevice') ||
32390
+ message.includes('multiplatformbleadapter') ||
32391
+ message.includes('multipalformebleadapter') ||
32392
+ compactMessage.includes('rxerrorerror6') ||
32393
+ message.includes('rxerror error 6'));
32394
+ };
32395
+ const isProtocolV2ReconnectProbeError = (error) => {
32396
+ const message = getUnknownErrorText(error).toLowerCase();
32397
+ return ((message.includes('device protocol mismatch') && message.includes('expected v2')) ||
32398
+ message.includes('did not respond to expected protocol'));
32399
+ };
32400
+ const isProtocolV2PollingTransientError = (error) => {
32401
+ const message = getUnknownErrorText(error).toLowerCase();
32402
+ return (isDeviceDisconnectedError(error) ||
32403
+ isProtocolV2ReconnectProbeError(error) ||
32404
+ (message.includes('response timeout') && message.includes('devgetfirmwareupdatestatus')) ||
32405
+ message.includes('device not found') ||
32406
+ message.includes('transportnotfound'));
32407
+ };
32408
+ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
32409
+ init() {
32410
+ this.allowDeviceMode = [UI_REQUEST.BOOTLOADER, UI_REQUEST.NOT_INITIALIZE];
32411
+ this.requireDeviceMode = [];
32412
+ this.useDevicePassphraseState = false;
32413
+ this.skipForceUpdateCheck = true;
32414
+ const { payload } = this;
32415
+ validateParams(payload, [
32416
+ { name: 'bleVersion', type: 'array' },
32417
+ { name: 'bleBinary', type: 'buffer' },
32418
+ { name: 'chunkSize', type: 'number' },
32419
+ { name: 'firmwareVersion', type: 'array' },
32420
+ { name: 'firmwareBinary', type: 'buffer' },
32421
+ { name: 'resourceBinary', type: 'buffer' },
32422
+ { name: 'forcedUpdateRes', type: 'boolean' },
32423
+ { name: 'bootloaderVersion', type: 'array' },
32424
+ { name: 'bootloaderBinary', type: 'buffer' },
32425
+ { name: 'firmwareType', type: 'string' },
32426
+ { name: 'platform', type: 'string' },
32427
+ ]);
32428
+ this.params = {
32429
+ bleBinary: payload.bleBinary,
32430
+ chunkSize: payload.chunkSize,
32431
+ firmwareBinary: payload.firmwareBinary,
32432
+ forcedUpdateRes: payload.forcedUpdateRes,
32433
+ bleVersion: payload.bleVersion,
32434
+ bootloaderVersion: payload.bootloaderVersion,
32435
+ bootloaderBinary: payload.bootloaderBinary,
32436
+ firmwareVersion: payload.firmwareVersion,
32437
+ resourceBinary: payload.resourceBinary,
32438
+ firmwareType: payload.firmwareType,
32439
+ platform: payload.platform,
32440
+ };
32441
+ }
32442
+ getProtocolV2FirmwareChunkSize() {
32443
+ var _a, _b;
32444
+ const payloadChunkSize = Number((_a = this.params) === null || _a === void 0 ? void 0 : _a.chunkSize);
32445
+ const env = DataManager.getSettings('env');
32446
+ const maxChunkSize = ((_b = this.params) === null || _b === void 0 ? void 0 : _b.platform) === 'native' || (env && DataManager.isBleConnect(env))
32447
+ ? hdTransport.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE
32448
+ : hdTransport.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
32449
+ if (!Number.isFinite(payloadChunkSize) || payloadChunkSize <= 0) {
32450
+ return maxChunkSize;
32451
+ }
32452
+ return Math.min(Math.max(Math.floor(payloadChunkSize), PROTOCOL_V2_MIN_FILE_CHUNK_SIZE), maxChunkSize);
32453
+ }
32454
+ run() {
32455
+ var _a;
32456
+ return __awaiter(this, void 0, void 0, function* () {
32457
+ if (((_a = this.device.originalDescriptor) === null || _a === void 0 ? void 0 : _a.protocolType) !== 'V2') {
32458
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'firmwareUpdateV4 requires a Protocol V2 device');
32459
+ }
32460
+ Log$4.debug('FirmwareUpdateV4 strategy: Protocol V2');
32461
+ return this.runProtocolV2();
32462
+ });
32463
+ }
32464
+ runProtocolV2() {
32465
+ var _a, _b;
32466
+ return __awaiter(this, void 0, void 0, function* () {
32467
+ const { device } = this;
32468
+ const { features } = device;
32469
+ if (!features) {
32470
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Device features not available');
32471
+ }
32472
+ const deviceFirmwareType = getFirmwareType(features);
32473
+ const firmwareType = (_a = this.params.firmwareType) !== null && _a !== void 0 ? _a : deviceFirmwareType;
32474
+ let resourceBinary = null;
32475
+ let fwBinaryMap = [];
32476
+ let bootloaderBinary = null;
32477
+ try {
32478
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.StartDownloadFirmware);
32479
+ resourceBinary = yield this.prepareResourceBinary(firmwareType);
32480
+ fwBinaryMap = yield this.prepareFirmwareAndBleBinary(firmwareType);
32481
+ bootloaderBinary = yield this.prepareBootloaderBinary(firmwareType);
32482
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FinishDownloadFirmware);
32483
+ }
32484
+ catch (err) {
32485
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, (_b = err.message) !== null && _b !== void 0 ? _b : err);
32486
+ }
32487
+ if (!resourceBinary && !bootloaderBinary && fwBinaryMap.length === 0) {
32488
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, 'No firmware to update');
32489
+ }
32490
+ yield this.executeProtocolV2Update({
32491
+ resourceBinary,
32492
+ fwBinaryMap,
32493
+ bootloaderBinary,
32494
+ });
32495
+ yield this.exitProtocolV2BootloaderToNormal();
32496
+ const versions = yield this.waitForProtocolV2FinalFeatures();
32497
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FirmwareUpdateCompleted);
32498
+ DevicePool.resetState();
32499
+ return versions;
32500
+ });
32501
+ }
32502
+ prepareResourceBinary(firmwareType) {
32503
+ return __awaiter(this, void 0, void 0, function* () {
32504
+ if (this.params.resourceBinary) {
32505
+ return this.params.resourceBinary;
32506
+ }
32507
+ const { features } = this.device;
32508
+ if (!features)
32509
+ return null;
32510
+ const resourceUrl = DataManager.getSysResourcesLatestRelease({
32511
+ features,
32512
+ forcedUpdateRes: this.params.forcedUpdateRes,
32513
+ firmwareType,
32514
+ });
32515
+ if (resourceUrl) {
32516
+ const resource = (yield getSysResourceBinary(resourceUrl)).binary;
32517
+ return resource;
32518
+ }
32519
+ Log$4.warn('No resource url found');
32520
+ return null;
32521
+ });
32522
+ }
32523
+ prepareBootloaderBinary(firmwareType) {
32524
+ return __awaiter(this, void 0, void 0, function* () {
32525
+ if (this.params.bootloaderBinary) {
32526
+ return this.params.bootloaderBinary;
32527
+ }
32528
+ const { features } = this.device;
32529
+ if (!features)
32530
+ return null;
32531
+ if (this.params.bootloaderVersion) {
32532
+ const bootResourceUrl = DataManager.getBootloaderResource(features, firmwareType);
32533
+ if (bootResourceUrl) {
32534
+ const bootBinary = (yield getSysResourceBinary(bootResourceUrl)).binary;
32535
+ return bootBinary;
32536
+ }
32537
+ }
32538
+ return null;
32539
+ });
32540
+ }
32541
+ prepareFirmwareAndBleBinary(firmwareType) {
32542
+ return __awaiter(this, void 0, void 0, function* () {
32543
+ const fwBinaryMap = [];
32544
+ if (this.params.firmwareBinary) {
32545
+ fwBinaryMap.push({
32546
+ fileName: 'firmware.bin',
32547
+ binary: this.params.firmwareBinary,
32548
+ });
32549
+ }
32550
+ else if (this.params.firmwareVersion) {
32551
+ const { features } = this.device;
32552
+ if (features) {
32553
+ const firmwareBinary = (yield getBinary({
32554
+ features,
32555
+ version: this.params.firmwareVersion,
32556
+ updateType: 'firmware',
32557
+ isUpdateBootloader: false,
32558
+ firmwareType,
32559
+ })).binary;
32560
+ fwBinaryMap.push({
32561
+ fileName: 'firmware.bin',
32562
+ binary: firmwareBinary,
32563
+ });
32564
+ }
32565
+ }
32566
+ if (this.params.bleBinary) {
32567
+ fwBinaryMap.push({
32568
+ fileName: 'ble-firmware.bin',
32569
+ binary: this.params.bleBinary,
32570
+ });
32571
+ }
32572
+ else if (this.params.bleVersion) {
32573
+ const { features } = this.device;
32574
+ if (features) {
32575
+ const bleBinary = yield getBinary({
32576
+ features,
32577
+ version: this.params.bleVersion,
32578
+ updateType: 'ble',
32579
+ firmwareType,
32580
+ });
32581
+ fwBinaryMap.push({
32582
+ fileName: 'ble-firmware.bin',
32583
+ binary: bleBinary.binary,
32584
+ });
32585
+ }
32586
+ }
32587
+ return fwBinaryMap;
32588
+ });
32589
+ }
32590
+ executeProtocolV2Update({ resourceBinary, fwBinaryMap, bootloaderBinary, }) {
32591
+ return __awaiter(this, void 0, void 0, function* () {
32592
+ let totalSize = 0;
32593
+ let processedSize = 0;
32594
+ if (resourceBinary)
32595
+ totalSize += resourceBinary.byteLength;
32596
+ for (const fwbinary of fwBinaryMap)
32597
+ totalSize += fwbinary.binary.byteLength;
32598
+ if (bootloaderBinary)
32599
+ totalSize += bootloaderBinary.byteLength;
32600
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.StartTransferData);
32601
+ const transferStartTime = Date.now();
32602
+ const targets = [];
32603
+ if (resourceBinary) {
32604
+ const resourcePath = `${PROTOCOL_V2_FIRMWARE_STAGING_VOLUME}res/`;
32605
+ yield this.protocolV2CreateFolder(resourcePath);
32606
+ const file = yield JSZip__default["default"].loadAsync(resourceBinary);
32607
+ const files = Object.entries(file.files);
32608
+ for (const [fileName, entry] of files) {
32609
+ const name = fileName.split('/').pop();
32610
+ if (!entry.dir && fileName.indexOf('__MACOSX') === -1 && name) {
32611
+ const data = yield entry.async('arraybuffer');
32612
+ processedSize = yield this.protocolV2CommonUpdateProcess({
32613
+ payload: data,
32614
+ filePath: `${resourcePath}${name}`,
32615
+ processedSize,
32616
+ totalSize,
32617
+ transferStartTime,
32618
+ });
32619
+ }
32620
+ }
32621
+ targets.push({
32622
+ target_id: ProtocolV2FirmwareTargetType.TARGET_RESOURCE,
32623
+ path: resourcePath,
32624
+ });
32625
+ }
32626
+ if (bootloaderBinary) {
32627
+ const bootloaderPath = `${PROTOCOL_V2_FIRMWARE_STAGING_VOLUME}bootloader.bin`;
32628
+ processedSize = yield this.protocolV2CommonUpdateProcess({
32629
+ payload: bootloaderBinary,
32630
+ filePath: bootloaderPath,
32631
+ processedSize,
32632
+ totalSize,
32633
+ transferStartTime,
32634
+ });
32635
+ targets.push({
32636
+ target_id: ProtocolV2FirmwareTargetType.TARGET_MAIN_BOOT,
32637
+ path: bootloaderPath,
32638
+ });
32639
+ }
32640
+ for (const fwbinary of fwBinaryMap) {
32641
+ const firmwarePath = `${PROTOCOL_V2_FIRMWARE_STAGING_VOLUME}${fwbinary.fileName}`;
32642
+ processedSize = yield this.protocolV2CommonUpdateProcess({
32643
+ payload: fwbinary.binary,
32644
+ filePath: firmwarePath,
32645
+ processedSize,
32646
+ totalSize,
32647
+ transferStartTime,
32648
+ });
32649
+ targets.push({
32650
+ target_id: protocolV2FileNameToTargetId(fwbinary.fileName),
32651
+ path: firmwarePath,
32652
+ });
32653
+ }
32654
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.ConfirmOnDevice);
32655
+ const startResponse = yield this.protocolV2StartFirmwareUpdate({ targets });
32656
+ yield this.waitForProtocolV2FirmwareUpdateComplete(targets, startResponse);
32657
+ });
32658
+ }
32659
+ queryProtocolV2FirmwareUpdateStatus() {
32660
+ return __awaiter(this, void 0, void 0, function* () {
32661
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32662
+ return typedCall('DevGetFirmwareUpdateStatus', 'DevFirmwareUpdateStatus', {}, {
32663
+ timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
32664
+ });
32665
+ });
32666
+ }
32667
+ pingProtocolV2Device() {
32668
+ return __awaiter(this, void 0, void 0, function* () {
32669
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32670
+ yield typedCall('Ping', 'Success', { message: 'firmware-update' }, {
32671
+ timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
32672
+ });
32673
+ });
32674
+ }
32675
+ assertProtocolV2TargetStatus(statusTargets, expectedTargetIds) {
32676
+ const failedTarget = statusTargets.find(target => expectedTargetIds.has(target.target_id) &&
32677
+ target.status === PROTOCOL_V2_TARGET_STATUS_FAILED);
32678
+ if (failedTarget) {
32679
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareError, `Protocol V2 firmware target ${failedTarget.target_id} failed`);
32680
+ }
32681
+ const completedTargets = statusTargets.filter(target => expectedTargetIds.has(target.target_id) &&
32682
+ target.status === PROTOCOL_V2_TARGET_STATUS_FINISHED);
32683
+ if (completedTargets.length === expectedTargetIds.size && expectedTargetIds.size > 0) {
32684
+ return true;
32685
+ }
32686
+ const inProgressTarget = statusTargets.find(target => expectedTargetIds.has(target.target_id) &&
32687
+ target.status === PROTOCOL_V2_TARGET_STATUS_IN_PROGRESS);
32688
+ if (inProgressTarget) {
32689
+ this.postProgressMessage(99, 'installingFirmware');
32690
+ }
32691
+ return false;
32692
+ }
32693
+ waitForProtocolV2FirmwareUpdateComplete(targets, startResponse) {
32694
+ var _a, _b;
32695
+ return __awaiter(this, void 0, void 0, function* () {
32696
+ const expectedTargetIds = new Set(targets.map(target => target.target_id));
32697
+ if ((startResponse === null || startResponse === void 0 ? void 0 : startResponse.type) === 'Success') {
32698
+ return;
32699
+ }
32700
+ if ((startResponse === null || startResponse === void 0 ? void 0 : startResponse.type) === 'DevFirmwareUpdateStatus') {
32701
+ const statusTargets = ((_a = startResponse.message.targets) !== null && _a !== void 0 ? _a : []);
32702
+ if (this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds)) {
32703
+ return;
32704
+ }
32705
+ }
32706
+ const startTime = Date.now();
32707
+ let lastError;
32708
+ while (Date.now() - startTime < PROTOCOL_V2_INSTALL_TIMEOUT) {
32709
+ try {
32710
+ const statusRes = yield this.queryProtocolV2FirmwareUpdateStatus();
32711
+ const statusTargets = ((_b = statusRes.message.targets) !== null && _b !== void 0 ? _b : []);
32712
+ if (this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds)) {
32713
+ return;
32714
+ }
32715
+ }
32716
+ catch (error) {
32717
+ lastError = error;
32718
+ if (error instanceof hdShared.HardwareError && error.errorCode === hdShared.HardwareErrorCode.FirmwareError) {
32719
+ throw error;
32720
+ }
32721
+ Log$4.log('Protocol V2 firmware install status polling failed: ', error);
32722
+ if (isProtocolV2PollingTransientError(error)) {
32723
+ try {
32724
+ yield this.reconnectProtocolV2Device();
32725
+ }
32726
+ catch (reconnectError) {
32727
+ lastError = reconnectError;
32728
+ Log$4.log('Protocol V2 firmware install reconnect/status polling failed: ', reconnectError);
32729
+ }
32730
+ try {
32731
+ yield this.pingProtocolV2Device();
32732
+ Log$4.log('Protocol V2 firmware status unavailable, Ping is ready');
32733
+ return;
32734
+ }
32735
+ catch (pingError) {
32736
+ lastError = pingError;
32737
+ Log$4.log('Protocol V2 firmware install Ping polling failed: ', pingError);
32738
+ }
32739
+ }
32740
+ }
32741
+ yield hdShared.wait(1000);
32742
+ }
32743
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Protocol V2 firmware update status timeout: ${this.normalizeErrorMessage(lastError)}`);
32744
+ });
32745
+ }
32746
+ exitProtocolV2BootloaderToNormal() {
32747
+ return __awaiter(this, void 0, void 0, function* () {
32748
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.SwitchFirmwareReconnectDevice);
32749
+ yield this.protocolV2Reboot(hdTransport.DevRebootType.Normal);
32750
+ });
32751
+ }
32752
+ waitForProtocolV2FinalFeatures() {
32753
+ return __awaiter(this, void 0, void 0, function* () {
32754
+ const features = yield this.waitForProtocolV2ReconnectAndFeatures(PROTOCOL_V2_BOOTLOADER_RECONNECT_TIMEOUT);
32755
+ this.device._updateFeatures(features);
32756
+ const bootloaderVersion = getDeviceBootloaderVersion(features).join('.');
32757
+ const bleVersion = getDeviceBLEFirmwareVersion(features).join('.');
32758
+ const firmwareVersion = getDeviceFirmwareVersion(features).join('.');
32759
+ if (firmwareVersion === '0.0.0') {
32760
+ Log$4.warn('Protocol V2 firmware update finished but app firmware version is still 0.0.0. This is allowed for Pro2 debug BLE-only update flows.');
32761
+ }
32762
+ return {
32763
+ bootloaderVersion,
32764
+ bleVersion,
32765
+ firmwareVersion,
32766
+ };
32767
+ });
32768
+ }
32769
+ waitForProtocolV2ReconnectAndFeatures(timeout) {
32770
+ return __awaiter(this, void 0, void 0, function* () {
32771
+ const startTime = Date.now();
32772
+ let lastError;
32773
+ while (Date.now() - startTime < timeout) {
32774
+ try {
32775
+ yield this.reconnectProtocolV2Device();
32776
+ const features = yield getProtocolV2Features({
32777
+ commands: this.device.getCommands(),
32778
+ descriptor: this.device.originalDescriptor,
32779
+ onDeviceInfoError: error => {
32780
+ Log$4.debug('Protocol V2 post-update DevGetDeviceInfo failed:', error);
32781
+ },
32782
+ timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
32783
+ });
32784
+ return features;
32785
+ }
32786
+ catch (error) {
32787
+ lastError = error;
32788
+ Log$4.log('Protocol V2 normal mode not ready, polling Ping/DevGetDeviceInfo: ', error);
32789
+ yield hdShared.wait(1000);
32790
+ }
32791
+ }
32792
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Protocol V2 final features not ready within ${timeout / 1000}s: ${this.normalizeErrorMessage(lastError)}`);
32793
+ });
32794
+ }
32795
+ reconnectProtocolV2Device() {
32796
+ var _a, _b, _c;
32797
+ return __awaiter(this, void 0, void 0, function* () {
32798
+ if (this.isBleReconnect()) {
32799
+ yield this.acquireProtocolV2BleDevice();
32800
+ return;
32801
+ }
32802
+ const deviceDiff = yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.enumerate());
32803
+ const devicesDescriptor = (_b = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _b !== void 0 ? _b : [];
32804
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, this.connectId);
32805
+ if (deviceList.length !== 1) {
32806
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound);
32807
+ }
32808
+ this.device.updateFromCache(deviceList[0]);
32809
+ yield this.device.acquire();
32810
+ this.device.commands.disposed = false;
32811
+ this.device.getCommands().mainId = (_c = this.device.mainId) !== null && _c !== void 0 ? _c : '';
32812
+ });
32813
+ }
32814
+ protocolV2CreateFolder(path) {
32815
+ return __awaiter(this, void 0, void 0, function* () {
32816
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32817
+ yield typedCall('FilesystemDirMake', 'Success', { path });
32818
+ });
32819
+ }
32820
+ protocolV2CommonUpdateProcess({ payload, filePath, processedSize, totalSize, transferStartTime = Date.now(), }) {
32821
+ var _a;
32822
+ return __awaiter(this, void 0, void 0, function* () {
32823
+ const chunkSize = this.getProtocolV2FirmwareChunkSize();
32824
+ let offset = 0;
32825
+ const getUploadProgress = (fileOffset) => {
32826
+ if (totalSize !== undefined && processedSize !== undefined) {
32827
+ return Math.min(Math.ceil(((processedSize + fileOffset) / totalSize) * 100), 99);
32828
+ }
32829
+ return Math.min(Math.ceil((fileOffset / payload.byteLength) * 100), 99);
32830
+ };
32831
+ while (offset < payload.byteLength) {
32832
+ const chunkEnd = Math.min(offset + chunkSize, payload.byteLength);
32833
+ const chunkLength = chunkEnd - offset;
32834
+ const chunk = payload.slice(offset, chunkEnd);
32835
+ const overwrite = offset === 0;
32836
+ const progress = getUploadProgress(chunkEnd);
32837
+ const writeRes = yield this.fileWriteWithRetry(filePath, payload.byteLength, offset, chunk, overwrite, progress);
32838
+ const nextOffset = (_a = writeRes.message.processed_byte) !== null && _a !== void 0 ? _a : offset + chunkLength;
32839
+ if (nextOffset <= offset || nextOffset > payload.byteLength) {
32840
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, `invalid processed_byte ${nextOffset} for offset ${offset}`);
32841
+ }
32842
+ offset = nextOffset;
32843
+ const elapsedMs = Date.now() - transferStartTime;
32844
+ const transferredBytes = totalSize !== undefined && processedSize !== undefined
32845
+ ? Math.min(processedSize + offset, totalSize)
32846
+ : offset;
32847
+ const totalBytes = totalSize !== null && totalSize !== void 0 ? totalSize : payload.byteLength;
32848
+ this.postProgressMessage(getUploadProgress(offset), 'transferData', {
32849
+ transferredBytes,
32850
+ totalBytes,
32851
+ rateBytesPerSecond: elapsedMs > 0 ? Math.round((transferredBytes / elapsedMs) * 1000) : undefined,
32852
+ elapsedMs,
32853
+ });
32854
+ }
32855
+ return totalSize !== undefined ? (processedSize !== null && processedSize !== void 0 ? processedSize : 0) + payload.byteLength : 0;
32856
+ });
32857
+ }
32858
+ fileWriteWithRetry(filePath, totalFileSize, offset, chunk, overwrite, progress) {
32859
+ return __awaiter(this, void 0, void 0, function* () {
32860
+ const writeFunc = () => __awaiter(this, void 0, void 0, function* () {
32861
+ var _a;
32862
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32863
+ const writeRes = yield typedCall('FilesystemFileWrite', 'FilesystemFile', {
32864
+ file: {
32865
+ path: filePath,
32866
+ offset,
32867
+ total_size: totalFileSize,
32868
+ data: chunk,
32869
+ },
32870
+ overwrite,
32871
+ append: false,
32872
+ ui_percentage: progress !== null && progress !== void 0 ? progress : undefined,
32873
+ });
32874
+ if (writeRes.type !== 'FilesystemFile') {
32875
+ if (writeRes.type === 'CallMethodError') {
32876
+ if (((_a = writeRes.message.error) !== null && _a !== void 0 ? _a : '').indexOf(SESSION_ERROR) > -1) {
32877
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR);
32878
+ }
32879
+ }
32880
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
32881
+ }
32882
+ return writeRes;
32883
+ });
32884
+ let retryCount = 10;
32885
+ while (retryCount > 0) {
32886
+ try {
32887
+ const result = yield writeFunc();
32888
+ return result;
32889
+ }
32890
+ catch (error) {
32891
+ Log$4.error(`fileWrite error: `, error);
32892
+ retryCount--;
32893
+ if (retryCount === 0) {
32894
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
32895
+ }
32896
+ const env = DataManager.getSettings('env');
32897
+ if (DataManager.isBleConnect(env)) {
32898
+ yield hdShared.wait(3000);
32899
+ yield this.acquireProtocolV2BleDevice();
32900
+ yield this.device.initialize();
32901
+ }
32902
+ yield hdShared.wait(2000);
32903
+ }
32904
+ }
32905
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.EmmcFileWriteFirmwareError, 'transfer data error');
32906
+ });
32907
+ }
32908
+ acquireProtocolV2BleDevice() {
32909
+ var _a;
32910
+ return __awaiter(this, void 0, void 0, function* () {
32911
+ yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true, PROTOCOL_V2_CONNECT_PROTOCOL));
32912
+ });
32913
+ }
32914
+ protocolV2StartFirmwareUpdate({ targets, }) {
32915
+ return __awaiter(this, void 0, void 0, function* () {
32916
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32917
+ let response;
32918
+ try {
32919
+ response = yield typedCall('DevFirmwareUpdate', PROTOCOL_V2_FIRMWARE_UPDATE_RESPONSE_TYPES, {
32920
+ targets,
32921
+ }, {
32922
+ intermediateTypes: ['DevFirmwareInstallProgress'],
32923
+ onIntermediateResponse: (response) => {
32924
+ var _a;
32925
+ const progress = Number((_a = response.message) === null || _a === void 0 ? void 0 : _a.progress);
32926
+ if (Number.isFinite(progress)) {
32927
+ this.postProgressMessage(Math.min(progress, 99), 'installingFirmware');
32928
+ }
32929
+ },
32930
+ });
32931
+ }
32932
+ catch (error) {
32933
+ if (isDeviceDisconnectedError(error)) {
32934
+ Log$4.log('Rebooting device');
32935
+ }
32936
+ else {
32937
+ throw error;
32938
+ }
32939
+ }
32940
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FirmwareUpdating);
32941
+ return response;
32942
+ });
32943
+ }
32944
+ protocolV2Reboot(rebootType) {
32945
+ return __awaiter(this, void 0, void 0, function* () {
32946
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
32947
+ try {
32948
+ const res = yield typedCall('DevReboot', 'Success', {
32949
+ reboot_type: rebootType,
32950
+ });
32951
+ return res.message;
32952
+ }
32953
+ catch (error) {
32954
+ if (isDeviceDisconnectedError(error) || isProtocolV2ReconnectProbeError(error)) {
32955
+ return { message: 'Device rebooted successfully' };
32956
+ }
32957
+ throw error;
32958
+ }
32959
+ });
32960
+ }
32961
+ normalizeErrorMessage(error) {
32962
+ if (!error) {
32963
+ return '';
32964
+ }
32965
+ return getUnknownErrorText(error);
32966
+ }
32967
+ }
32968
+
31071
32969
  const Log$3 = getLogger(exports.LoggerNames.Method);
31072
32970
  class PromptWebDeviceAccess extends BaseMethod {
31073
32971
  init() {
@@ -31125,6 +33023,538 @@ class PromptWebDeviceAccess extends BaseMethod {
31125
33023
  }
31126
33024
  }
31127
33025
 
33026
+ class GetProtoVersion extends BaseMethod {
33027
+ init() {
33028
+ this.skipForceUpdateCheck = true;
33029
+ this.useDevicePassphraseState = false;
33030
+ this.params = undefined;
33031
+ }
33032
+ run() {
33033
+ return __awaiter(this, void 0, void 0, function* () {
33034
+ const res = yield this.device.commands.typedCall('GetProtoVersion', 'ProtoVersion', {});
33035
+ return Promise.resolve(res.message);
33036
+ });
33037
+ }
33038
+ }
33039
+
33040
+ class Ping extends BaseMethod {
33041
+ init() {
33042
+ this.skipForceUpdateCheck = true;
33043
+ this.useDevicePassphraseState = false;
33044
+ this.params = { message: this.payload.message };
33045
+ }
33046
+ run() {
33047
+ var _a;
33048
+ return __awaiter(this, void 0, void 0, function* () {
33049
+ const res = yield this.device.commands.typedCall('Ping', 'Success', {
33050
+ message: (_a = this.params.message) !== null && _a !== void 0 ? _a : '',
33051
+ });
33052
+ return Promise.resolve(res.message);
33053
+ });
33054
+ }
33055
+ }
33056
+
33057
+ class DevReboot extends BaseMethod {
33058
+ init() {
33059
+ this.skipForceUpdateCheck = true;
33060
+ this.useDevicePassphraseState = false;
33061
+ this.params = {
33062
+ rebootType: this.payload.rebootType,
33063
+ reboot_type: this.payload.reboot_type,
33064
+ };
33065
+ }
33066
+ run() {
33067
+ var _a;
33068
+ return __awaiter(this, void 0, void 0, function* () {
33069
+ const res = yield this.device.commands.typedCall('DevReboot', 'Success', {
33070
+ reboot_type: normalizeRebootType((_a = this.params.reboot_type) !== null && _a !== void 0 ? _a : this.params.rebootType),
33071
+ });
33072
+ return Promise.resolve(res.message);
33073
+ });
33074
+ }
33075
+ }
33076
+
33077
+ class DevGetDeviceInfo extends BaseMethod {
33078
+ init() {
33079
+ this.skipForceUpdateCheck = true;
33080
+ this.useDevicePassphraseState = false;
33081
+ this.params = {
33082
+ targets: this.payload.targets,
33083
+ types: this.payload.types,
33084
+ targetHw: this.payload.targetHw,
33085
+ targetFw: this.payload.targetFw,
33086
+ targetBt: this.payload.targetBt,
33087
+ targetSe1: this.payload.targetSe1,
33088
+ targetSe2: this.payload.targetSe2,
33089
+ targetSe3: this.payload.targetSe3,
33090
+ targetSe4: this.payload.targetSe4,
33091
+ targetStatus: this.payload.targetStatus,
33092
+ includeVersion: this.payload.includeVersion,
33093
+ includeBuildId: this.payload.includeBuildId,
33094
+ includeHash: this.payload.includeHash,
33095
+ includeSpecific: this.payload.includeSpecific,
33096
+ };
33097
+ }
33098
+ run() {
33099
+ return __awaiter(this, void 0, void 0, function* () {
33100
+ const res = yield this.device.commands.typedCall('DevGetDeviceInfo', 'DeviceInfo', {
33101
+ targets: buildTargets(this.params),
33102
+ types: buildTypes(this.params),
33103
+ });
33104
+ return Promise.resolve(res.message);
33105
+ });
33106
+ }
33107
+ }
33108
+
33109
+ class DevGetOnboardingStatus extends BaseMethod {
33110
+ init() {
33111
+ this.skipForceUpdateCheck = true;
33112
+ this.useDevicePassphraseState = false;
33113
+ this.params = undefined;
33114
+ }
33115
+ run() {
33116
+ return __awaiter(this, void 0, void 0, function* () {
33117
+ const res = yield this.device.commands.typedCall('DevGetOnboardingStatus', 'DevOnboardingStatus', {});
33118
+ return Promise.resolve(res.message);
33119
+ });
33120
+ }
33121
+ }
33122
+
33123
+ class DevFirmwareUpdate extends BaseMethod {
33124
+ init() {
33125
+ this.skipForceUpdateCheck = true;
33126
+ this.useDevicePassphraseState = false;
33127
+ this.params = {
33128
+ targets: this.payload.targets,
33129
+ targetId: this.payload.targetId,
33130
+ target_id: this.payload.target_id,
33131
+ path: this.payload.path,
33132
+ };
33133
+ }
33134
+ run() {
33135
+ return __awaiter(this, void 0, void 0, function* () {
33136
+ const res = yield this.device.commands.typedCall('DevFirmwareUpdate', PROTOCOL_V2_FIRMWARE_UPDATE_RESPONSE_TYPES, {
33137
+ targets: normalizeFirmwareTargets(this.params),
33138
+ }, PROTOCOL_V2_FIRMWARE_UPDATE_OPTIONS);
33139
+ return Promise.resolve(res.message);
33140
+ });
33141
+ }
33142
+ }
33143
+
33144
+ class DevGetFirmwareUpdateStatus extends BaseMethod {
33145
+ init() {
33146
+ this.skipForceUpdateCheck = true;
33147
+ this.useDevicePassphraseState = false;
33148
+ this.params = undefined;
33149
+ }
33150
+ run() {
33151
+ return __awaiter(this, void 0, void 0, function* () {
33152
+ const res = yield this.device.commands.typedCall('DevGetFirmwareUpdateStatus', 'DevFirmwareUpdateStatus', {});
33153
+ return Promise.resolve(res.message);
33154
+ });
33155
+ }
33156
+ }
33157
+
33158
+ class FactoryDeviceInfoSettings extends BaseMethod {
33159
+ init() {
33160
+ this.skipForceUpdateCheck = true;
33161
+ this.useDevicePassphraseState = false;
33162
+ this.params = {
33163
+ serial_no: this.payload.serial_no,
33164
+ serialNo: this.payload.serialNo,
33165
+ cpu_info: this.payload.cpu_info,
33166
+ cpuInfo: this.payload.cpuInfo,
33167
+ pre_firmware: this.payload.pre_firmware,
33168
+ preFirmware: this.payload.preFirmware,
33169
+ };
33170
+ }
33171
+ run() {
33172
+ var _a, _b, _c;
33173
+ return __awaiter(this, void 0, void 0, function* () {
33174
+ const res = yield this.device.commands.typedCall('FactoryDeviceInfoSettings', 'Success', {
33175
+ serial_no: (_a = this.params.serial_no) !== null && _a !== void 0 ? _a : this.params.serialNo,
33176
+ cpu_info: (_b = this.params.cpu_info) !== null && _b !== void 0 ? _b : this.params.cpuInfo,
33177
+ pre_firmware: (_c = this.params.pre_firmware) !== null && _c !== void 0 ? _c : this.params.preFirmware,
33178
+ });
33179
+ return Promise.resolve(res.message);
33180
+ });
33181
+ }
33182
+ }
33183
+
33184
+ class FactoryGetDeviceInfo extends BaseMethod {
33185
+ init() {
33186
+ this.skipForceUpdateCheck = true;
33187
+ this.useDevicePassphraseState = false;
33188
+ this.params = undefined;
33189
+ }
33190
+ run() {
33191
+ return __awaiter(this, void 0, void 0, function* () {
33192
+ const res = yield this.device.commands.typedCall('FactoryGetDeviceInfo', 'FactoryDeviceInfo', {});
33193
+ return Promise.resolve(res.message);
33194
+ });
33195
+ }
33196
+ }
33197
+
33198
+ class FilesystemFixPermission extends BaseMethod {
33199
+ init() {
33200
+ this.skipForceUpdateCheck = true;
33201
+ this.useDevicePassphraseState = false;
33202
+ this.params = undefined;
33203
+ }
33204
+ run() {
33205
+ return __awaiter(this, void 0, void 0, function* () {
33206
+ const res = yield this.device.commands.typedCall('FilesystemFixPermission', 'Success', {});
33207
+ return Promise.resolve(res.message);
33208
+ });
33209
+ }
33210
+ }
33211
+
33212
+ class FilesystemFormat extends BaseMethod {
33213
+ init() {
33214
+ this.skipForceUpdateCheck = true;
33215
+ this.useDevicePassphraseState = false;
33216
+ this.params = undefined;
33217
+ }
33218
+ run() {
33219
+ return __awaiter(this, void 0, void 0, function* () {
33220
+ const res = yield this.device.commands.typedCall('FilesystemFormat', 'Success', {});
33221
+ return Promise.resolve(res.message);
33222
+ });
33223
+ }
33224
+ }
33225
+
33226
+ const MIN_FILE_READ_CHUNK_SIZE = 64;
33227
+ function getProtocolV2FileReadChunkLimit() {
33228
+ const env = DataManager.getSettings('env');
33229
+ if (env && DataManager.isBleConnect(env)) {
33230
+ return hdTransport.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
33231
+ }
33232
+ return hdTransport.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
33233
+ }
33234
+ function normalizeChunkSize$1(value, maxChunkSize) {
33235
+ const numeric = Number(value);
33236
+ if (!Number.isFinite(numeric) || numeric <= 0)
33237
+ return maxChunkSize;
33238
+ return Math.min(Math.max(Math.floor(numeric), MIN_FILE_READ_CHUNK_SIZE), maxChunkSize);
33239
+ }
33240
+ function toFiniteNumber(value) {
33241
+ if (typeof value === 'number' && Number.isFinite(value))
33242
+ return value;
33243
+ if (typeof value === 'string') {
33244
+ const numeric = Number(value);
33245
+ return Number.isFinite(numeric) ? numeric : undefined;
33246
+ }
33247
+ if (value && typeof value === 'object') {
33248
+ const longLike = value;
33249
+ if (typeof longLike.toNumber === 'function') {
33250
+ const numeric = longLike.toNumber();
33251
+ return Number.isFinite(numeric) ? numeric : undefined;
33252
+ }
33253
+ }
33254
+ return undefined;
33255
+ }
33256
+ function toUint8Array(value) {
33257
+ if (value instanceof Uint8Array)
33258
+ return value;
33259
+ if (value instanceof ArrayBuffer)
33260
+ return new Uint8Array(value);
33261
+ if (ArrayBuffer.isView(value)) {
33262
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
33263
+ }
33264
+ if (typeof value === 'string') {
33265
+ const hex = stripHexPrefix(value);
33266
+ if (!hex)
33267
+ return new Uint8Array(0);
33268
+ if (!isHexString(hex) || hex.length % 2 !== 0)
33269
+ return new Uint8Array(0);
33270
+ return hexToBytes(hex);
33271
+ }
33272
+ return new Uint8Array(0);
33273
+ }
33274
+ class FileRead extends BaseMethod {
33275
+ init() {
33276
+ var _a, _b;
33277
+ this.skipForceUpdateCheck = true;
33278
+ this.useDevicePassphraseState = false;
33279
+ this.params = {
33280
+ path: this.payload.path,
33281
+ offset: (_a = this.payload.offset) !== null && _a !== void 0 ? _a : 0,
33282
+ totalSize: (_b = this.payload.totalSize) !== null && _b !== void 0 ? _b : 0,
33283
+ chunkLen: this.payload.chunkLen,
33284
+ uiPercentage: this.payload.uiPercentage,
33285
+ };
33286
+ }
33287
+ run() {
33288
+ var _a, _b, _c, _d, _e, _f;
33289
+ return __awaiter(this, void 0, void 0, function* () {
33290
+ const startOffset = (_a = this.params.offset) !== null && _a !== void 0 ? _a : 0;
33291
+ const requestedLength = Number(this.params.totalSize);
33292
+ const chunkSize = normalizeChunkSize$1(this.params.chunkLen, getProtocolV2FileReadChunkLimit());
33293
+ let totalLength = Number.isFinite(requestedLength) && requestedLength > 0 ? requestedLength : 0;
33294
+ if (totalLength === 0) {
33295
+ const pathInfoRes = yield this.device.commands.typedCall('FilesystemPathInfoQuery', 'FilesystemPathInfo', {
33296
+ path: this.params.path,
33297
+ });
33298
+ const fileSize = toFiniteNumber((_b = pathInfoRes.message) === null || _b === void 0 ? void 0 : _b.size);
33299
+ if (!((_c = pathInfoRes.message) === null || _c === void 0 ? void 0 : _c.exist) || ((_d = pathInfoRes.message) === null || _d === void 0 ? void 0 : _d.directory)) {
33300
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileRead path is not a file: ${this.params.path}`);
33301
+ }
33302
+ if (fileSize === undefined || fileSize < startOffset) {
33303
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileRead invalid offset ${startOffset} for ${this.params.path}`);
33304
+ }
33305
+ totalLength = fileSize - startOffset;
33306
+ }
33307
+ const chunks = [];
33308
+ let read = 0;
33309
+ let lastMessage;
33310
+ while (read < totalLength) {
33311
+ const readLen = Math.min(chunkSize, totalLength - read);
33312
+ const offset = startOffset + read;
33313
+ const progress = (_e = this.params.uiPercentage) !== null && _e !== void 0 ? _e : Math.min(Math.ceil(((read + readLen) / Math.max(totalLength, 1)) * 100), 99);
33314
+ const res = yield this.device.commands.typedCall('FilesystemFileRead', 'FilesystemFile', {
33315
+ file: {
33316
+ path: this.params.path,
33317
+ offset,
33318
+ total_size: 0,
33319
+ },
33320
+ chunk_len: readLen,
33321
+ ui_percentage: progress,
33322
+ });
33323
+ const data = toUint8Array((_f = res.message) === null || _f === void 0 ? void 0 : _f.data);
33324
+ lastMessage = res.message;
33325
+ if (data.byteLength === 0) {
33326
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileRead received empty data at offset ${offset}`);
33327
+ }
33328
+ chunks.push(data);
33329
+ read += data.byteLength;
33330
+ }
33331
+ const combined = new Uint8Array(read);
33332
+ let cursor = 0;
33333
+ chunks.forEach(chunk => {
33334
+ combined.set(chunk, cursor);
33335
+ cursor += chunk.byteLength;
33336
+ });
33337
+ return Promise.resolve(Object.assign(Object.assign({}, lastMessage), { path: this.params.path, offset: startOffset, total_size: totalLength, data: combined, chunks: chunks.length }));
33338
+ });
33339
+ }
33340
+ }
33341
+
33342
+ const MIN_FILE_CHUNK_SIZE = 64;
33343
+ function getProtocolV2FileChunkLimit() {
33344
+ const env = DataManager.getSettings('env');
33345
+ if (env && DataManager.isBleConnect(env)) {
33346
+ return hdTransport.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
33347
+ }
33348
+ return hdTransport.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
33349
+ }
33350
+ function dataToUint8Array(data) {
33351
+ return __awaiter(this, void 0, void 0, function* () {
33352
+ if (typeof data === 'string') {
33353
+ return new TextEncoder().encode(data);
33354
+ }
33355
+ if (data instanceof ArrayBuffer) {
33356
+ return new Uint8Array(data);
33357
+ }
33358
+ if (ArrayBuffer.isView(data)) {
33359
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
33360
+ }
33361
+ if (typeof Blob !== 'undefined' && data instanceof Blob) {
33362
+ return new Uint8Array(yield data.arrayBuffer());
33363
+ }
33364
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Unsupported FilesystemFileWrite data');
33365
+ });
33366
+ }
33367
+ function normalizeChunkSize(value, maxChunkSize) {
33368
+ const numeric = Number(value);
33369
+ if (!Number.isFinite(numeric) || numeric <= 0)
33370
+ return maxChunkSize;
33371
+ return Math.min(Math.max(Math.floor(numeric), MIN_FILE_CHUNK_SIZE), maxChunkSize);
33372
+ }
33373
+ function getConfirmedProgress(processedByte, totalSize, written, dataLength) {
33374
+ if (Number.isFinite(processedByte) && Number.isFinite(totalSize) && totalSize > 0) {
33375
+ if (processedByte >= totalSize)
33376
+ return 100;
33377
+ return Math.min(Math.max(Math.floor((processedByte / totalSize) * 100), 0), 99);
33378
+ }
33379
+ if (dataLength > 0) {
33380
+ if (written >= dataLength)
33381
+ return 100;
33382
+ return Math.min(Math.max(Math.floor((written / dataLength) * 100), 0), 99);
33383
+ }
33384
+ return 100;
33385
+ }
33386
+ class FileWrite extends BaseMethod {
33387
+ init() {
33388
+ var _a, _b, _c, _d;
33389
+ this.skipForceUpdateCheck = true;
33390
+ this.useDevicePassphraseState = false;
33391
+ const offset = (_a = this.payload.offset) !== null && _a !== void 0 ? _a : 0;
33392
+ this.params = {
33393
+ path: this.payload.path,
33394
+ offset,
33395
+ totalSize: (_b = this.payload.totalSize) !== null && _b !== void 0 ? _b : 0,
33396
+ data: this.payload.data,
33397
+ chunkSize: this.payload.chunkSize,
33398
+ chunkLen: this.payload.chunkLen,
33399
+ overwrite: (_c = this.payload.overwrite) !== null && _c !== void 0 ? _c : offset === 0,
33400
+ append: (_d = this.payload.append) !== null && _d !== void 0 ? _d : false,
33401
+ uiPercentage: this.payload.uiPercentage,
33402
+ };
33403
+ }
33404
+ run() {
33405
+ var _a, _b, _c, _d, _e, _f;
33406
+ return __awaiter(this, void 0, void 0, function* () {
33407
+ const data = yield dataToUint8Array(this.params.data);
33408
+ const dataLength = data.byteLength;
33409
+ const offsetValue = Number((_a = this.params.offset) !== null && _a !== void 0 ? _a : 0);
33410
+ const startOffset = Number.isFinite(offsetValue) && offsetValue > 0 ? offsetValue : 0;
33411
+ const payloadTotalSize = Number(this.params.totalSize);
33412
+ const totalSize = Number.isFinite(payloadTotalSize) && payloadTotalSize > 0
33413
+ ? payloadTotalSize
33414
+ : startOffset + dataLength;
33415
+ if (totalSize < startOffset + dataLength) {
33416
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileWrite totalSize ${totalSize} is smaller than offset + data length ${startOffset + dataLength}`);
33417
+ }
33418
+ const chunkSize = normalizeChunkSize((_b = this.params.chunkSize) !== null && _b !== void 0 ? _b : this.params.chunkLen, getProtocolV2FileChunkLimit());
33419
+ const overwrite = (_c = this.params.overwrite) !== null && _c !== void 0 ? _c : false;
33420
+ const append = (_d = this.params.append) !== null && _d !== void 0 ? _d : false;
33421
+ let written = 0;
33422
+ let chunkIndex = 0;
33423
+ let lastMessage;
33424
+ const startTime = Date.now();
33425
+ while (written < dataLength) {
33426
+ const chunkEnd = Math.min(written + chunkSize, dataLength);
33427
+ const chunk = data.slice(written, chunkEnd);
33428
+ const offset = startOffset + written;
33429
+ const isFirstChunk = chunkIndex === 0;
33430
+ const progress = (_e = this.params.uiPercentage) !== null && _e !== void 0 ? _e : Math.min(Math.ceil(((written + chunk.byteLength) / dataLength) * 100), 99);
33431
+ const res = yield this.device.commands.typedCall('FilesystemFileWrite', 'FilesystemFile', {
33432
+ file: {
33433
+ path: this.params.path,
33434
+ offset,
33435
+ total_size: totalSize,
33436
+ data: chunk,
33437
+ },
33438
+ overwrite: isFirstChunk ? overwrite : false,
33439
+ append,
33440
+ ui_percentage: progress,
33441
+ });
33442
+ lastMessage = res.message;
33443
+ const processedByte = Number((_f = res.message) === null || _f === void 0 ? void 0 : _f.processed_byte);
33444
+ if (Number.isFinite(processedByte) && processedByte > offset) {
33445
+ written = processedByte - startOffset;
33446
+ }
33447
+ else {
33448
+ written += chunk.byteLength;
33449
+ }
33450
+ if (written > dataLength) {
33451
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `FilesystemFileWrite invalid processed_byte ${processedByte}`);
33452
+ }
33453
+ const confirmedProcessedByte = Number.isFinite(processedByte) && processedByte > offset
33454
+ ? processedByte
33455
+ : startOffset + written;
33456
+ if (typeof this.postMessage === 'function') {
33457
+ const elapsedMs = Date.now() - startTime;
33458
+ const transferredBytes = Math.min(written, dataLength);
33459
+ this.postMessage(createUiMessage(UI_REQUEST.DEVICE_PROGRESS, {
33460
+ progress: getConfirmedProgress(confirmedProcessedByte, totalSize, written, dataLength),
33461
+ transferredBytes,
33462
+ totalBytes: dataLength,
33463
+ rateBytesPerSecond: elapsedMs > 0 ? Math.round((transferredBytes / elapsedMs) * 1000) : undefined,
33464
+ elapsedMs,
33465
+ }));
33466
+ }
33467
+ chunkIndex += 1;
33468
+ }
33469
+ return Promise.resolve(Object.assign(Object.assign({}, lastMessage), { path: this.params.path, offset: startOffset, total_size: totalSize, processed_byte: startOffset + written, chunks: chunkIndex }));
33470
+ });
33471
+ }
33472
+ }
33473
+
33474
+ class FileDelete extends BaseMethod {
33475
+ init() {
33476
+ this.skipForceUpdateCheck = true;
33477
+ this.useDevicePassphraseState = false;
33478
+ this.params = { path: this.payload.path };
33479
+ }
33480
+ run() {
33481
+ return __awaiter(this, void 0, void 0, function* () {
33482
+ const res = yield this.device.commands.typedCall('FilesystemFileDelete', 'Success', {
33483
+ path: this.params.path,
33484
+ });
33485
+ return Promise.resolve(res.message);
33486
+ });
33487
+ }
33488
+ }
33489
+
33490
+ class DirList extends BaseMethod {
33491
+ init() {
33492
+ this.skipForceUpdateCheck = true;
33493
+ this.useDevicePassphraseState = false;
33494
+ this.params = {
33495
+ path: this.payload.path,
33496
+ depth: this.payload.depth,
33497
+ };
33498
+ }
33499
+ run() {
33500
+ return __awaiter(this, void 0, void 0, function* () {
33501
+ const res = yield this.device.commands.typedCall('FilesystemDirList', 'FilesystemDir', {
33502
+ path: this.params.path,
33503
+ depth: this.params.depth,
33504
+ });
33505
+ return Promise.resolve(res.message);
33506
+ });
33507
+ }
33508
+ }
33509
+
33510
+ class DirMake extends BaseMethod {
33511
+ init() {
33512
+ this.skipForceUpdateCheck = true;
33513
+ this.useDevicePassphraseState = false;
33514
+ this.params = { path: this.payload.path };
33515
+ }
33516
+ run() {
33517
+ return __awaiter(this, void 0, void 0, function* () {
33518
+ const res = yield this.device.commands.typedCall('FilesystemDirMake', 'Success', {
33519
+ path: this.params.path,
33520
+ });
33521
+ return Promise.resolve(res.message);
33522
+ });
33523
+ }
33524
+ }
33525
+
33526
+ class DirRemove extends BaseMethod {
33527
+ init() {
33528
+ this.skipForceUpdateCheck = true;
33529
+ this.useDevicePassphraseState = false;
33530
+ this.params = { path: this.payload.path };
33531
+ }
33532
+ run() {
33533
+ return __awaiter(this, void 0, void 0, function* () {
33534
+ const res = yield this.device.commands.typedCall('FilesystemDirRemove', 'Success', {
33535
+ path: this.params.path,
33536
+ });
33537
+ return Promise.resolve(res.message);
33538
+ });
33539
+ }
33540
+ }
33541
+
33542
+ class PathInfo extends BaseMethod {
33543
+ init() {
33544
+ this.skipForceUpdateCheck = true;
33545
+ this.useDevicePassphraseState = false;
33546
+ this.params = { path: this.payload.path };
33547
+ }
33548
+ run() {
33549
+ return __awaiter(this, void 0, void 0, function* () {
33550
+ const res = yield this.device.commands.typedCall('FilesystemPathInfoQuery', 'FilesystemPathInfo', {
33551
+ path: this.params.path,
33552
+ });
33553
+ return Promise.resolve(res.message);
33554
+ });
33555
+ }
33556
+ }
33557
+
31128
33558
  class CipherKeyValue extends BaseMethod {
31129
33559
  constructor() {
31130
33560
  super(...arguments);
@@ -40059,7 +42489,33 @@ var ApiMethods = /*#__PURE__*/Object.freeze({
40059
42489
  firmwareUpdate: FirmwareUpdate,
40060
42490
  firmwareUpdateV2: FirmwareUpdateV2,
40061
42491
  firmwareUpdateV3: FirmwareUpdateV3,
42492
+ firmwareUpdateV4: FirmwareUpdateV4,
40062
42493
  promptWebDeviceAccess: PromptWebDeviceAccess,
42494
+ getProtoVersion: GetProtoVersion,
42495
+ ping: Ping,
42496
+ devReboot: DevReboot,
42497
+ devGetDeviceInfo: DevGetDeviceInfo,
42498
+ devGetOnboardingStatus: DevGetOnboardingStatus,
42499
+ devFirmwareUpdate: DevFirmwareUpdate,
42500
+ devGetFirmwareUpdateStatus: DevGetFirmwareUpdateStatus,
42501
+ factoryDeviceInfoSettings: FactoryDeviceInfoSettings,
42502
+ factoryGetDeviceInfo: FactoryGetDeviceInfo,
42503
+ filesystemFixPermission: FilesystemFixPermission,
42504
+ filesystemFormat: FilesystemFormat,
42505
+ fileRead: FileRead,
42506
+ fileWrite: FileWrite,
42507
+ fileDelete: FileDelete,
42508
+ dirList: DirList,
42509
+ dirMake: DirMake,
42510
+ dirRemove: DirRemove,
42511
+ pathInfo: PathInfo,
42512
+ filesystemFileRead: FileRead,
42513
+ filesystemFileWrite: FileWrite,
42514
+ filesystemFileDelete: FileDelete,
42515
+ filesystemDirList: DirList,
42516
+ filesystemDirMake: DirMake,
42517
+ filesystemDirRemove: DirRemove,
42518
+ filesystemPathInfoQuery: PathInfo,
40063
42519
  cipherKeyValue: CipherKeyValue,
40064
42520
  allNetworkGetAddress: AllNetworkGetAddress,
40065
42521
  allNetworkGetAddressByLoop: AllNetworkGetAddressByLoop,
@@ -40231,17 +42687,31 @@ class DeviceConnector {
40231
42687
  stop() {
40232
42688
  this.listening = false;
40233
42689
  }
40234
- acquire(path, session, forceCleanRunPromise) {
42690
+ acquire(path, session, forceCleanRunPromise, connectProtocol) {
40235
42691
  return __awaiter(this, void 0, void 0, function* () {
40236
- Log$2.debug('acquire', path, session);
42692
+ Log$2.debug('acquire', path, session, connectProtocol);
40237
42693
  const env = DataManager.getSettings('env');
40238
42694
  try {
40239
42695
  let res;
40240
42696
  if (DataManager.isBleConnect(env)) {
40241
- res = yield this.transport.acquire({ uuid: path, forceCleanRunPromise });
42697
+ res = yield this.transport.acquire({
42698
+ uuid: path,
42699
+ forceCleanRunPromise,
42700
+ expectedProtocol: connectProtocol,
42701
+ });
40242
42702
  }
40243
42703
  else {
40244
- res = yield this.transport.acquire({ path, previous: session !== null && session !== void 0 ? session : null });
42704
+ res = yield this.transport.acquire({
42705
+ path,
42706
+ previous: session !== null && session !== void 0 ? session : null,
42707
+ expectedProtocol: connectProtocol,
42708
+ });
42709
+ }
42710
+ if (connectProtocol) {
42711
+ const detectedProtocol = this.transport.getProtocolType(path);
42712
+ if (detectedProtocol !== connectProtocol) {
42713
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${connectProtocol}, detected ${detectedProtocol}`);
42714
+ }
40245
42715
  }
40246
42716
  return res;
40247
42717
  }
@@ -40428,6 +42898,7 @@ const parseInitOptions = (method) => ({
40428
42898
  passphraseState: method === null || method === void 0 ? void 0 : method.payload.passphraseState,
40429
42899
  deviceId: method === null || method === void 0 ? void 0 : method.payload.deviceId,
40430
42900
  deriveCardano: method && hasDeriveCardano(method),
42901
+ connectProtocol: method === null || method === void 0 ? void 0 : method.payload.connectProtocol,
40431
42902
  });
40432
42903
  let _core;
40433
42904
  let _deviceList;
@@ -40799,6 +43270,7 @@ function initDevice(method) {
40799
43270
  }
40800
43271
  else if (allDevices.length > 1) {
40801
43272
  throw hdShared.ERRORS.TypedError([
43273
+ 'firmwareUpdateV4',
40802
43274
  'firmwareUpdateV3',
40803
43275
  'firmwareUpdateV2',
40804
43276
  'checkFirmwareRelease',
@@ -40837,18 +43309,28 @@ function initDeviceForBle(method) {
40837
43309
  return device;
40838
43310
  }
40839
43311
  let bleTimeoutRetry = 0;
43312
+ function isRetryableBleProtocolV2ProbeError(method, error) {
43313
+ const message = error instanceof Error ? error.message : String(error !== null && error !== void 0 ? error : '');
43314
+ return (method.payload.connectProtocol === 'V2' &&
43315
+ message.includes('Device protocol mismatch') &&
43316
+ message.includes('expected V2') &&
43317
+ message.includes('did not respond to expected protocol'));
43318
+ }
40840
43319
  function connectDeviceForBle(method, device) {
40841
43320
  var _a;
40842
43321
  return __awaiter(this, void 0, void 0, function* () {
40843
43322
  try {
40844
- yield device.acquire();
43323
+ yield device.acquire(method.payload.connectProtocol);
40845
43324
  if ((_a = method.payload) === null || _a === void 0 ? void 0 : _a.onlyConnectBleDevice) {
40846
43325
  return;
40847
43326
  }
40848
43327
  yield device.initialize(parseInitOptions(method));
40849
43328
  }
40850
43329
  catch (err) {
40851
- if (err.errorCode === hdShared.HardwareErrorCode.BleTimeoutError && bleTimeoutRetry <= 5) {
43330
+ if ((err.errorCode === hdShared.HardwareErrorCode.BleTimeoutError ||
43331
+ err.errorCode === hdShared.HardwareErrorCode.BleConnectedError ||
43332
+ isRetryableBleProtocolV2ProbeError(method, err)) &&
43333
+ bleTimeoutRetry <= 5) {
40852
43334
  bleTimeoutRetry += 1;
40853
43335
  Log.debug(`Bletooth connect timeout and will retry, retry count: ${bleTimeoutRetry}`);
40854
43336
  yield wait(3000);