@onekeyfe/hd-core 1.2.0-alpha.47 → 1.2.0-alpha.49

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 (62) hide show
  1. package/__tests__/check-all-firmware-release-protocol-v2.test.ts +110 -15
  2. package/__tests__/device-lifecycle-events.test.ts +105 -3
  3. package/__tests__/method-protocol-support.test.ts +19 -0
  4. package/__tests__/protocol-binding.test.ts +89 -0
  5. package/__tests__/protocol-v2-resources.test.ts +87 -42
  6. package/__tests__/protocol-v2.test.ts +347 -40
  7. package/__tests__/search-devices.test.ts +12 -3
  8. package/dist/api/CheckAllFirmwareRelease.d.ts.map +1 -1
  9. package/dist/api/DetectDeviceConnectProtocol.d.ts +7 -0
  10. package/dist/api/DetectDeviceConnectProtocol.d.ts.map +1 -0
  11. package/dist/api/FirmwareUpdate.d.ts.map +1 -1
  12. package/dist/api/FirmwareUpdateV2.d.ts.map +1 -1
  13. package/dist/api/FirmwareUpdateV3.d.ts.map +1 -1
  14. package/dist/api/FirmwareUpdateV4.d.ts +1 -0
  15. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  16. package/dist/api/SearchDevices.d.ts.map +1 -1
  17. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts.map +1 -1
  18. package/dist/api/firmware/uploadFirmware.d.ts.map +1 -1
  19. package/dist/api/index.d.ts +1 -0
  20. package/dist/api/index.d.ts.map +1 -1
  21. package/dist/core/index.d.ts.map +1 -1
  22. package/dist/device/Device.d.ts +5 -1
  23. package/dist/device/Device.d.ts.map +1 -1
  24. package/dist/device/DevicePool.d.ts.map +1 -1
  25. package/dist/index.d.ts +20 -3
  26. package/dist/index.js +361 -203
  27. package/dist/inject.d.ts +6 -1
  28. package/dist/inject.d.ts.map +1 -1
  29. package/dist/lowLevelInject.d.ts.map +1 -1
  30. package/dist/protocols/protocol-v2/resources.d.ts +4 -4
  31. package/dist/protocols/protocol-v2/resources.d.ts.map +1 -1
  32. package/dist/topLevelInject.d.ts.map +1 -1
  33. package/dist/types/api/detectDeviceConnectProtocol.d.ts +4 -0
  34. package/dist/types/api/detectDeviceConnectProtocol.d.ts.map +1 -0
  35. package/dist/types/api/index.d.ts +4 -0
  36. package/dist/types/api/index.d.ts.map +1 -1
  37. package/dist/types/params.d.ts +1 -0
  38. package/dist/types/params.d.ts.map +1 -1
  39. package/dist/utils/patch.d.ts +1 -1
  40. package/dist/utils/patch.d.ts.map +1 -1
  41. package/package.json +4 -4
  42. package/src/api/CheckAllFirmwareRelease.ts +10 -9
  43. package/src/api/DetectDeviceConnectProtocol.ts +18 -0
  44. package/src/api/FirmwareUpdate.ts +6 -2
  45. package/src/api/FirmwareUpdateV2.ts +5 -2
  46. package/src/api/FirmwareUpdateV3.ts +6 -2
  47. package/src/api/FirmwareUpdateV4.ts +73 -43
  48. package/src/api/SearchDevices.ts +3 -1
  49. package/src/api/firmware/FirmwareUpdateBaseMethod.ts +15 -4
  50. package/src/api/firmware/uploadFirmware.ts +17 -4
  51. package/src/api/index.ts +1 -0
  52. package/src/core/index.ts +11 -2
  53. package/src/data/messages/messages-protocol-v2.json +0 -43
  54. package/src/device/Device.ts +53 -15
  55. package/src/device/DevicePool.ts +7 -2
  56. package/src/inject.ts +57 -2
  57. package/src/lowLevelInject.ts +6 -3
  58. package/src/protocols/protocol-v2/resources.ts +150 -56
  59. package/src/topLevelInject.ts +6 -3
  60. package/src/types/api/detectDeviceConnectProtocol.ts +7 -0
  61. package/src/types/api/index.ts +11 -0
  62. package/src/types/params.ts +7 -1
package/dist/index.js CHANGED
@@ -101,26 +101,61 @@ const executeCallback = (id, ...args) => {
101
101
  const cleanupCallback = (id) => {
102
102
  callbackManager.delete(id);
103
103
  };
104
+ const normalizeConnectId = (connectId) => connectId.trim().toLowerCase();
105
+ const createProtocolAwareCall = (rawCall) => {
106
+ const protocolByConnectId = new Map();
107
+ const setDeviceConnectProtocol = (connectId, connectProtocol) => {
108
+ const normalizedConnectId = normalizeConnectId(connectId);
109
+ if (!normalizedConnectId)
110
+ return;
111
+ if (connectProtocol) {
112
+ protocolByConnectId.set(normalizedConnectId, connectProtocol);
113
+ }
114
+ else {
115
+ protocolByConnectId.delete(normalizedConnectId);
116
+ }
117
+ };
118
+ const call = params => {
119
+ if (!params || typeof params !== 'object') {
120
+ return rawCall(params);
121
+ }
122
+ const connectId = typeof params.connectId === 'string' ? params.connectId : undefined;
123
+ const boundProtocol = connectId
124
+ ? protocolByConnectId.get(normalizeConnectId(connectId))
125
+ : undefined;
126
+ if (boundProtocol &&
127
+ params.connectProtocol === undefined &&
128
+ params.forceProtocolDetection !== true) {
129
+ return rawCall(Object.assign(Object.assign({}, params), { connectProtocol: boundProtocol }));
130
+ }
131
+ return rawCall(params);
132
+ };
133
+ return { call, setDeviceConnectProtocol };
134
+ };
104
135
  const inject = ({ call, cancel, dispose, eventEmitter, init, updateSettings, switchTransport, uiResponse, }) => {
136
+ const protocolAwareCall = createProtocolAwareCall(call);
105
137
  const api = Object.assign({ on: (type, fn) => {
106
138
  eventEmitter.on(type, fn);
107
139
  }, emit: () => { }, off: (type, fn) => {
108
140
  eventEmitter.removeListener(type, fn);
109
141
  }, removeAllListeners: type => {
110
142
  eventEmitter.removeAllListeners(type);
111
- }, init,
112
- call,
113
- dispose,
143
+ }, init, call: protocolAwareCall.call, setDeviceConnectProtocol: protocolAwareCall.setDeviceConnectProtocol, dispose,
114
144
  uiResponse,
115
145
  cancel,
116
146
  updateSettings,
117
- switchTransport }, createCoreApi(call));
147
+ switchTransport }, createCoreApi(protocolAwareCall.call));
118
148
  return api;
119
149
  };
120
150
  const createCoreApi = (call) => ({
121
151
  getLogs: () => call({ method: 'getLogs' }),
122
152
  clearSessionCache: params => call(Object.assign(Object.assign({}, params), { method: 'clearSessionCache' })),
123
153
  searchDevices: params => call(Object.assign(Object.assign({}, params), { method: 'searchDevices' })),
154
+ detectDeviceConnectProtocol: connectId => call({
155
+ connectId,
156
+ method: 'detectDeviceConnectProtocol',
157
+ forceProtocolDetection: true,
158
+ }),
124
159
  getFeatures: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'getFeatures' })),
125
160
  getDeviceState: (connectId, params) => {
126
161
  const _a = (params !== null && params !== void 0 ? params : {}), commonParams = __rest(_a, ["refresh", "includeRaw"]);
@@ -277,15 +312,14 @@ const createCoreApi = (call) => ({
277
312
  });
278
313
 
279
314
  const lowLevelInject = ({ call, cancel, dispose, eventEmitter, init, uiResponse, updateSettings, switchTransport, addHardwareGlobalEventListener, }) => {
315
+ const protocolAwareCall = createProtocolAwareCall(call);
280
316
  const api = Object.assign({ addHardwareGlobalEventListener, removeAllListeners: type => {
281
317
  eventEmitter.removeAllListeners(type);
282
- }, init,
283
- call,
284
- dispose,
318
+ }, init, call: protocolAwareCall.call, setDeviceConnectProtocol: protocolAwareCall.setDeviceConnectProtocol, dispose,
285
319
  uiResponse,
286
320
  cancel,
287
321
  updateSettings,
288
- switchTransport, emit: () => { } }, createCoreApi(call));
322
+ switchTransport, emit: () => { } }, createCoreApi(protocolAwareCall.call));
289
323
  return api;
290
324
  };
291
325
 
@@ -773,6 +807,7 @@ const topLevelInject = () => {
773
807
  return Promise.resolve(undefined);
774
808
  return lowLevelApi.call(params);
775
809
  };
810
+ const protocolAwareCall = createProtocolAwareCall(call);
776
811
  const api = Object.assign(Object.assign({ on: (type, fn) => {
777
812
  eventEmitter.on(type, fn);
778
813
  }, emit: (eventName, ...args) => {
@@ -783,7 +818,7 @@ const topLevelInject = () => {
783
818
  var _a;
784
819
  lowLevelApi = hardwareLowLeverApi;
785
820
  return (_a = lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.init(settings)) !== null && _a !== void 0 ? _a : Promise.resolve(false);
786
- }, call }, createCoreApi(call)), { removeAllListeners: type => {
821
+ }, call: protocolAwareCall.call, setDeviceConnectProtocol: protocolAwareCall.setDeviceConnectProtocol }, createCoreApi(protocolAwareCall.call)), { removeAllListeners: type => {
787
822
  eventEmitter.removeAllListeners(type);
788
823
  lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.removeAllListeners(type);
789
824
  }, dispose: () => lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.dispose(), uiResponse: response => lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.uiResponse(response), cancel: (connectId) => lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.cancel(connectId), updateSettings: settings => { var _a; return (_a = lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.updateSettings(settings)) !== null && _a !== void 0 ? _a : Promise.resolve(false); }, switchTransport: (env) => { var _a; return (_a = lowLevelApi === null || lowLevelApi === void 0 ? void 0 : lowLevelApi.switchTransport(env)) !== null && _a !== void 0 ? _a : Promise.resolve({ success: false }); } });
@@ -26252,8 +26287,6 @@ var nested = {
26252
26287
  MessageType_DeviceInfo: 60601,
26253
26288
  MessageType_DeviceStatusGet: 60602,
26254
26289
  MessageType_DeviceStatus: 60603,
26255
- MessageType_ResourceInventoryGet: 60604,
26256
- MessageType_ResourceInventory: 60605,
26257
26290
  MessageType_FilesystemPermissionFix: 60800,
26258
26291
  MessageType_FilesystemPathInfo: 60801,
26259
26292
  MessageType_FilesystemPathInfoQuery: 60802,
@@ -37846,16 +37879,6 @@ var nested = {
37846
37879
  APP: 85
37847
37880
  }
37848
37881
  },
37849
- ResourceBundleType: {
37850
- values: {
37851
- IMAGES: 0,
37852
- ANIMATION: 1,
37853
- WALLPAPER: 2,
37854
- TRANSLATIONS: 3,
37855
- ROOBERT: 4,
37856
- NOTO: 5
37857
- }
37858
- },
37859
37882
  DeviceFirmwareImageInfo: {
37860
37883
  fields: {
37861
37884
  version: {
@@ -38053,38 +38076,6 @@ var nested = {
38053
38076
  }
38054
38077
  }
38055
38078
  },
38056
- ResourceInventoryGet: {
38057
- fields: {
38058
- }
38059
- },
38060
- ResourceInventoryItem: {
38061
- fields: {
38062
- type: {
38063
- rule: "required",
38064
- type: "ResourceBundleType",
38065
- id: 1
38066
- },
38067
- size: {
38068
- rule: "required",
38069
- type: "uint32",
38070
- id: 2
38071
- },
38072
- header_hash: {
38073
- rule: "required",
38074
- type: "bytes",
38075
- id: 3
38076
- }
38077
- }
38078
- },
38079
- ResourceInventory: {
38080
- fields: {
38081
- items: {
38082
- rule: "repeated",
38083
- type: "ResourceInventoryItem",
38084
- id: 1
38085
- }
38086
- }
38087
- },
38088
38079
  DeviceSessionErrorCode: {
38089
38080
  values: {
38090
38081
  DeviceSessionError_None: 0,
@@ -39485,56 +39476,120 @@ const PROTOCOL_V2_RESOURCE_DEVICE_PATHS = {
39485
39476
  const RESOURCE_TYPE_SET = new Set(PROTOCOL_V2_RESOURCE_TYPES);
39486
39477
  const SHA256_HEX_LENGTH = 64;
39487
39478
  const SHA3_512_HEX_LENGTH = 128;
39479
+ const PROTOCOL_V2_OKPP_HEADER_SIZE$1 = 0x52a0;
39480
+ const PROTOCOL_V2_OKPP_TYPE_OFFSET = 0x08;
39481
+ const PROTOCOL_V2_OKPP_HEADER_LENGTH_OFFSET = 0x0c;
39482
+ const PROTOCOL_V2_OKPP_HEADER_HASH_OFFSET$1 = 0x240;
39483
+ const PROTOCOL_V2_OKPP_HASH_SIZE$1 = 64;
39484
+ const PROTOCOL_V2_RESOURCE_IDENTITY_READ_SIZE = PROTOCOL_V2_OKPP_HEADER_HASH_OFFSET$1 + PROTOCOL_V2_OKPP_HASH_SIZE$1;
39485
+ const PROTOCOL_V2_MIN_FILE_READ_CHUNK_SIZE = 64;
39488
39486
  const PROTOCOL_V2_RESOURCE_INVENTORY_TIMEOUT_MS = 5 * 1000;
39489
- const RESOURCE_TYPE_BY_DEVICE_VALUE = {
39490
- '0': 'images',
39491
- IMAGES: 'images',
39492
- '1': 'animation',
39493
- ANIMATION: 'animation',
39494
- '2': 'wallpaper',
39495
- WALLPAPER: 'wallpaper',
39496
- '3': 'translations',
39497
- TRANSLATIONS: 'translations',
39498
- '4': 'roobert',
39499
- ROOBERT: 'roobert',
39500
- '5': 'noto',
39501
- NOTO: 'noto',
39502
- };
39503
- function parseProtocolV2ResourceInventory(value) {
39504
- const items = value === null || value === void 0 ? void 0 : value.items;
39505
- if (!Array.isArray(items)) {
39506
- throw new Error('Invalid Pro2 resource inventory: items must be an array');
39507
- }
39508
- const inventory = items.map((item, index) => {
39509
- if (!item || typeof item !== 'object') {
39510
- throw new Error(`Invalid Pro2 resource inventory item at ${index}`);
39511
- }
39512
- const raw = item;
39513
- const type = RESOURCE_TYPE_BY_DEVICE_VALUE[String(raw.type).toUpperCase()];
39514
- if (!type) {
39515
- throw new Error(`Invalid Pro2 resource inventory type at ${index}`);
39516
- }
39517
- if (!Number.isSafeInteger(raw.size) || Number(raw.size) <= 0) {
39518
- throw new Error(`Invalid Pro2 resource inventory size at ${index}`);
39487
+ function toFiniteNumber(value) {
39488
+ if (typeof value === 'number' && Number.isFinite(value))
39489
+ return value;
39490
+ if (typeof value === 'string') {
39491
+ const numeric = Number(value);
39492
+ return Number.isFinite(numeric) ? numeric : undefined;
39493
+ }
39494
+ if (value && typeof value === 'object') {
39495
+ const longLike = value;
39496
+ if (typeof longLike.toNumber === 'function') {
39497
+ const numeric = longLike.toNumber();
39498
+ return Number.isFinite(numeric) ? numeric : undefined;
39519
39499
  }
39520
- return {
39521
- type,
39522
- size: Number(raw.size),
39523
- headerHash: normalizeHex$1(raw.header_hash, SHA3_512_HEX_LENGTH, 'inventory headerHash'),
39524
- };
39525
- });
39526
- if (new Set(inventory.map(item => item.type)).size !== inventory.length) {
39527
- throw new Error('Invalid Pro2 resource inventory: duplicate resource type');
39528
39500
  }
39529
- return PROTOCOL_V2_RESOURCE_TYPES.flatMap(type => {
39530
- const item = inventory.find(candidate => candidate.type === type);
39531
- return item ? [item] : [];
39501
+ return undefined;
39502
+ }
39503
+ function toUint8Array(value) {
39504
+ if (value instanceof Uint8Array)
39505
+ return value;
39506
+ if (value instanceof ArrayBuffer)
39507
+ return new Uint8Array(value);
39508
+ if (ArrayBuffer.isView(value)) {
39509
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
39510
+ }
39511
+ if (typeof value === 'string') {
39512
+ const hex = value.replace(/^0x/i, '');
39513
+ if (!hex || hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex)) {
39514
+ return new Uint8Array(0);
39515
+ }
39516
+ const bytes = new Uint8Array(hex.length / 2);
39517
+ for (let index = 0; index < bytes.length; index += 1) {
39518
+ bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
39519
+ }
39520
+ return bytes;
39521
+ }
39522
+ return new Uint8Array(0);
39523
+ }
39524
+ function readAscii(bytes, offset, length) {
39525
+ return Array.from(bytes.slice(offset, offset + length), byte => String.fromCharCode(byte)).join('');
39526
+ }
39527
+ function parseProtocolV2ResourceHeaderHash(bytes) {
39528
+ if (bytes.byteLength < PROTOCOL_V2_RESOURCE_IDENTITY_READ_SIZE)
39529
+ return undefined;
39530
+ if (readAscii(bytes, 0, 4) !== 'OKPP')
39531
+ return undefined;
39532
+ if (readAscii(bytes, PROTOCOL_V2_OKPP_TYPE_OFFSET, 4) !== 'RESC')
39533
+ return undefined;
39534
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
39535
+ if (view.getUint32(PROTOCOL_V2_OKPP_HEADER_LENGTH_OFFSET, true) !== PROTOCOL_V2_OKPP_HEADER_SIZE$1) {
39536
+ return undefined;
39537
+ }
39538
+ return bytesToHex$3(bytes.slice(PROTOCOL_V2_OKPP_HEADER_HASH_OFFSET$1, PROTOCOL_V2_OKPP_HEADER_HASH_OFFSET$1 + PROTOCOL_V2_OKPP_HASH_SIZE$1));
39539
+ }
39540
+ function readProtocolV2ResourceIdentity({ commands, resource, chunkSize, timeoutMs = PROTOCOL_V2_RESOURCE_INVENTORY_TIMEOUT_MS, }) {
39541
+ var _a, _b, _c, _d;
39542
+ return __awaiter(this, void 0, void 0, function* () {
39543
+ const path = PROTOCOL_V2_RESOURCE_DEVICE_PATHS[resource.type];
39544
+ const pathInfo = yield commands.typedCall('FilesystemPathInfoQuery', 'FilesystemPathInfo', { path }, { timeoutMs });
39545
+ const size = toFiniteNumber((_a = pathInfo.message) === null || _a === void 0 ? void 0 : _a.size);
39546
+ if (!((_b = pathInfo.message) === null || _b === void 0 ? void 0 : _b.exist) ||
39547
+ ((_c = pathInfo.message) === null || _c === void 0 ? void 0 : _c.directory) ||
39548
+ !Number.isSafeInteger(size) ||
39549
+ size !== resource.size ||
39550
+ size < PROTOCOL_V2_OKPP_HEADER_SIZE$1) {
39551
+ return undefined;
39552
+ }
39553
+ const header = new Uint8Array(PROTOCOL_V2_RESOURCE_IDENTITY_READ_SIZE);
39554
+ let offset = 0;
39555
+ while (offset < header.byteLength) {
39556
+ const readLength = Math.min(chunkSize, header.byteLength - offset);
39557
+ const response = yield commands.typedCall('FilesystemFileRead', 'FilesystemFile', {
39558
+ file: { path, offset, total_size: 0 },
39559
+ chunk_len: readLength,
39560
+ }, { timeoutMs });
39561
+ const data = toUint8Array((_d = response.message) === null || _d === void 0 ? void 0 : _d.data);
39562
+ if (data.byteLength === 0)
39563
+ return undefined;
39564
+ const copied = Math.min(data.byteLength, header.byteLength - offset);
39565
+ header.set(data.subarray(0, copied), offset);
39566
+ offset += copied;
39567
+ }
39568
+ const headerHash = parseProtocolV2ResourceHeaderHash(header);
39569
+ return headerHash ? { type: resource.type, size, headerHash } : undefined;
39532
39570
  });
39533
39571
  }
39534
- function requestProtocolV2ResourceInventory({ commands, timeoutMs = PROTOCOL_V2_RESOURCE_INVENTORY_TIMEOUT_MS, }) {
39572
+ function readProtocolV2ResourceInventory({ commands, resources, chunkSize = hdTransport.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE, timeoutMs = PROTOCOL_V2_RESOURCE_INVENTORY_TIMEOUT_MS, }) {
39535
39573
  return __awaiter(this, void 0, void 0, function* () {
39536
- const { message } = yield commands.typedCall('ResourceInventoryGet', 'ResourceInventory', {}, { timeoutMs });
39537
- return parseProtocolV2ResourceInventory(message);
39574
+ const normalizedChunkSize = Number.isFinite(chunkSize)
39575
+ ? Math.max(Math.floor(chunkSize), PROTOCOL_V2_MIN_FILE_READ_CHUNK_SIZE)
39576
+ : hdTransport.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE;
39577
+ const inventory = [];
39578
+ for (const resource of resources) {
39579
+ try {
39580
+ const item = yield readProtocolV2ResourceIdentity({
39581
+ commands,
39582
+ resource,
39583
+ chunkSize: normalizedChunkSize,
39584
+ timeoutMs,
39585
+ });
39586
+ if (item)
39587
+ inventory.push(item);
39588
+ }
39589
+ catch (_a) {
39590
+ }
39591
+ }
39592
+ return inventory;
39538
39593
  });
39539
39594
  }
39540
39595
  function normalizeHex$1(value, expectedLength, field) {
@@ -39625,14 +39680,19 @@ function parseProtocolV2Resources(value) {
39625
39680
  }) }, (boot ? { boot } : undefined));
39626
39681
  }
39627
39682
  function buildProtocolV2ResourceUpdatePlan({ resources, inventory, mode, forced = false, }) {
39628
- if (mode === 'bootloader-recovery' || forced) {
39683
+ if (forced) {
39629
39684
  return {
39630
39685
  status: resources.length > 0 ? 'outdated' : 'valid',
39631
39686
  resources: [...resources],
39632
39687
  };
39633
39688
  }
39634
39689
  if (!inventory) {
39635
- return { status: 'unknown', resources: [] };
39690
+ return mode === 'bootloader-recovery'
39691
+ ? {
39692
+ status: resources.length > 0 ? 'outdated' : 'valid',
39693
+ resources: [...resources],
39694
+ }
39695
+ : { status: 'unknown', resources: [] };
39636
39696
  }
39637
39697
  const inventoryByType = new Map(inventory.map(item => [item.type, item]));
39638
39698
  const changedResources = resources.filter(resource => {
@@ -41945,7 +42005,9 @@ class DevicePool extends events.exports {
41945
42005
  if (!device) {
41946
42006
  device = Device.fromDescriptor(descriptor);
41947
42007
  device.deviceConnector = this.connector;
41948
- yield device.connect(initOptions === null || initOptions === void 0 ? void 0 : initOptions.connectProtocol);
42008
+ yield device.connect(initOptions === null || initOptions === void 0 ? void 0 : initOptions.connectProtocol, {
42009
+ forceProtocolDetection: initOptions === null || initOptions === void 0 ? void 0 : initOptions.forceProtocolDetection,
42010
+ });
41949
42011
  try {
41950
42012
  yield device.initialize(initOptions);
41951
42013
  if ((initOptions === null || initOptions === void 0 ? void 0 : initOptions.refreshRuntimeState) && device.isProtocolV2()) {
@@ -41971,7 +42033,10 @@ class DevicePool extends events.exports {
41971
42033
  catch (error) {
41972
42034
  refreshError = error;
41973
42035
  }
41974
- }), { connectProtocol: initOptions.connectProtocol });
42036
+ }), {
42037
+ connectProtocol: initOptions.connectProtocol,
42038
+ forceProtocolDetection: initOptions.forceProtocolDetection,
42039
+ });
41975
42040
  if (refreshError instanceof Error)
41976
42041
  throw refreshError;
41977
42042
  if (refreshError)
@@ -43717,7 +43782,7 @@ class Device extends events.exports {
43717
43782
  unavailableCapabilities: this.unavailableCapabilities,
43718
43783
  };
43719
43784
  }
43720
- connect(connectProtocol) {
43785
+ connect(connectProtocol, options) {
43721
43786
  const env = DataManager.getSettings('env');
43722
43787
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
43723
43788
  if (DataManager.isBleConnect(env)) {
@@ -43726,7 +43791,7 @@ class Device extends events.exports {
43726
43791
  return;
43727
43792
  }
43728
43793
  try {
43729
- yield this.acquire(connectProtocol);
43794
+ yield this.acquire(connectProtocol, options);
43730
43795
  resolve(true);
43731
43796
  }
43732
43797
  catch (error) {
@@ -43736,7 +43801,7 @@ class Device extends events.exports {
43736
43801
  }
43737
43802
  if (!this.mainId || (!this.isUsedHere() && this.originalDescriptor)) {
43738
43803
  try {
43739
- yield this.acquire(connectProtocol);
43804
+ yield this.acquire(connectProtocol, options);
43740
43805
  resolve(true);
43741
43806
  }
43742
43807
  catch (error) {
@@ -43752,35 +43817,58 @@ class Device extends events.exports {
43752
43817
  }));
43753
43818
  }
43754
43819
  acquire(expectedProtocol, options) {
43755
- var _a, _b, _c, _d, _e, _f, _g;
43820
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
43756
43821
  return __awaiter(this, void 0, void 0, function* () {
43757
43822
  const env = DataManager.getSettings('env');
43758
43823
  const mainIdKey = DataManager.isBleConnect(env) ? 'id' : 'session';
43759
- const protocolHint = expectedProtocol ? undefined : this.originalDescriptor.protocolType;
43824
+ const previousProtocol = this.originalDescriptor.protocolType;
43825
+ const strictProtocol = (options === null || options === void 0 ? void 0 : options.forceProtocolDetection)
43826
+ ? undefined
43827
+ : expectedProtocol !== null && expectedProtocol !== void 0 ? expectedProtocol : this.originalDescriptor.protocolType;
43760
43828
  try {
43761
43829
  let acquireResult;
43762
43830
  if (DataManager.isBleConnect(env)) {
43763
- acquireResult = yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.originalDescriptor.id, undefined, true, expectedProtocol, protocolHint));
43831
+ acquireResult = yield ((_a = this.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.originalDescriptor.id, undefined, true, strictProtocol, undefined));
43764
43832
  this.mainId = (_b = acquireResult === null || acquireResult === void 0 ? void 0 : acquireResult.uuid) !== null && _b !== void 0 ? _b : '';
43765
43833
  Log$e.debug('Expected uuid:', this.mainId);
43766
43834
  }
43767
43835
  else {
43768
- acquireResult = yield ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.originalDescriptor.path, this.originalDescriptor.session, undefined, expectedProtocol, protocolHint));
43836
+ acquireResult = yield ((_c = this.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.originalDescriptor.path, this.originalDescriptor.session, undefined, strictProtocol, undefined));
43769
43837
  this.mainId = acquireResult;
43770
43838
  Log$e.debug('Expected session id:', this.mainId);
43771
43839
  }
43772
- this.deviceAcquired = true;
43773
- this.updateDescriptor({ [mainIdKey]: this.mainId });
43774
43840
  const detectedProtocol = (_d = acquireResult === null || acquireResult === void 0 ? void 0 : acquireResult.protocolType) !== null && _d !== void 0 ? _d : (_f = (_e = TransportManager.transport) === null || _e === void 0 ? void 0 : _e.getProtocolType) === null || _f === void 0 ? void 0 : _f.call(_e, DataManager.isBleConnect(env) ? this.originalDescriptor.id : this.originalDescriptor.path);
43841
+ if ((options === null || options === void 0 ? void 0 : options.forceProtocolDetection) && !detectedProtocol) {
43842
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Active protocol detection returned no protocol for ${this.originalDescriptor.path || this.originalDescriptor.id}`);
43843
+ }
43775
43844
  if (detectedProtocol) {
43776
43845
  this.originalDescriptor.protocolType = detectedProtocol;
43777
43846
  }
43847
+ this.deviceAcquired = true;
43848
+ this.updateDescriptor({ [mainIdKey]: this.mainId });
43778
43849
  if (this.commands) {
43779
43850
  yield this.commands.dispose(false);
43780
43851
  }
43781
43852
  this.commands = new DeviceCommands(this, (_g = this.mainId) !== null && _g !== void 0 ? _g : '');
43782
43853
  }
43783
43854
  catch (error) {
43855
+ if (options === null || options === void 0 ? void 0 : options.forceProtocolDetection) {
43856
+ this.originalDescriptor.protocolType = previousProtocol;
43857
+ const failedSession = this.mainId;
43858
+ this.deviceAcquired = false;
43859
+ if (failedSession) {
43860
+ try {
43861
+ yield ((_j = (_h = this.deviceConnector) === null || _h === void 0 ? void 0 : _h.release) === null || _j === void 0 ? void 0 : _j.call(_h, failedSession, false));
43862
+ }
43863
+ catch (releaseError) {
43864
+ Log$e.debug('Failed to release an unsuccessful protocol probe', releaseError);
43865
+ }
43866
+ }
43867
+ if (!DataManager.isBleConnect(env)) {
43868
+ this.mainId = null;
43869
+ this.updateDescriptor({ session: null });
43870
+ }
43871
+ }
43784
43872
  if (options === null || options === void 0 ? void 0 : options.throwOnRunPromiseError) {
43785
43873
  throw error;
43786
43874
  }
@@ -44502,11 +44590,16 @@ class Device extends events.exports {
44502
44590
  this.runPromise = null;
44503
44591
  }
44504
44592
  };
44505
- if (!this.isUsedHere() || this.commands.disposed) {
44506
- const env = DataManager.getSettings('env');
44593
+ const env = DataManager.getSettings('env');
44594
+ if (options.forceProtocolDetection && env !== 'react-native' && this.isUsedHere()) {
44595
+ yield this.release();
44596
+ }
44597
+ if (options.forceProtocolDetection || !this.isUsedHere() || this.commands.disposed) {
44507
44598
  if (env !== 'react-native') {
44508
44599
  try {
44509
- yield this.acquire(options.connectProtocol);
44600
+ yield this.acquire(options.connectProtocol, {
44601
+ forceProtocolDetection: options.forceProtocolDetection,
44602
+ });
44510
44603
  }
44511
44604
  catch (error) {
44512
44605
  clearRunPromise();
@@ -45330,7 +45423,8 @@ class SearchDevices extends BaseMethod {
45330
45423
  for (const descriptor of devicesDescriptor) {
45331
45424
  try {
45332
45425
  const result = yield DevicePool.getDevices([descriptor], descriptor.path, {
45333
- connectProtocol: this.payload.connectProtocol,
45426
+ connectProtocol: undefined,
45427
+ forceProtocolDetection: true,
45334
45428
  refreshRuntimeState: true,
45335
45429
  });
45336
45430
  deviceList.push(...result.deviceList);
@@ -45347,6 +45441,21 @@ class SearchDevices extends BaseMethod {
45347
45441
  }
45348
45442
  }
45349
45443
 
45444
+ class DetectDeviceConnectProtocol extends BaseMethod {
45445
+ init() {
45446
+ this.payload.forceProtocolDetection = true;
45447
+ this.useDevicePassphraseState = false;
45448
+ this.skipForceUpdateCheck = true;
45449
+ this.unlockPolicy = 'none';
45450
+ }
45451
+ getSupportedProtocols() {
45452
+ return ['V1', 'V2'];
45453
+ }
45454
+ run() {
45455
+ return Promise.resolve(this.device.getProtocol());
45456
+ }
45457
+ }
45458
+
45350
45459
  class GetFeatures extends BaseMethod {
45351
45460
  init() {
45352
45461
  this.unlockPolicy = 'none';
@@ -46325,24 +46434,22 @@ class CheckAllFirmwareRelease extends BaseMethod {
46325
46434
  if (resources === null || resources === void 0 ? void 0 : resources.length) {
46326
46435
  const loaderMode = state.status.mode === 'bootloader' || state.status.mode === 'romloader';
46327
46436
  if (loaderMode) {
46328
- resourceStatus = buildProtocolV2ResourceUpdatePlan({
46329
- resources,
46330
- mode: 'bootloader-recovery',
46331
- }).status;
46332
- }
46333
- else if (state.status.mode === 'normal') {
46334
46437
  try {
46335
- const inventory = yield requestProtocolV2ResourceInventory({
46438
+ const inventory = yield readProtocolV2ResourceInventory({
46336
46439
  commands: this.device.getCommands(),
46440
+ resources,
46337
46441
  });
46338
46442
  resourceStatus = buildProtocolV2ResourceUpdatePlan({
46339
46443
  resources,
46340
46444
  inventory,
46341
- mode: 'application',
46445
+ mode: 'bootloader-recovery',
46342
46446
  }).status;
46343
46447
  }
46344
46448
  catch (_b) {
46345
- resourceStatus = 'unknown';
46449
+ resourceStatus = buildProtocolV2ResourceUpdatePlan({
46450
+ resources,
46451
+ mode: 'bootloader-recovery',
46452
+ }).status;
46346
46453
  }
46347
46454
  }
46348
46455
  }
@@ -47347,7 +47454,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
47347
47454
  try {
47348
47455
  if (isBleReconnect) {
47349
47456
  try {
47350
- yield ((_d = device.deviceConnector) === null || _d === void 0 ? void 0 : _d.acquire(device.originalDescriptor.id, null, true));
47457
+ yield ((_d = device.deviceConnector) === null || _d === void 0 ? void 0 : _d.acquire(device.originalDescriptor.id, null, true, device.originalDescriptor.protocolType));
47351
47458
  const typedCall = device.getCommands().typedCall.bind(device.getCommands());
47352
47459
  yield Promise.race([
47353
47460
  typedCall('Initialize', 'Features', {}),
@@ -47365,7 +47472,7 @@ const newTouchUpdateProcess = (updateType, postMessage, device, { payload }, reb
47365
47472
  else {
47366
47473
  const deviceDiff = yield ((_e = device.deviceConnector) === null || _e === void 0 ? void 0 : _e.enumerate());
47367
47474
  const devicesDescriptor = (_f = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _f !== void 0 ? _f : [];
47368
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, device.originalDescriptor.id);
47475
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, device.originalDescriptor.id, { connectProtocol: device.originalDescriptor.protocolType });
47369
47476
  if (deviceList.length === 1) {
47370
47477
  device.updateFromCache(deviceList[0]);
47371
47478
  yield device.acquire();
@@ -47428,14 +47535,16 @@ const emmcFileWriteWithRetry = (device, filePath, chunkLength, offset, chunk, ov
47428
47535
  const env = DataManager.getSettings('env');
47429
47536
  if (DataManager.isBleConnect(env)) {
47430
47537
  yield wait(3000);
47431
- yield ((_h = device.deviceConnector) === null || _h === void 0 ? void 0 : _h.acquire(device.originalDescriptor.id, null, true));
47538
+ yield ((_h = device.deviceConnector) === null || _h === void 0 ? void 0 : _h.acquire(device.originalDescriptor.id, null, true, device.originalDescriptor.protocolType));
47432
47539
  yield device.initialize();
47433
47540
  }
47434
47541
  else if (((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.indexOf(SESSION_ERROR$2)) > -1 ||
47435
47542
  ((_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) {
47436
47543
  const deviceDiff = yield ((_m = device.deviceConnector) === null || _m === void 0 ? void 0 : _m.enumerate());
47437
47544
  const devicesDescriptor = (_o = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _o !== void 0 ? _o : [];
47438
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
47545
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined, {
47546
+ connectProtocol: device.originalDescriptor.protocolType,
47547
+ });
47439
47548
  if (deviceList.length === 1 && ((_p = deviceList[0]) === null || _p === void 0 ? void 0 : _p.isBootloader())) {
47440
47549
  device.updateFromCache(deviceList[0]);
47441
47550
  yield device.acquire();
@@ -47651,7 +47760,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
47651
47760
  const isTouchOrProDevice = ((_a = this === null || this === void 0 ? void 0 : this.device) === null || _a === void 0 ? void 0 : _a.getCurrentDeviceType()) === hdShared.EDeviceType.Touch ||
47652
47761
  ((_b = this === null || this === void 0 ? void 0 : this.device) === null || _b === void 0 ? void 0 : _b.getCurrentDeviceType()) === hdShared.EDeviceType.Pro;
47653
47762
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
47654
- var _c, _d, _e;
47763
+ var _c, _d, _e, _f;
47655
47764
  checkCount += 1;
47656
47765
  Log$9.log('FirmwareUpdateBaseMethod [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
47657
47766
  if (isTouchOrProDevice && isFirstCheck) {
@@ -47686,11 +47795,11 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
47686
47795
  }
47687
47796
  if (isBleReconnect) {
47688
47797
  try {
47689
- yield ((_d = this.device.deviceConnector) === null || _d === void 0 ? void 0 : _d.acquire(this.device.originalDescriptor.id, null, true));
47798
+ yield ((_d = this.device.deviceConnector) === null || _d === void 0 ? void 0 : _d.acquire(this.device.originalDescriptor.id, null, true, (_e = this.payload.connectProtocol) !== null && _e !== void 0 ? _e : this.device.originalDescriptor.protocolType));
47690
47799
  yield this.device.initialize();
47691
47800
  if (this.device.isBootloader()) {
47692
47801
  clearInterval(intervalTimer);
47693
- (_e = this.checkPromise) === null || _e === void 0 ? void 0 : _e.resolve(true);
47802
+ (_f = this.checkPromise) === null || _f === void 0 ? void 0 : _f.resolve(true);
47694
47803
  }
47695
47804
  }
47696
47805
  catch (e) {
@@ -47709,19 +47818,21 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
47709
47818
  }, 30000);
47710
47819
  }
47711
47820
  _checkDeviceInBootloaderMode(connectId, intervalTimer, timeoutTimer) {
47712
- var _a, _b, _c, _d;
47821
+ var _a, _b, _c, _d, _e;
47713
47822
  return __awaiter(this, void 0, void 0, function* () {
47714
47823
  const deviceDiff = yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.enumerate());
47715
47824
  const devicesDescriptor = (_b = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _b !== void 0 ? _b : [];
47716
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, connectId);
47717
- if (deviceList.length === 1 && ((_c = deviceList[0]) === null || _c === void 0 ? void 0 : _c.isBootloader())) {
47825
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, connectId, {
47826
+ connectProtocol: (_c = this.payload.connectProtocol) !== null && _c !== void 0 ? _c : this.device.originalDescriptor.protocolType,
47827
+ });
47828
+ if (deviceList.length === 1 && ((_d = deviceList[0]) === null || _d === void 0 ? void 0 : _d.isBootloader())) {
47718
47829
  this.device.updateFromCache(deviceList[0]);
47719
47830
  this.device.commands.disposed = false;
47720
47831
  if (intervalTimer)
47721
47832
  clearInterval(intervalTimer);
47722
47833
  if (timeoutTimer)
47723
47834
  clearTimeout(timeoutTimer);
47724
- (_d = this.checkPromise) === null || _d === void 0 ? void 0 : _d.resolve(true);
47835
+ (_e = this.checkPromise) === null || _e === void 0 ? void 0 : _e.resolve(true);
47725
47836
  return true;
47726
47837
  }
47727
47838
  return false;
@@ -47832,10 +47943,10 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
47832
47943
  });
47833
47944
  }
47834
47945
  emmcFileWriteWithRetry(filePath, chunkLength, offset, chunk, overwrite, progress) {
47835
- var _a, _b, _c, _d, _e, _f, _g, _h;
47946
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
47836
47947
  return __awaiter(this, void 0, void 0, function* () {
47837
47948
  const writeFunc = () => __awaiter(this, void 0, void 0, function* () {
47838
- var _j;
47949
+ var _l;
47839
47950
  const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
47840
47951
  const writeRes = yield typedCall('EmmcFileWrite', 'EmmcFile', {
47841
47952
  file: {
@@ -47850,7 +47961,7 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
47850
47961
  });
47851
47962
  if (writeRes.type !== 'EmmcFile') {
47852
47963
  if (writeRes.type === 'CallMethodError') {
47853
- if (((_j = writeRes.message.error) !== null && _j !== void 0 ? _j : '').indexOf(SESSION_ERROR$1) > -1) {
47964
+ if (((_l = writeRes.message.error) !== null && _l !== void 0 ? _l : '').indexOf(SESSION_ERROR$1) > -1) {
47854
47965
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, SESSION_ERROR$1);
47855
47966
  }
47856
47967
  }
@@ -47873,18 +47984,20 @@ class FirmwareUpdateBaseMethod extends BaseMethod {
47873
47984
  const env = DataManager.getSettings('env');
47874
47985
  if (DataManager.isBleConnect(env)) {
47875
47986
  yield wait(3000);
47876
- yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true));
47987
+ yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true, (_b = this.payload.connectProtocol) !== null && _b !== void 0 ? _b : this.device.originalDescriptor.protocolType));
47877
47988
  yield this.device.initialize();
47878
47989
  }
47879
- else if (((_b = error === null || error === void 0 ? void 0 : error.message) === null || _b === void 0 ? void 0 : _b.indexOf(SESSION_ERROR$1)) > -1 ||
47880
- ((_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) {
47881
- const deviceDiff = yield ((_e = this.device.deviceConnector) === null || _e === void 0 ? void 0 : _e.enumerate());
47882
- const devicesDescriptor = (_f = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _f !== void 0 ? _f : [];
47883
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined);
47884
- if (deviceList.length === 1 && ((_g = deviceList[0]) === null || _g === void 0 ? void 0 : _g.isBootloader())) {
47990
+ else if (((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.indexOf(SESSION_ERROR$1)) > -1 ||
47991
+ ((_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.indexOf(SESSION_ERROR$1)) > -1) {
47992
+ const deviceDiff = yield ((_f = this.device.deviceConnector) === null || _f === void 0 ? void 0 : _f.enumerate());
47993
+ const devicesDescriptor = (_g = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _g !== void 0 ? _g : [];
47994
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined, {
47995
+ connectProtocol: (_h = this.payload.connectProtocol) !== null && _h !== void 0 ? _h : this.device.originalDescriptor.protocolType,
47996
+ });
47997
+ if (deviceList.length === 1 && ((_j = deviceList[0]) === null || _j === void 0 ? void 0 : _j.isBootloader())) {
47885
47998
  this.device.updateFromCache(deviceList[0]);
47886
47999
  yield this.device.acquire();
47887
- this.device.getCommands().mainId = (_h = this.device.mainId) !== null && _h !== void 0 ? _h : '';
48000
+ this.device.getCommands().mainId = (_k = this.device.mainId) !== null && _k !== void 0 ? _k : '';
47888
48001
  }
47889
48002
  }
47890
48003
  yield wait(2000);
@@ -48103,14 +48216,14 @@ class FirmwareUpdate extends BaseMethod {
48103
48216
  const isBleReconnect = connectId && DataManager.isBleConnect(env);
48104
48217
  Log$8.log('FirmwareUpdate [checkDeviceToBootloader] isBleReconnect: ', isBleReconnect);
48105
48218
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
48106
- var _a, _b, _c, _d, _e, _f;
48219
+ var _a, _b, _c, _d, _e, _f, _g, _h;
48107
48220
  if (isBleReconnect) {
48108
48221
  try {
48109
- yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true));
48222
+ yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true, (_b = this.payload.connectProtocol) !== null && _b !== void 0 ? _b : this.device.originalDescriptor.protocolType));
48110
48223
  yield this.device.initialize();
48111
48224
  if (this.device.isBootloader()) {
48112
48225
  clearInterval(intervalTimer);
48113
- (_b = this.checkPromise) === null || _b === void 0 ? void 0 : _b.resolve(true);
48226
+ (_c = this.checkPromise) === null || _c === void 0 ? void 0 : _c.resolve(true);
48114
48227
  }
48115
48228
  }
48116
48229
  catch (e) {
@@ -48118,14 +48231,16 @@ class FirmwareUpdate extends BaseMethod {
48118
48231
  }
48119
48232
  }
48120
48233
  else {
48121
- const deviceDiff = yield ((_c = this.device.deviceConnector) === null || _c === void 0 ? void 0 : _c.enumerate());
48122
- const devicesDescriptor = (_d = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _d !== void 0 ? _d : [];
48123
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, connectId);
48124
- if (deviceList.length === 1 && ((_e = deviceList[0]) === null || _e === void 0 ? void 0 : _e.isBootloader())) {
48234
+ const deviceDiff = yield ((_d = this.device.deviceConnector) === null || _d === void 0 ? void 0 : _d.enumerate());
48235
+ const devicesDescriptor = (_e = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _e !== void 0 ? _e : [];
48236
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, connectId, {
48237
+ connectProtocol: (_f = this.payload.connectProtocol) !== null && _f !== void 0 ? _f : this.device.originalDescriptor.protocolType,
48238
+ });
48239
+ if (deviceList.length === 1 && ((_g = deviceList[0]) === null || _g === void 0 ? void 0 : _g.isBootloader())) {
48125
48240
  this.device.updateFromCache(deviceList[0]);
48126
48241
  this.device.commands.disposed = false;
48127
48242
  clearInterval(intervalTimer);
48128
- (_f = this.checkPromise) === null || _f === void 0 ? void 0 : _f.resolve(true);
48243
+ (_h = this.checkPromise) === null || _h === void 0 ? void 0 : _h.resolve(true);
48129
48244
  }
48130
48245
  }
48131
48246
  }), isBleReconnect ? 3000 : 2000);
@@ -48331,7 +48446,7 @@ class FirmwareUpdateV2 extends BaseMethod {
48331
48446
  const deviceType = (_a = this.device) === null || _a === void 0 ? void 0 : _a.getCurrentDeviceType();
48332
48447
  const isTouchOrProDevice = deviceType === hdShared.EDeviceType.Touch || deviceType === hdShared.EDeviceType.Pro;
48333
48448
  const intervalTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () {
48334
- var _b, _c, _d;
48449
+ var _b, _c, _d, _e;
48335
48450
  checkCount += 1;
48336
48451
  Log$7.log('FirmwareUpdateV2 [checkDeviceToBootloader] isFirstCheck: ', isFirstCheck);
48337
48452
  if (isTouchOrProDevice && isFirstCheck) {
@@ -48359,11 +48474,11 @@ class FirmwareUpdateV2 extends BaseMethod {
48359
48474
  }
48360
48475
  if (isBleReconnect) {
48361
48476
  try {
48362
- yield ((_c = this.device.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.device.originalDescriptor.id, null, true));
48477
+ yield ((_c = this.device.deviceConnector) === null || _c === void 0 ? void 0 : _c.acquire(this.device.originalDescriptor.id, null, true, (_d = this.payload.connectProtocol) !== null && _d !== void 0 ? _d : this.device.originalDescriptor.protocolType));
48363
48478
  yield this.device.initialize();
48364
48479
  if (this.device.isBootloader()) {
48365
48480
  clearInterval(intervalTimer);
48366
- (_d = this.checkPromise) === null || _d === void 0 ? void 0 : _d.resolve(true);
48481
+ (_e = this.checkPromise) === null || _e === void 0 ? void 0 : _e.resolve(true);
48367
48482
  }
48368
48483
  }
48369
48484
  catch (e) {
@@ -48382,19 +48497,21 @@ class FirmwareUpdateV2 extends BaseMethod {
48382
48497
  }, 30000);
48383
48498
  }
48384
48499
  _checkDeviceInBootloaderMode(connectId, intervalTimer, timeoutTimer) {
48385
- var _a, _b, _c, _d;
48500
+ var _a, _b, _c, _d, _e;
48386
48501
  return __awaiter(this, void 0, void 0, function* () {
48387
48502
  const deviceDiff = yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.enumerate());
48388
48503
  const devicesDescriptor = (_b = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _b !== void 0 ? _b : [];
48389
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, connectId);
48390
- if (deviceList.length === 1 && ((_c = deviceList[0]) === null || _c === void 0 ? void 0 : _c.isBootloader())) {
48504
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, connectId, {
48505
+ connectProtocol: (_c = this.payload.connectProtocol) !== null && _c !== void 0 ? _c : this.device.originalDescriptor.protocolType,
48506
+ });
48507
+ if (deviceList.length === 1 && ((_d = deviceList[0]) === null || _d === void 0 ? void 0 : _d.isBootloader())) {
48391
48508
  this.device.updateFromCache(deviceList[0]);
48392
48509
  this.device.commands.disposed = false;
48393
48510
  if (intervalTimer)
48394
48511
  clearInterval(intervalTimer);
48395
48512
  if (timeoutTimer)
48396
48513
  clearTimeout(timeoutTimer);
48397
- (_d = this.checkPromise) === null || _d === void 0 ? void 0 : _d.resolve(true);
48514
+ (_e = this.checkPromise) === null || _e === void 0 ? void 0 : _e.resolve(true);
48398
48515
  return true;
48399
48516
  }
48400
48517
  return false;
@@ -48922,7 +49039,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
48922
49039
  this.device.listenerCount(DEVICE.SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE) > 0);
48923
49040
  }
48924
49041
  waitForDeviceReconnect(timeout) {
48925
- var _a, _b, _c, _d;
49042
+ var _a, _b, _c, _d, _e, _f;
48926
49043
  return __awaiter(this, void 0, void 0, function* () {
48927
49044
  const startTime = Date.now();
48928
49045
  const isBleReconnect = this.isBleReconnect();
@@ -48931,7 +49048,7 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
48931
49048
  try {
48932
49049
  if (isBleReconnect) {
48933
49050
  try {
48934
- yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true));
49051
+ yield ((_a = this.device.deviceConnector) === null || _a === void 0 ? void 0 : _a.acquire(this.device.originalDescriptor.id, null, true, (_b = this.payload.connectProtocol) !== null && _b !== void 0 ? _b : this.device.originalDescriptor.protocolType));
48935
49052
  const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
48936
49053
  yield Promise.race([
48937
49054
  typedCall('Initialize', 'Features', {}),
@@ -48948,8 +49065,8 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
48948
49065
  }
48949
49066
  }
48950
49067
  else {
48951
- const deviceDiff = yield ((_b = this.device.deviceConnector) === null || _b === void 0 ? void 0 : _b.enumerate());
48952
- const devicesDescriptor = (_c = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _c !== void 0 ? _c : [];
49068
+ const deviceDiff = yield ((_c = this.device.deviceConnector) === null || _c === void 0 ? void 0 : _c.enumerate());
49069
+ const devicesDescriptor = (_d = deviceDiff === null || deviceDiff === void 0 ? void 0 : deviceDiff.descriptors) !== null && _d !== void 0 ? _d : [];
48953
49070
  const canPromptSwitchFirmwareReconnect = this.canPromptWebUsbSwitchFirmwareReconnect();
48954
49071
  if (canPromptSwitchFirmwareReconnect) {
48955
49072
  webUsbCheckCount += 1;
@@ -48967,12 +49084,14 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
48967
49084
  else {
48968
49085
  webUsbCheckCount = 0;
48969
49086
  }
48970
- const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, this.connectId);
49087
+ const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, this.connectId, {
49088
+ connectProtocol: (_e = this.payload.connectProtocol) !== null && _e !== void 0 ? _e : this.device.originalDescriptor.protocolType,
49089
+ });
48971
49090
  if (deviceList.length === 1) {
48972
49091
  this.device.updateFromCache(deviceList[0]);
48973
49092
  yield this.device.acquire();
48974
49093
  this.device.commands.disposed = false;
48975
- this.device.getCommands().mainId = (_d = this.device.mainId) !== null && _d !== void 0 ? _d : '';
49094
+ this.device.getCommands().mainId = (_f = this.device.mainId) !== null && _f !== void 0 ? _f : '';
48976
49095
  return;
48977
49096
  }
48978
49097
  }
@@ -49386,13 +49505,14 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
49386
49505
  });
49387
49506
  }
49388
49507
  runProtocolV2() {
49389
- var _a, _b, _c, _d, _e;
49508
+ var _a, _b, _c, _d, _e, _f;
49390
49509
  return __awaiter(this, void 0, void 0, function* () {
49391
49510
  yield this.captureProtocolV2PhysicalIdentity();
49392
49511
  const deviceFeatures = yield this.getProtocolV2DeviceFeatures();
49393
49512
  const deviceFirmwareType = getFirmwareType(deviceFeatures);
49394
49513
  const firmwareType = (_a = this.params.firmwareType) !== null && _a !== void 0 ? _a : deviceFirmwareType;
49395
- const resourceRecoveryMode = Boolean(this.isProtocolV2BootloaderMode() || this.isProtocolV2RomloaderMode());
49514
+ const needsRemoteResources = !((_b = this.params.resourceBundleFiles) === null || _b === void 0 ? void 0 : _b.length) &&
49515
+ !!((_c = this.params.targetsToUpdate) === null || _c === void 0 ? void 0 : _c.includes('resource'));
49396
49516
  let fwBinaryMap = [];
49397
49517
  let bootloaderBinary = null;
49398
49518
  let bootResourcesInstallItem;
@@ -49400,11 +49520,10 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
49400
49520
  let resourceBundles;
49401
49521
  try {
49402
49522
  this.postTipMessage(exports.FirmwareUpdateTipMessage.StartDownloadFirmware);
49523
+ resourceBundles = this.prepareExplicitProtocolV2ResourceBundles();
49403
49524
  fwBinaryMap = this.collectExplicitTargetBinaries();
49404
49525
  bootloaderBinary = this.prepareBootloaderBinary();
49405
49526
  const needsRemoteFirmware = !this.hasExplicitProtocolV2Payload(fwBinaryMap);
49406
- const needsRemoteResources = !((_b = this.params.resourceBundleFiles) === null || _b === void 0 ? void 0 : _b.length) &&
49407
- !!((_c = this.params.targetsToUpdate) === null || _c === void 0 ? void 0 : _c.includes('resource'));
49408
49527
  const needsRemoteBootResources = !this.params.bootResourcesBinary &&
49409
49528
  !!((_d = this.params.targetsToUpdate) === null || _d === void 0 ? void 0 : _d.includes('boot_resources'));
49410
49529
  if (needsRemoteFirmware || needsRemoteResources || needsRemoteBootResources) {
@@ -49423,8 +49542,9 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
49423
49542
  ...(installItems !== null && installItems !== void 0 ? installItems : this.buildProtocolV2InstallItems({ bootloaderBinary, fwBinaryMap })),
49424
49543
  ];
49425
49544
  }
49426
- resourceBundles = yield this.prepareProtocolV2ResourceBundles(resourceRecoveryMode);
49427
- this.postTipMessage(exports.FirmwareUpdateTipMessage.FinishDownloadFirmware);
49545
+ if (!needsRemoteResources) {
49546
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FinishDownloadFirmware);
49547
+ }
49428
49548
  }
49429
49549
  catch (err) {
49430
49550
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, (_e = err.message) !== null && _e !== void 0 ? _e : err);
@@ -49432,14 +49552,28 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
49432
49552
  if (!bootloaderBinary &&
49433
49553
  fwBinaryMap.length === 0 &&
49434
49554
  !(installItems === null || installItems === void 0 ? void 0 : installItems.length) &&
49435
- !(resourceBundles === null || resourceBundles === void 0 ? void 0 : resourceBundles.length)) {
49436
- if (resourceBundles !== undefined) {
49437
- this.postTipMessage(exports.FirmwareUpdateTipMessage.FirmwareUpdateCompleted);
49438
- return this.getProtocolV2VersionResult(deviceFeatures);
49439
- }
49555
+ !(resourceBundles === null || resourceBundles === void 0 ? void 0 : resourceBundles.length) &&
49556
+ !needsRemoteResources) {
49440
49557
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, 'No firmware to update');
49441
49558
  }
49442
- yield this.enterProtocolV2BootloaderMode();
49559
+ const enteredBootloader = yield this.enterProtocolV2BootloaderMode();
49560
+ if (needsRemoteResources) {
49561
+ try {
49562
+ resourceBundles = yield this.prepareProtocolV2ResourceBundles();
49563
+ this.postTipMessage(exports.FirmwareUpdateTipMessage.FinishDownloadFirmware);
49564
+ }
49565
+ catch (err) {
49566
+ if (enteredBootloader) {
49567
+ try {
49568
+ yield this.exitProtocolV2BootloaderToNormal();
49569
+ }
49570
+ catch (restoreError) {
49571
+ Log$5.warn('[FirmwareUpdateV4] failed to restore App mode after resource preparation error:', restoreError);
49572
+ }
49573
+ }
49574
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.FirmwareUpdateDownloadFailed, (_f = err.message) !== null && _f !== void 0 ? _f : err);
49575
+ }
49576
+ }
49443
49577
  yield this.executeProtocolV2Update(Object.assign(Object.assign({ fwBinaryMap,
49444
49578
  bootloaderBinary }, (installItems ? { installItems } : undefined)), ((resourceBundles === null || resourceBundles === void 0 ? void 0 : resourceBundles.length) ? { resourceBundles } : undefined)));
49445
49579
  yield this.exitProtocolV2BootloaderToNormal();
@@ -49660,40 +49794,45 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
49660
49794
  };
49661
49795
  });
49662
49796
  }
49663
- prepareProtocolV2ResourceBundles(recoveryMode) {
49664
- var _a, _b;
49797
+ prepareExplicitProtocolV2ResourceBundles() {
49798
+ var _a;
49799
+ if (!((_a = this.params.resourceBundleFiles) === null || _a === void 0 ? void 0 : _a.length))
49800
+ return undefined;
49801
+ return this.params.resourceBundleFiles.map((file, index) => {
49802
+ var _a;
49803
+ const devicePath = validateProtocolV2FilesystemPath(file.devicePath, `resourceBundleFiles[${index}].devicePath`);
49804
+ return {
49805
+ name: (_a = devicePath.split('/').pop()) !== null && _a !== void 0 ? _a : devicePath,
49806
+ binary: file.binary,
49807
+ devicePath,
49808
+ };
49809
+ });
49810
+ }
49811
+ prepareProtocolV2ResourceBundles() {
49812
+ var _a;
49665
49813
  return __awaiter(this, void 0, void 0, function* () {
49666
- if ((_a = this.params.resourceBundleFiles) === null || _a === void 0 ? void 0 : _a.length) {
49667
- return this.params.resourceBundleFiles.map((file, index) => {
49668
- var _a;
49669
- const devicePath = validateProtocolV2FilesystemPath(file.devicePath, `resourceBundleFiles[${index}].devicePath`);
49670
- return {
49671
- name: (_a = devicePath.split('/').pop()) !== null && _a !== void 0 ? _a : devicePath,
49672
- binary: file.binary,
49673
- devicePath,
49674
- };
49675
- });
49676
- }
49677
- if (!((_b = this.params.targetsToUpdate) === null || _b === void 0 ? void 0 : _b.includes('resource'))) {
49814
+ if (!((_a = this.params.targetsToUpdate) === null || _a === void 0 ? void 0 : _a.includes('resource'))) {
49678
49815
  return undefined;
49679
49816
  }
49680
49817
  const resources = DataManager.getProtocolV2Resources();
49681
49818
  if (!(resources === null || resources === void 0 ? void 0 : resources.length)) {
49682
49819
  throw new Error('Missing Pro2 stable resource configuration');
49683
49820
  }
49684
- const inventory = recoveryMode
49821
+ const inventory = this.params.forcedUpdateRes
49685
49822
  ? undefined
49686
- : yield requestProtocolV2ResourceInventory({
49823
+ : yield readProtocolV2ResourceInventory({
49687
49824
  commands: this.device.getCommands(),
49825
+ resources,
49826
+ chunkSize: this.getProtocolV2FirmwareChunkSize(),
49688
49827
  timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
49689
49828
  });
49690
49829
  const plan = buildProtocolV2ResourceUpdatePlan({
49691
49830
  resources,
49692
49831
  inventory,
49693
- mode: recoveryMode ? 'bootloader-recovery' : 'application',
49832
+ mode: 'bootloader-recovery',
49694
49833
  forced: this.params.forcedUpdateRes,
49695
49834
  });
49696
- Log$5.log(`[FirmwareUpdateV4] Pro2 resource plan mode=${recoveryMode ? 'bootloader-recovery' : 'application'} status=${plan.status} count=${plan.resources.length}`);
49835
+ Log$5.log(`[FirmwareUpdateV4] Pro2 resource plan mode=bootloader-recovery status=${plan.status} count=${plan.resources.length}`);
49697
49836
  const bundles = [];
49698
49837
  for (const resource of plan.resources) {
49699
49838
  bundles.push(yield this.downloadProtocolV2Resource(resource));
@@ -50074,7 +50213,7 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
50074
50213
  });
50075
50214
  }
50076
50215
  reconnectProtocolV2Device() {
50077
- var _a, _b, _c, _d;
50216
+ var _a, _b, _c, _d, _e, _f;
50078
50217
  return __awaiter(this, void 0, void 0, function* () {
50079
50218
  if (this.isBleReconnect()) {
50080
50219
  yield this.acquireProtocolV2BleDevice();
@@ -50093,14 +50232,23 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
50093
50232
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined, {
50094
50233
  connectProtocol: PROTOCOL_V2_CONNECT_PROTOCOL,
50095
50234
  });
50096
- if (deviceList.length !== 1) {
50235
+ const expectedSerialNumber = (_d = this.protocolV2ExpectedSerialNumber) === null || _d === void 0 ? void 0 : _d.trim();
50236
+ const identityMatch = expectedSerialNumber
50237
+ ? deviceList.find(candidate => { var _a; return ((_a = candidate.getCurrentSerialNo) === null || _a === void 0 ? void 0 : _a.call(candidate).trim()) === expectedSerialNumber; })
50238
+ : undefined;
50239
+ const singleCandidate = deviceList.length === 1 ? deviceList.at(0) : undefined;
50240
+ const singleCandidateSerialNumber = (_e = singleCandidate === null || singleCandidate === void 0 ? void 0 : singleCandidate.getCurrentSerialNo) === null || _e === void 0 ? void 0 : _e.call(singleCandidate).trim();
50241
+ const reconnectDevice = identityMatch !== null && identityMatch !== void 0 ? identityMatch : (singleCandidate && (!expectedSerialNumber || !singleCandidateSerialNumber)
50242
+ ? singleCandidate
50243
+ : undefined);
50244
+ if (!reconnectDevice) {
50097
50245
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound);
50098
50246
  }
50099
- Log$5.debug('Protocol V2 firmware reconnect using single enumerated device:', deviceList[0].getConnectId());
50100
- this.device.updateFromCache(deviceList[0]);
50247
+ Log$5.debug('Protocol V2 firmware reconnect using matched device:', reconnectDevice.getConnectId());
50248
+ this.device.updateFromCache(reconnectDevice);
50101
50249
  yield this.ensureProtocolV2DeviceAcquired();
50102
50250
  this.device.commands.disposed = false;
50103
- this.device.getCommands().mainId = (_d = this.device.mainId) !== null && _d !== void 0 ? _d : '';
50251
+ this.device.getCommands().mainId = (_f = this.device.mainId) !== null && _f !== void 0 ? _f : '';
50104
50252
  });
50105
50253
  }
50106
50254
  ensureProtocolV2DeviceAcquired() {
@@ -60523,6 +60671,7 @@ var ApiMethods = /*#__PURE__*/Object.freeze({
60523
60671
  testProtocolV2Ping: Ping,
60524
60672
  preInitialize: PreInitialize,
60525
60673
  searchDevices: SearchDevices,
60674
+ detectDeviceConnectProtocol: DetectDeviceConnectProtocol,
60526
60675
  getFeatures: GetFeatures,
60527
60676
  getDeviceState: GetDeviceState,
60528
60677
  getOnekeyFeatures: GetOnekeyFeatures,
@@ -61029,6 +61178,7 @@ const parseInitOptions = (method) => ({
61029
61178
  deviceId: method === null || method === void 0 ? void 0 : method.payload.deviceId,
61030
61179
  deriveCardano: method && hasDeriveCardano(method),
61031
61180
  connectProtocol: method === null || method === void 0 ? void 0 : method.payload.connectProtocol,
61181
+ forceProtocolDetection: method === null || method === void 0 ? void 0 : method.payload.forceProtocolDetection,
61032
61182
  protocolV2DeviceInfoTimeoutMs: method === null || method === void 0 ? void 0 : method.payload.protocolV2DeviceInfoTimeoutMs,
61033
61183
  });
61034
61184
  let _core;
@@ -61583,9 +61733,17 @@ function connectDeviceForBle(method, device, retryCount = 0) {
61583
61733
  var _a;
61584
61734
  return __awaiter(this, void 0, void 0, function* () {
61585
61735
  try {
61586
- const shouldAcquire = !device.hasDeviceAcquire() || !device.commands || device.commands.disposed;
61736
+ if (method.payload.forceProtocolDetection && device.hasDeviceAcquire()) {
61737
+ yield device.release();
61738
+ }
61739
+ const shouldAcquire = method.payload.forceProtocolDetection ||
61740
+ !device.hasDeviceAcquire() ||
61741
+ !device.commands ||
61742
+ device.commands.disposed;
61587
61743
  if (shouldAcquire) {
61588
- yield device.acquire(method.payload.connectProtocol);
61744
+ yield device.acquire(method.payload.connectProtocol, {
61745
+ forceProtocolDetection: method.payload.forceProtocolDetection,
61746
+ });
61589
61747
  }
61590
61748
  if ((_a = method.payload) === null || _a === void 0 ? void 0 : _a.onlyConnectBleDevice) {
61591
61749
  if (shouldAcquire) {