@onekeyfe/hd-transport 1.2.0-alpha.11 → 1.2.0-alpha.111

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 (64) hide show
  1. package/__tests__/messages.test.js +165 -13
  2. package/__tests__/protocol-v2-ble-frame-writer.test.js +119 -0
  3. package/__tests__/protocol-v2-link-manager.test.js +120 -9
  4. package/__tests__/protocol-v2-usb-transport-base.test.js +36 -2
  5. package/__tests__/protocol-v2.test.js +553 -63
  6. package/__tests__/transport-log.test.js +79 -0
  7. package/dist/constants.d.ts +3 -1
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/index.d.ts +687 -255
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +661 -296
  12. package/dist/protocols/index.d.ts +25 -6
  13. package/dist/protocols/index.d.ts.map +1 -1
  14. package/dist/protocols/v2/ble-frame-writer.d.ts +15 -0
  15. package/dist/protocols/v2/ble-frame-writer.d.ts.map +1 -0
  16. package/dist/protocols/v2/decode.d.ts +12 -2
  17. package/dist/protocols/v2/decode.d.ts.map +1 -1
  18. package/dist/protocols/v2/encode.d.ts +2 -3
  19. package/dist/protocols/v2/encode.d.ts.map +1 -1
  20. package/dist/protocols/v2/errors.d.ts +8 -0
  21. package/dist/protocols/v2/errors.d.ts.map +1 -0
  22. package/dist/protocols/v2/frame-assembler.d.ts.map +1 -1
  23. package/dist/protocols/v2/index.d.ts +2 -1
  24. package/dist/protocols/v2/index.d.ts.map +1 -1
  25. package/dist/protocols/v2/link-manager.d.ts +4 -0
  26. package/dist/protocols/v2/link-manager.d.ts.map +1 -1
  27. package/dist/protocols/v2/session.d.ts +10 -4
  28. package/dist/protocols/v2/session.d.ts.map +1 -1
  29. package/dist/protocols/v2/usb-transport-base.d.ts +1 -0
  30. package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -1
  31. package/dist/serialization/protobuf/decode.d.ts.map +1 -1
  32. package/dist/serialization/protobuf/encode.d.ts.map +1 -1
  33. package/dist/types/messages.d.ts +336 -155
  34. package/dist/types/messages.d.ts.map +1 -1
  35. package/dist/types/transport.d.ts +20 -3
  36. package/dist/types/transport.d.ts.map +1 -1
  37. package/dist/utils/transportLog.d.ts +9 -0
  38. package/dist/utils/transportLog.d.ts.map +1 -0
  39. package/messages-protocol-v2.json +1030 -567
  40. package/package.json +3 -3
  41. package/scripts/protobuf-build.sh +85 -217
  42. package/scripts/protobuf-patches/index.js +1 -0
  43. package/scripts/protobuf-types.js +19 -1
  44. package/src/constants.ts +30 -16
  45. package/src/index.ts +5 -1
  46. package/src/protocols/index.ts +128 -40
  47. package/src/protocols/v2/ble-frame-writer.ts +77 -0
  48. package/src/protocols/v2/crc8.ts +1 -1
  49. package/src/protocols/v2/decode.ts +50 -35
  50. package/src/protocols/v2/encode.ts +2 -28
  51. package/src/protocols/v2/errors.ts +25 -0
  52. package/src/protocols/v2/frame-assembler.ts +6 -4
  53. package/src/protocols/v2/index.ts +2 -1
  54. package/src/protocols/v2/link-manager.ts +54 -5
  55. package/src/protocols/v2/session.ts +151 -200
  56. package/src/protocols/v2/usb-transport-base.ts +29 -10
  57. package/src/serialization/protobuf/decode.ts +4 -1
  58. package/src/serialization/protobuf/encode.ts +5 -1
  59. package/src/types/messages.ts +409 -197
  60. package/src/types/transport.ts +28 -3
  61. package/src/utils/transportLog.ts +102 -0
  62. package/dist/protocols/v2/debug.d.ts +0 -13
  63. package/dist/protocols/v2/debug.d.ts.map +0 -1
  64. package/src/protocols/v2/debug.ts +0 -26
package/dist/index.js CHANGED
@@ -140,7 +140,7 @@ function messageToJSON(Message, fields) {
140
140
  res[key] = field.resolvedType.valuesById[value];
141
141
  }
142
142
  else if (field.resolvedType.fields) {
143
- res[key] = messageToJSON(value, field.resolvedType.fields);
143
+ res[key] = value == null ? null : messageToJSON(value, field.resolvedType.fields);
144
144
  }
145
145
  else {
146
146
  throw new Error(`case not handled: ${key}`);
@@ -200,7 +200,10 @@ function patch(Message, payload) {
200
200
  }
201
201
  if (field.repeated) {
202
202
  const RefMessage = Message.lookupTypeOrEnum(field.type);
203
- patched[key] = value.map((v) => patch(RefMessage, v));
203
+ patched[key] =
204
+ RefMessage instanceof protobuf.Enum
205
+ ? value.map((v) => transform(field.type, v))
206
+ : value.map((v) => patch(RefMessage, v));
204
207
  }
205
208
  else if (typeof value === 'object' && value !== null) {
206
209
  const RefMessage = Message.lookupType(field.type);
@@ -267,9 +270,10 @@ const PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = 63;
267
270
  const PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1;
268
271
  const PROTOCOL_V1_MESSAGE_HEADER_SIZE = 2 + 4;
269
272
  const PROTOCOL_V1_ENVELOPE_HEADER_SIZE = 1 + 1 + PROTOCOL_V1_MESSAGE_HEADER_SIZE;
270
- const PROTOCOL_V2_FRAME_MAX_BYTES = 4608;
273
+ const PROTOCOL_V2_FRAME_MAX_BYTES = 4200;
271
274
  const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4000;
272
275
  const PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = 1800;
276
+ const PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = 1960;
273
277
  const PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = 900;
274
278
  const PROTOCOL_V2_BLE_FRAME_MAX_BYTES = 2048;
275
279
  const PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
@@ -277,6 +281,7 @@ const PROTOCOL_V2_CHANNEL_USB = 0;
277
281
  const PROTOCOL_V2_CHANNEL_BLE_UART = 1;
278
282
  const PROTOCOL_V2_CHANNEL_SOCKET = 2;
279
283
  const PROTOCOL_V2_PACKET_SRC_COMMAND = 0;
284
+ const PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = 5 * 60 * 1000;
280
285
 
281
286
  function encodeEnvelope(data, options) {
282
287
  const { addTrezorHeaders, chunked, messageTypeId } = options;
@@ -411,16 +416,11 @@ function crc8(data, len) {
411
416
  return crc;
412
417
  }
413
418
 
414
- function logProtocolV2Debug(options, stage, details) {
415
- var _a, _b, _c;
416
- (_b = (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `[${(_c = options.logPrefix) !== null && _c !== void 0 ? _c : 'ProtocolV2'}] ${stage}`, Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (options.context ? { context: options.context } : {})), (options.messageName ? { messageName: options.messageName } : {})), (options.messageTypeId !== undefined ? { messageTypeId: options.messageTypeId } : {})), (options.pbPayloadLength !== undefined ? { pbPayloadLength: options.pbPayloadLength } : {})), details));
417
- }
418
-
419
419
  const PROTO_SEQ_DEFAULT = 1;
420
420
  function nextProtoSeq(current) {
421
421
  return current >= 255 ? 1 : current + 1;
422
422
  }
423
- function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
423
+ function encodeFrame(payload, packetSrc, router, seq) {
424
424
  const resolvedPacketSrc = packetSrc !== null && packetSrc !== void 0 ? packetSrc : 0;
425
425
  const resolvedRouter = router !== null && router !== void 0 ? router : 0;
426
426
  const resolvedSeq = seq !== null && seq !== void 0 ? seq : PROTO_SEQ_DEFAULT;
@@ -430,7 +430,7 @@ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
430
430
  const payloadLen = payload ? payload.length : 0;
431
431
  const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
432
432
  if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
433
- throw new Error(`Protocol V2 frame too large: ${frameLen}`);
433
+ throw new Error(`Protocol V2 frame too large: ${frameLen} > ${PROTOCOL_V2_FRAME_MAX_BYTES}`);
434
434
  }
435
435
  const frame = new Uint8Array(frameLen);
436
436
  frame[0] = PROTO_HEAD_SOF;
@@ -445,27 +445,17 @@ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
445
445
  frame.set(payload, 7);
446
446
  }
447
447
  frame[frameLen - 1] = crc8(frame, frameLen - 1);
448
- logProtocolV2Debug(debugOptions, 'encode raw frame', {
449
- frameLen,
450
- payloadLen,
451
- packetSrc: resolvedPacketSrc,
452
- router: frame[4],
453
- attr: frame[5],
454
- seq: frame[6],
455
- headerCrc: frame[3],
456
- frameCrc: frame[frameLen - 1],
457
- });
458
448
  return frame;
459
449
  }
460
- function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, debugOptions, seq) {
450
+ function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, seq) {
461
451
  const payload = new Uint8Array(2 + pbPayload.length);
462
452
  payload[0] = messageTypeId % 256;
463
453
  payload[1] = Math.floor(messageTypeId / 256) % 256;
464
454
  payload.set(pbPayload, 2);
465
- return encodeFrame(payload, packetSrc, router, Object.assign(Object.assign({}, debugOptions), { messageTypeId, pbPayloadLength: pbPayload.length }), seq);
455
+ return encodeFrame(payload, packetSrc, router, seq);
466
456
  }
467
457
 
468
- function validateFrame(data) {
458
+ function inspectFrameHeader(data) {
469
459
  if (data.length < PROTO_HEAD_CRC_SIZE) {
470
460
  throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
471
461
  }
@@ -473,8 +463,8 @@ function validateFrame(data) {
473
463
  throw new Error(`Invalid SOF byte: expected 0x5A, got 0x${data[0].toString(16).padStart(2, '0')}`);
474
464
  }
475
465
  const frameLen = data[1] + data[2] * 256;
476
- if (data.length < frameLen) {
477
- throw new Error(`Frame truncated: expected ${frameLen} bytes, got ${data.length}`);
466
+ if (data.length !== frameLen) {
467
+ throw new Error(`Protocol V2 frame length mismatch: expected ${frameLen} bytes, got ${data.length}`);
478
468
  }
479
469
  const expectedHeaderCrc = crc8(data, 3);
480
470
  if (data[3] !== expectedHeaderCrc) {
@@ -488,44 +478,53 @@ function validateFrame(data) {
488
478
  .toString(16)
489
479
  .padStart(2, '0')}, got 0x${data[frameLen - 1].toString(16).padStart(2, '0')}`);
490
480
  }
491
- return frameLen;
481
+ const dataType = data[5] & 0x03;
482
+ const packetSrc = (data[5] >> 2) & 0x0f;
483
+ const seq = data[6];
484
+ if (seq === 0) {
485
+ throw new Error('Invalid Protocol V2 sequence: 0 is reserved');
486
+ }
487
+ return {
488
+ frameLen,
489
+ router: data[4],
490
+ packetSrc,
491
+ dataType,
492
+ seq,
493
+ };
492
494
  }
493
495
  function isAckFrame(data) {
494
496
  if (data.length < 6 || (data[5] & 0x03) !== PROTO_DATA_TYPE_ACK) {
495
497
  return false;
496
498
  }
497
- const frameLen = validateFrame(data);
498
- if (frameLen !== PROTO_HEAD_CRC_SIZE) {
499
- throw new Error(`Invalid Protocol V2 ACK frame length: ${frameLen}`);
499
+ const header = inspectFrameHeader(data);
500
+ if (header.frameLen !== PROTO_HEAD_CRC_SIZE) {
501
+ throw new Error(`Invalid Protocol V2 ACK frame length: ${header.frameLen}`);
500
502
  }
501
503
  return true;
502
504
  }
503
- function decodeFrame(data, debugOptions) {
504
- const frameLen = validateFrame(data);
505
- const expectedHeaderCrc = data[3];
506
- const expectedFrameCrc = data[frameLen - 1];
507
- const seq = data[6];
505
+ function decodeFrame(data) {
506
+ const { frameLen, router, packetSrc, dataType, seq } = inspectFrameHeader(data);
507
+ if (dataType !== PROTO_DATA_TYPE_PACKET) {
508
+ throw new Error(`Invalid Protocol V2 data type: expected packet, got ${dataType}`);
509
+ }
508
510
  const payloadData = data.slice(7, frameLen - 1);
509
511
  if (payloadData.length < 2) {
510
512
  throw new Error(`Protocol V2 payload too short (need >=2 bytes for messageTypeId)`);
511
513
  }
512
514
  const messageTypeId = payloadData[0] + payloadData[1] * 256;
513
515
  const pbPayload = payloadData.slice(2);
514
- logProtocolV2Debug(debugOptions, 'decode raw frame', {
515
- frameLen,
516
- dataLength: data.length,
517
- router: data[4],
518
- attr: data[5],
519
- seq,
520
- headerCrc: data[3],
521
- expectedHeaderCrc,
522
- frameCrc: data[frameLen - 1],
523
- expectedFrameCrc,
524
- messageTypeId,
525
- pbPayloadLength: pbPayload.length,
526
- });
527
- return { messageTypeId, pbPayload, seq };
516
+ return { messageTypeId, pbPayload, seq, router, packetSrc, dataType };
517
+ }
518
+
519
+ class ProtocolV2LinkError extends Error {
520
+ constructor(code, message, cause) {
521
+ super(message);
522
+ this.name = 'ProtocolV2LinkError';
523
+ this.code = code;
524
+ this.cause = cause;
525
+ }
528
526
  }
527
+ const isProtocolV2LinkError = (error) => error instanceof ProtocolV2LinkError;
529
528
 
530
529
  function concatUint8Arrays(arrays) {
531
530
  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
@@ -570,23 +569,23 @@ class ProtocolV2FrameAssembler {
570
569
  return undefined;
571
570
  if (this.buffer[0] !== PROTO_HEAD_SOF) {
572
571
  this.reset();
573
- throw new Error('Invalid Protocol V2 SOF');
572
+ throw new ProtocolV2LinkError('frame', 'Invalid Protocol V2 SOF');
574
573
  }
575
574
  const expectedLen = this.buffer[1] + this.buffer[2] * 256;
576
575
  if (expectedLen < PROTO_HEAD_CRC_SIZE) {
577
576
  this.reset();
578
- throw new Error(`Protocol V2 frame length too small: ${expectedLen}`);
577
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame length too small: ${expectedLen}`);
579
578
  }
580
579
  if (expectedLen > this.maxFrameBytes) {
581
580
  this.reset();
582
- throw new Error(`Protocol V2 frame too large: ${expectedLen}`);
581
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame too large: ${expectedLen}`);
583
582
  }
584
583
  if (this.buffer.length < PROTO_PRE_HEAD_SIZE)
585
584
  return undefined;
586
585
  const expectedHeaderCrc = crc8(this.buffer, 3);
587
586
  if (this.buffer[3] !== expectedHeaderCrc) {
588
587
  this.reset();
589
- throw new Error(`Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
588
+ throw new ProtocolV2LinkError('frame', `Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
590
589
  .toString(16)
591
590
  .padStart(2, '0')}`);
592
591
  }
@@ -598,6 +597,51 @@ class ProtocolV2FrameAssembler {
598
597
  }
599
598
  }
600
599
 
600
+ const defaultWait = (timeoutMs) => new Promise(resolve => {
601
+ setTimeout(resolve, timeoutMs);
602
+ });
603
+ function writeProtocolV2BleFrame({ frame, packetCapacity, writePacket, assertActive, signal, abortMessage = 'Protocol V2 BLE write aborted', initialDelayMs = 0, burstSize, burstPauseMs = 0, flushDelayMs = 0, wait = defaultWait, }) {
604
+ return __awaiter(this, void 0, void 0, function* () {
605
+ if (!Number.isInteger(packetCapacity) || packetCapacity <= 0) {
606
+ throw new Error('Protocol V2 BLE packet capacity must be a positive integer');
607
+ }
608
+ if (burstSize !== undefined && (!Number.isInteger(burstSize) || burstSize <= 0)) {
609
+ throw new Error('Protocol V2 BLE burst size must be a positive integer');
610
+ }
611
+ const assertWritable = () => {
612
+ assertActive === null || assertActive === void 0 ? void 0 : assertActive();
613
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
614
+ throw new Error(abortMessage);
615
+ }
616
+ };
617
+ if (frame.length > 0 && initialDelayMs > 0) {
618
+ assertWritable();
619
+ yield wait(initialDelayMs);
620
+ assertWritable();
621
+ }
622
+ let packetsWritten = 0;
623
+ for (let offset = 0; offset < frame.length; offset += packetCapacity) {
624
+ assertWritable();
625
+ const packet = frame.slice(offset, offset + packetCapacity);
626
+ yield writePacket(packet, packetsWritten);
627
+ packetsWritten += 1;
628
+ assertWritable();
629
+ const hasMorePackets = offset + packetCapacity < frame.length;
630
+ if (hasMorePackets &&
631
+ burstSize !== undefined &&
632
+ packetsWritten % burstSize === 0 &&
633
+ burstPauseMs > 0) {
634
+ yield wait(burstPauseMs);
635
+ assertWritable();
636
+ }
637
+ }
638
+ if (burstSize !== undefined && packetsWritten > burstSize && flushDelayMs > 0) {
639
+ yield wait(flushDelayMs);
640
+ assertWritable();
641
+ }
642
+ });
643
+ }
644
+
601
645
  var protocolV2Codec = /*#__PURE__*/Object.freeze({
602
646
  __proto__: null,
603
647
  PROTO_HEAD_SOF: PROTO_HEAD_SOF,
@@ -609,17 +653,95 @@ var protocolV2Codec = /*#__PURE__*/Object.freeze({
609
653
  PROTO_DATA_TYPE_ACK: PROTO_DATA_TYPE_ACK,
610
654
  CRC8_TABLE: CRC8_TABLE,
611
655
  crc8: crc8,
612
- logProtocolV2Debug: logProtocolV2Debug,
613
656
  nextProtoSeq: nextProtoSeq,
614
657
  encodeFrame: encodeFrame,
615
658
  encodeProtobufFrame: encodeProtobufFrame,
659
+ inspectFrameHeader: inspectFrameHeader,
616
660
  isAckFrame: isAckFrame,
617
661
  decodeFrame: decodeFrame,
662
+ ProtocolV2LinkError: ProtocolV2LinkError,
663
+ isProtocolV2LinkError: isProtocolV2LinkError,
618
664
  concatUint8Arrays: concatUint8Arrays,
619
- ProtocolV2FrameAssembler: ProtocolV2FrameAssembler
665
+ ProtocolV2FrameAssembler: ProtocolV2FrameAssembler,
666
+ writeProtocolV2BleFrame: writeProtocolV2BleFrame
620
667
  });
621
668
 
622
669
  const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
670
+ const LEGACY_PROTOCOL_V2_PROTOCOL_INFO = protobuf.Type.fromJSON('LegacyProtocolInfo', {
671
+ fields: {
672
+ version: {
673
+ rule: 'required',
674
+ type: 'uint32',
675
+ id: 1,
676
+ },
677
+ supported_messages: {
678
+ rule: 'repeated',
679
+ type: 'uint32',
680
+ id: 2,
681
+ options: {
682
+ packed: false,
683
+ },
684
+ },
685
+ protobuf_definition: {
686
+ type: 'string',
687
+ id: 3,
688
+ },
689
+ },
690
+ });
691
+ const decodeLegacyProtocolV2ProtocolInfo = (pbPayload) => {
692
+ var _a;
693
+ const byteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
694
+ const legacy = decode(LEGACY_PROTOCOL_V2_PROTOCOL_INFO, byteBuffer);
695
+ return {
696
+ version: legacy.version,
697
+ build_fingerprint: '',
698
+ supported_messages: (_a = legacy.supported_messages) !== null && _a !== void 0 ? _a : [],
699
+ protobuf_definition: null,
700
+ };
701
+ };
702
+ const isLegacyProtocolV2ProtocolInfoWireLayout = (pbPayload) => {
703
+ const reader = protobuf.Reader.create(pbPayload);
704
+ let hasVersion = false;
705
+ try {
706
+ while (reader.pos < reader.len) {
707
+ const tag = reader.uint32();
708
+ const fieldNumber = tag >>> 3;
709
+ const wireType = tag & 0x07;
710
+ if (fieldNumber === 1) {
711
+ if (wireType !== 0)
712
+ return false;
713
+ hasVersion = true;
714
+ }
715
+ else if (fieldNumber === 2) {
716
+ if (wireType !== 0)
717
+ return false;
718
+ }
719
+ else if (fieldNumber === 3) {
720
+ if (wireType !== 2)
721
+ return false;
722
+ }
723
+ else {
724
+ return false;
725
+ }
726
+ reader.skipType(wireType);
727
+ }
728
+ }
729
+ catch (_a) {
730
+ return false;
731
+ }
732
+ return hasVersion;
733
+ };
734
+ const tryDecodeLegacyProtocolV2ProtocolInfo = (messageName, pbPayload) => {
735
+ if (messageName !== 'ProtocolInfo' || !isLegacyProtocolV2ProtocolInfoWireLayout(pbPayload)) {
736
+ return undefined;
737
+ }
738
+ try {
739
+ return decodeLegacyProtocolV2ProtocolInfo(pbPayload);
740
+ }
741
+ catch (_a) {
742
+ return undefined;
743
+ }
744
+ };
623
745
  const resolveProtocolV2EncodeSchema = (name, schemas) => {
624
746
  try {
625
747
  schemas.protocolV2.lookupType(name);
@@ -665,46 +787,56 @@ const ProtocolV1 = {
665
787
  };
666
788
  const ProtocolV2 = {
667
789
  isAckFrame,
790
+ inspectFrameHeader,
791
+ inspectFrame(schemas, frame) {
792
+ const { messageTypeId, pbPayload, seq, router, packetSrc, dataType } = decodeFrame(frame);
793
+ const { messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
794
+ return {
795
+ messageName,
796
+ messageTypeId,
797
+ pbPayload,
798
+ seq,
799
+ router,
800
+ packetSrc,
801
+ dataType,
802
+ type: messageName,
803
+ };
804
+ },
668
805
  encodeFrame(schemas, name, data, options = {}) {
669
- var _a, _b, _c, _d, _e, _f, _g;
670
806
  const encodeMessages = resolveProtocolV2EncodeSchema(name, schemas);
671
807
  const { Message, messageTypeId } = createMessageFromName(encodeMessages, name);
672
808
  const pbBuffer = encode(Message, data);
673
809
  pbBuffer.reset();
674
810
  const rawPbBuffer = pbBuffer.toBuffer();
675
811
  const pbBytes = new Uint8Array(rawPbBuffer);
676
- (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `[${(_c = options.logPrefix) !== null && _c !== void 0 ? _c : 'ProtocolV2'}] encode protobuf`, {
677
- context: (_d = options.context) !== null && _d !== void 0 ? _d : `encode:${name}`,
678
- messageName: name,
679
- messageTypeId,
680
- pbPayloadLength: pbBytes.length,
681
- packetSrc: (_e = options.packetSrc) !== null && _e !== void 0 ? _e : 0,
682
- router: (_f = options.router) !== null && _f !== void 0 ? _f : 0,
683
- });
684
- return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, {
685
- logger: options.logger,
686
- logPrefix: options.logPrefix,
687
- context: (_g = options.context) !== null && _g !== void 0 ? _g : `encode:${name}`,
688
- messageName: name,
689
- }, options.seq);
812
+ return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, options.seq);
690
813
  },
691
- decodeFrame(schemas, frame, options = {}) {
692
- var _a, _b, _c, _d, _e;
693
- const { messageTypeId, pbPayload, seq } = decodeFrame(frame, {
694
- logger: options.logger,
695
- logPrefix: options.logPrefix,
696
- context: (_a = options.context) !== null && _a !== void 0 ? _a : 'decode',
697
- });
698
- const { Message, messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
814
+ decodeFrame(schemas, frame) {
815
+ const { messageTypeId, pbPayload, seq, messageName } = this.inspectFrame(schemas, frame);
816
+ const { Message } = createProtocolV2MessageFromType(messageTypeId, schemas);
699
817
  const rxByteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
700
- const message = decode(Message, rxByteBuffer);
701
- (_c = (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug) === null || _c === void 0 ? void 0 : _c.call(_b, `[${(_d = options.logPrefix) !== null && _d !== void 0 ? _d : 'ProtocolV2'}] decode protobuf`, {
702
- context: (_e = options.context) !== null && _e !== void 0 ? _e : `decode:${messageName}`,
703
- messageName,
704
- messageTypeId,
705
- pbPayloadLength: pbPayload.length,
706
- seq,
707
- });
818
+ let message;
819
+ try {
820
+ message = decode(Message, rxByteBuffer);
821
+ }
822
+ catch (cause) {
823
+ const legacyProtocolInfo = tryDecodeLegacyProtocolV2ProtocolInfo(messageName, pbPayload);
824
+ if (legacyProtocolInfo) {
825
+ return {
826
+ message: legacyProtocolInfo,
827
+ messageName,
828
+ messageTypeId,
829
+ pbPayload,
830
+ seq,
831
+ type: messageName,
832
+ };
833
+ }
834
+ const error = new Error(`Protocol V2 protobuf decode failed for "${messageName}" ` +
835
+ `(${messageTypeId}, ${pbPayload.length}-byte payload); ` +
836
+ 'the payload is malformed or incompatible with the active SDK schema.');
837
+ error.cause = cause;
838
+ throw error;
839
+ }
708
840
  return {
709
841
  message,
710
842
  messageName,
@@ -853,93 +985,27 @@ function bytesToHex(bytes) {
853
985
  .map(b => b.toString(16).padStart(2, '0'))
854
986
  .join('');
855
987
  }
856
- const PROTOCOL_V2_DEBUG_HEADER_BYTES = 7;
857
- const PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT = 20;
858
- const PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT = 40;
859
- const PROTOCOL_V2_DEBUG_STRING_LIMIT = 512;
860
- const PROTOCOL_V2_DEBUG_DEPTH_LIMIT = 4;
861
- const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
988
+ const REDUCED_DEBUG_PROTOCOL_V2_CALLS = new Set([
862
989
  ...LogBlockCommand,
863
990
  'FilesystemFileRead',
864
991
  'FileRead',
865
992
  'EmmcFileRead',
866
993
  ]);
867
994
  function shouldReduceProtocolV2Debug(name) {
868
- return HIGH_VOLUME_PROTOCOL_V2_CALLS.has(name);
869
- }
870
- function frameHeaderDebugHex(frame) {
871
- return bytesToHex(frame.slice(0, PROTOCOL_V2_DEBUG_HEADER_BYTES));
872
- }
873
- function getBinaryByteLength(value) {
874
- if (value instanceof ArrayBuffer) {
875
- return value.byteLength;
876
- }
877
- if (ArrayBuffer.isView(value)) {
878
- return value.byteLength;
879
- }
880
- if (typeof Blob !== 'undefined' && value instanceof Blob) {
881
- return value.size;
882
- }
883
- return undefined;
884
- }
885
- function summarizeRedactedData(value) {
886
- const byteLength = getBinaryByteLength(value);
887
- if (byteLength !== undefined) {
888
- return `[redacted data: ${byteLength} bytes]`;
889
- }
890
- if (typeof value === 'string') {
891
- return `[redacted data: string length=${value.length}]`;
892
- }
893
- if (Array.isArray(value)) {
894
- return `[redacted data: array length=${value.length}]`;
895
- }
896
- if (value && typeof value === 'object') {
897
- return `[redacted data: object keys=${Object.keys(value).length}]`;
898
- }
899
- return `[redacted data: ${typeof value}]`;
995
+ return REDUCED_DEBUG_PROTOCOL_V2_CALLS.has(name);
900
996
  }
901
- function sanitizeProtocolV2DebugPayload(value, key = '', depth = 0) {
902
- if (/^(data|payload)$/i.test(key) && value !== null && value !== undefined) {
903
- return summarizeRedactedData(value);
904
- }
905
- if (/(passphrase|pin|mnemonic|seed|private)/i.test(key)) {
906
- return '[redacted sensitive value]';
907
- }
908
- const byteLength = getBinaryByteLength(value);
909
- if (byteLength !== undefined) {
910
- return `[binary: ${byteLength} bytes]`;
911
- }
912
- if (typeof value === 'string') {
913
- return value.length > PROTOCOL_V2_DEBUG_STRING_LIMIT
914
- ? `${value.slice(0, PROTOCOL_V2_DEBUG_STRING_LIMIT)}... (len=${value.length})`
915
- : value;
916
- }
917
- if (!value || typeof value !== 'object') {
918
- return value;
919
- }
920
- if (depth >= PROTOCOL_V2_DEBUG_DEPTH_LIMIT) {
921
- return Array.isArray(value)
922
- ? `[array length=${value.length}]`
923
- : `[object keys=${Object.keys(value).length}]`;
924
- }
925
- if (Array.isArray(value)) {
926
- const items = value
927
- .slice(0, PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT)
928
- .map(item => sanitizeProtocolV2DebugPayload(item, key, depth + 1));
929
- if (value.length > PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT) {
930
- items.push(`... (${value.length - PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT} more)`);
931
- }
932
- return items;
933
- }
934
- const entries = Object.entries(value).slice(0, PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT);
935
- const sanitized = {};
936
- entries.forEach(([entryKey, entryValue]) => {
937
- sanitized[entryKey] = sanitizeProtocolV2DebugPayload(entryValue, entryKey, depth + 1);
938
- });
939
- if (Object.keys(value).length > PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT) {
940
- sanitized.__truncated__ = `${Object.keys(value).length - PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT} more keys`;
941
- }
942
- return sanitized;
997
+ const HIGH_THROUGHPUT_PROTOCOL_V2_CALLS = new Set([
998
+ 'FilesystemFileWrite',
999
+ 'FileWrite',
1000
+ 'EmmcFileWrite',
1001
+ 'FirmwareUpload',
1002
+ 'ResourceAck',
1003
+ 'FilesystemFileRead',
1004
+ 'FileRead',
1005
+ 'EmmcFileRead',
1006
+ ]);
1007
+ function isProtocolV2HighThroughputCall(name) {
1008
+ return HIGH_THROUGHPUT_PROTOCOL_V2_CALLS.has(name);
943
1009
  }
944
1010
  const COMMON_TERMINAL_RESPONSE_TYPES = new Set([
945
1011
  'Failure',
@@ -966,11 +1032,12 @@ function getErrorMessage(error) {
966
1032
  }
967
1033
  return String(error);
968
1034
  }
969
- function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout) {
1035
+ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout, abortSignal) {
970
1036
  return __awaiter(this, void 0, void 0, function* () {
971
1037
  if (!timeoutMs)
972
1038
  return promise;
973
1039
  let timer;
1040
+ let abortHandler;
974
1041
  try {
975
1042
  return yield Promise.race([
976
1043
  promise,
@@ -980,15 +1047,32 @@ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout)
980
1047
  reject(createTimeoutError());
981
1048
  }, timeoutMs);
982
1049
  }),
1050
+ ...(abortSignal
1051
+ ? [
1052
+ new Promise((_, reject) => {
1053
+ abortHandler = () => {
1054
+ reject(new Error('Protocol V2 operation aborted'));
1055
+ };
1056
+ if (abortSignal.aborted) {
1057
+ abortHandler();
1058
+ }
1059
+ else {
1060
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
1061
+ }
1062
+ }),
1063
+ ]
1064
+ : []),
983
1065
  ]);
984
1066
  }
985
1067
  finally {
986
1068
  if (timer)
987
1069
  clearTimeout(timer);
1070
+ if (abortHandler) {
1071
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener('abort', abortHandler);
1072
+ }
988
1073
  }
989
1074
  });
990
1075
  }
991
- const PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = 0;
992
1076
  class ProtocolV2Session {
993
1077
  constructor(options) {
994
1078
  var _a;
@@ -1003,87 +1087,97 @@ class ProtocolV2Session {
1003
1087
  return result;
1004
1088
  }
1005
1089
  executeCall(name, data, callOptions) {
1006
- var _a, _b;
1007
- return __awaiter(this, void 0, void 0, function* () {
1008
- const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
1009
- const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
1010
- const callContext = {
1011
- messageName: name,
1012
- timeoutMs: callOptions.timeoutMs,
1013
- highVolume: shouldReduceDebug,
1014
- generation,
1015
- };
1016
- yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(callContext));
1090
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
1091
+ const timeoutMs = callOptions.timeoutMs && callOptions.timeoutMs > 0
1092
+ ? callOptions.timeoutMs
1093
+ : PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1094
+ const abortController = new AbortController();
1095
+ const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
1096
+ const baseCallContext = Object.assign(Object.assign({ messageName: name, timeoutMs, highThroughput: isProtocolV2HighThroughputCall(name) }, (callOptions.writeWithResponse === undefined
1097
+ ? {}
1098
+ : { writeWithResponse: callOptions.writeWithResponse })), { generation, signal: abortController.signal });
1099
+ const runCall = () => __awaiter(this, void 0, void 0, function* () {
1100
+ var _a, _b, _c, _d, _e, _f;
1101
+ yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(baseCallContext));
1017
1102
  const protoSeq = this.sequenceCursor.next();
1018
1103
  const frame = ProtocolV2.encodeFrame(schemas, name, data, {
1019
1104
  packetSrc,
1020
1105
  router,
1021
1106
  seq: protoSeq,
1022
- logger: shouldReduceDebug ? undefined : logger,
1023
- logPrefix,
1024
- context: `tx:${name}`,
1025
1107
  });
1026
- const expectedSeq = frame[6];
1027
1108
  if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
1028
1109
  throw new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`);
1029
1110
  }
1030
- if (!shouldReduceDebug) {
1031
- (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] TX payload name=${name}`, sanitizeProtocolV2DebugPayload(data));
1032
- (_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, `[${logPrefix}] TX frame name=${name} len=${frame.length} router=${frame[4]} attr=${frame[5]} seq=${expectedSeq} headerHex=${frameHeaderDebugHex(frame)}`);
1111
+ const writeStartedAt = Date.now();
1112
+ yield writeFrame(frame, baseCallContext);
1113
+ try {
1114
+ (_a = callOptions.onWriteCompleted) === null || _a === void 0 ? void 0 : _a.call(callOptions, {
1115
+ elapsedMs: Math.max(Date.now() - writeStartedAt, 0),
1116
+ frameBytes: frame.byteLength,
1117
+ });
1033
1118
  }
1034
- yield withProtocolTimeout(writeFrame(frame, callContext), PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS, () => new Error(`Protocol V2 write timeout after ${PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS}ms for ${name}`));
1035
- const cancellation = { cancelled: false };
1036
- const readResponse = () => __awaiter(this, void 0, void 0, function* () {
1037
- var _c, _d, _e, _f, _g, _h, _j, _k, _l;
1038
- while (!cancellation.cancelled) {
1039
- const rxFrame = yield readFrame(callContext);
1040
- if (cancellation.cancelled) {
1041
- break;
1119
+ catch (error) {
1120
+ (_b = logger === null || logger === void 0 ? void 0 : logger.error) === null || _b === void 0 ? void 0 : _b.call(logger, `${logPrefix} write metrics callback failed: ${String(error)}`);
1121
+ }
1122
+ while (!abortController.signal.aborted) {
1123
+ const rxFrame = yield readFrame(baseCallContext);
1124
+ if (abortController.signal.aborted)
1125
+ break;
1126
+ let header;
1127
+ try {
1128
+ header = ProtocolV2.inspectFrameHeader(rxFrame);
1129
+ }
1130
+ catch (cause) {
1131
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame validation failed: ${getErrorMessage(cause)}`, cause);
1132
+ }
1133
+ if (header.router !== router) {
1134
+ throw new ProtocolV2LinkError('router', `Protocol V2 router mismatch: expected ${router}, got ${header.router}`);
1135
+ }
1136
+ if (header.packetSrc !== packetSrc) {
1137
+ throw new ProtocolV2LinkError('packet-source', `Protocol V2 packet source mismatch: expected ${packetSrc}, got ${header.packetSrc}`);
1138
+ }
1139
+ let isAck;
1140
+ try {
1141
+ isAck = ProtocolV2.isAckFrame(rxFrame);
1142
+ }
1143
+ catch (cause) {
1144
+ throw new ProtocolV2LinkError('frame', `Protocol V2 ACK validation failed: ${getErrorMessage(cause)}`, cause);
1145
+ }
1146
+ if (isAck) {
1147
+ if (header.seq !== protoSeq) {
1148
+ throw new ProtocolV2LinkError('ack-sequence', `Protocol V2 ACK sequence mismatch: expected ${protoSeq}, got ${header.seq}`);
1149
+ }
1150
+ }
1151
+ else {
1152
+ let decoded;
1153
+ try {
1154
+ decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
1155
+ }
1156
+ catch (cause) {
1157
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame decode failed: ${getErrorMessage(cause)}`, cause);
1042
1158
  }
1043
- if (!shouldReduceDebug) {
1044
- (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] RX frame len=${rxFrame.length} router=${rxFrame[4]} attr=${rxFrame[5]} seq=${rxFrame[6]} headerHex=${frameHeaderDebugHex(rxFrame)}`);
1159
+ if (this.lastResponseSequence === decoded.seq) {
1160
+ throw new ProtocolV2LinkError('response-sequence', `Protocol V2 duplicate response sequence: ${decoded.seq}`);
1045
1161
  }
1046
- const isAck = ProtocolV2.isAckFrame(rxFrame);
1047
- if (isAck) {
1048
- if (!shouldReduceDebug) {
1049
- (_d = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _d === void 0 ? void 0 : _d.call(logger, `[${logPrefix}] skip Proto Link ACK seq=${rxFrame[6]}`);
1050
- }
1162
+ this.lastResponseSequence = decoded.seq;
1163
+ const response = call(decoded);
1164
+ if ((_c = callOptions.intermediateTypes) === null || _c === void 0 ? void 0 : _c.includes(response.type)) {
1165
+ (_d = callOptions.onIntermediateResponse) === null || _d === void 0 ? void 0 : _d.call(callOptions, response);
1051
1166
  }
1052
- if (!isAck) {
1053
- const decoded = ProtocolV2.decodeFrame(schemas, rxFrame, {
1054
- logger: shouldReduceDebug ? undefined : logger,
1055
- logPrefix,
1056
- context: `rx:${name}`,
1057
- });
1058
- if (!shouldReduceDebug && decoded.seq !== expectedSeq) {
1059
- (_e = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _e === void 0 ? void 0 : _e.call(logger, `[${logPrefix}] seq differs for ${name}: tx=${expectedSeq}, rx=${decoded.seq}`);
1060
- }
1061
- if (!shouldReduceDebug) {
1062
- (_f = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _f === void 0 ? void 0 : _f.call(logger, `[${logPrefix}] TX name=${name} seq=${expectedSeq} | RX seq=${decoded.seq} messageTypeId=${decoded.messageTypeId} pbPayload=${decoded.pbPayload.length}B`);
1063
- (_g = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _g === void 0 ? void 0 : _g.call(logger, `[${logPrefix}] RX payload type=${decoded.type} messageTypeId=${decoded.messageTypeId}`, sanitizeProtocolV2DebugPayload(decoded.message));
1064
- }
1065
- const response = call(decoded);
1066
- if ((_h = callOptions.intermediateTypes) === null || _h === void 0 ? void 0 : _h.includes(response.type)) {
1067
- (_j = callOptions.onIntermediateResponse) === null || _j === void 0 ? void 0 : _j.call(callOptions, response);
1068
- }
1069
- else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1070
- return response;
1071
- }
1072
- else if (!shouldReduceDebug) {
1073
- (_k = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _k === void 0 ? void 0 : _k.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_l = callOptions.expectedTypes) === null || _l === void 0 ? void 0 : _l.join('|')} got=${response.type}`);
1074
- }
1167
+ else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1168
+ return response;
1169
+ }
1170
+ else if (!shouldReduceDebug) {
1171
+ (_e = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _e === void 0 ? void 0 : _e.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_f = callOptions.expectedTypes) === null || _f === void 0 ? void 0 : _f.join('|')} got=${response.type}`);
1075
1172
  }
1076
1173
  }
1077
- throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1078
- });
1079
- return withProtocolTimeout(readResponse(), callOptions.timeoutMs, () => {
1080
- var _a;
1081
- return createTimeoutError
1082
- ? createTimeoutError(name, (_a = callOptions.timeoutMs) !== null && _a !== void 0 ? _a : 0)
1083
- : new Error(`Protocol V2 response timeout after ${callOptions.timeoutMs}ms for ${name}`);
1084
- }, () => {
1085
- cancellation.cancelled = true;
1086
- });
1174
+ }
1175
+ throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1176
+ });
1177
+ return withProtocolTimeout(runCall(), timeoutMs, () => createTimeoutError
1178
+ ? createTimeoutError(name, timeoutMs)
1179
+ : new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${name}`), () => {
1180
+ abortController.abort();
1087
1181
  });
1088
1182
  }
1089
1183
  }
@@ -1093,7 +1187,10 @@ function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', on
1093
1187
  let probeError;
1094
1188
  try {
1095
1189
  yield (onBeforeProbe === null || onBeforeProbe === void 0 ? void 0 : onBeforeProbe());
1096
- const response = yield call('Ping', { message: 'protocol-v2-probe' }, { timeoutMs, expectedTypes: ['Success'] });
1190
+ const response = yield call('Ping', { message: 'protocol-v2-probe' }, {
1191
+ timeoutMs,
1192
+ expectedTypes: ['Success'],
1193
+ });
1097
1194
  if (response.type === 'Success') {
1098
1195
  return true;
1099
1196
  }
@@ -1113,12 +1210,19 @@ class ProtocolV2LinkManager {
1113
1210
  this.links = new Map();
1114
1211
  this.sequences = new Map();
1115
1212
  this.callQueues = new Map();
1213
+ this.generations = new Map();
1214
+ this.invalidationReasons = new Map();
1215
+ this.invalidations = new Map();
1116
1216
  this.options = options;
1117
1217
  }
1118
1218
  call(key, createAdapter, name, data, options) {
1119
- var _a;
1120
- const run = () => this.executeCall(key, createAdapter, name, data, options);
1121
- const previous = (_a = this.callQueues.get(key)) !== null && _a !== void 0 ? _a : Promise.resolve();
1219
+ var _a, _b;
1220
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1221
+ const run = () => {
1222
+ this.assertCallGeneration(key, generation);
1223
+ return this.executeCall(key, createAdapter, name, data, options);
1224
+ };
1225
+ const previous = (_b = this.callQueues.get(key)) !== null && _b !== void 0 ? _b : Promise.resolve();
1122
1226
  const result = previous.then(run, run);
1123
1227
  const queue = result.catch(() => undefined);
1124
1228
  this.callQueues.set(key, queue);
@@ -1128,20 +1232,44 @@ class ProtocolV2LinkManager {
1128
1232
  return result;
1129
1233
  }
1130
1234
  invalidateLink(key, reason) {
1131
- var _a, _b;
1235
+ var _a;
1132
1236
  return __awaiter(this, void 0, void 0, function* () {
1237
+ const generation = ((_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1238
+ this.generations.set(key, generation);
1239
+ this.invalidationReasons.set(key, { generation, reason });
1240
+ const pendingInvalidation = this.invalidations.get(key);
1133
1241
  const link = this.links.get(key);
1134
- if (!link)
1242
+ if (!link) {
1243
+ yield pendingInvalidation;
1135
1244
  return;
1245
+ }
1136
1246
  this.links.delete(key);
1137
1247
  link.state.invalidatedReason = reason;
1138
- yield link.adapter.reset(reason);
1139
- yield ((_b = (_a = this.options).onLinkInvalidated) === null || _b === void 0 ? void 0 : _b.call(_a, key, reason));
1248
+ const invalidation = (() => __awaiter(this, void 0, void 0, function* () {
1249
+ var _b, _c;
1250
+ yield (pendingInvalidation === null || pendingInvalidation === void 0 ? void 0 : pendingInvalidation.catch(() => undefined));
1251
+ yield link.adapter.reset(reason);
1252
+ yield ((_c = (_b = this.options).onLinkInvalidated) === null || _c === void 0 ? void 0 : _c.call(_b, key, reason));
1253
+ }))();
1254
+ this.invalidations.set(key, invalidation);
1255
+ try {
1256
+ yield invalidation;
1257
+ }
1258
+ finally {
1259
+ if (this.invalidations.get(key) === invalidation) {
1260
+ this.invalidations.delete(key);
1261
+ }
1262
+ }
1140
1263
  });
1141
1264
  }
1142
1265
  invalidateAllLinks(reason) {
1143
1266
  return __awaiter(this, void 0, void 0, function* () {
1144
- yield Promise.all(Array.from(this.links.keys(), key => this.invalidateLink(key, reason)));
1267
+ const keys = new Set([
1268
+ ...this.links.keys(),
1269
+ ...this.callQueues.keys(),
1270
+ ...this.invalidations.keys(),
1271
+ ]);
1272
+ yield Promise.all(Array.from(keys, key => this.invalidateLink(key, reason)));
1145
1273
  });
1146
1274
  }
1147
1275
  dispose(reason) {
@@ -1149,6 +1277,7 @@ class ProtocolV2LinkManager {
1149
1277
  yield this.invalidateAllLinks(reason);
1150
1278
  this.sequences.clear();
1151
1279
  this.callQueues.clear();
1280
+ this.invalidations.clear();
1152
1281
  });
1153
1282
  }
1154
1283
  getOrCreateLink(key, createAdapter) {
@@ -1216,6 +1345,17 @@ class ProtocolV2LinkManager {
1216
1345
  this.callQueues.delete(key);
1217
1346
  }
1218
1347
  }
1348
+ assertCallGeneration(key, generation) {
1349
+ var _a;
1350
+ const currentGeneration = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1351
+ if (currentGeneration === generation)
1352
+ return;
1353
+ const invalidation = this.invalidationReasons.get(key);
1354
+ const reason = (invalidation === null || invalidation === void 0 ? void 0 : invalidation.generation) === currentGeneration
1355
+ ? invalidation.reason
1356
+ : 'Protocol V2 link generation changed';
1357
+ throw new ProtocolV2LinkError('generation', reason);
1358
+ }
1219
1359
  }
1220
1360
 
1221
1361
  class ProtocolV2UsbTransportBase {
@@ -1226,7 +1366,7 @@ class ProtocolV2UsbTransportBase {
1226
1366
  this.protocolV2UsbOptions = options;
1227
1367
  this.protocolV2UsbLinks = new ProtocolV2LinkManager({
1228
1368
  getSchemas: () => this.getProtocolV2UsbSchemas(),
1229
- classifyError: () => 'link-fatal',
1369
+ classifyError: error => (isProtocolV2LinkError(error) ? 'link-fatal' : 'recoverable'),
1230
1370
  onLinkInvalidated: (key, reason) => __awaiter(this, void 0, void 0, function* () {
1231
1371
  var _a;
1232
1372
  (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
@@ -1276,10 +1416,10 @@ class ProtocolV2UsbTransportBase {
1276
1416
  }
1277
1417
  const assertCurrentGeneration = () => {
1278
1418
  if (cancellation.reason) {
1279
- throw new Error(cancellation.reason);
1419
+ throw new ProtocolV2LinkError('generation', cancellation.reason);
1280
1420
  }
1281
1421
  if (this.protocolV2UsbGenerations.get(key) !== generation) {
1282
- throw new Error('Protocol V2 USB connection generation changed');
1422
+ throw new ProtocolV2LinkError('generation', 'Protocol V2 USB connection generation changed');
1283
1423
  }
1284
1424
  };
1285
1425
  return {
@@ -1288,11 +1428,15 @@ class ProtocolV2UsbTransportBase {
1288
1428
  generation,
1289
1429
  prepareCall: () => {
1290
1430
  assertCurrentGeneration();
1291
- this.getProtocolV2UsbAssembler(key).reset();
1292
1431
  },
1293
1432
  writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1294
1433
  assertCurrentGeneration();
1295
- yield this.writeProtocolV2UsbPacket(key, frame, context);
1434
+ try {
1435
+ yield this.writeProtocolV2UsbPacket(key, frame, context);
1436
+ }
1437
+ catch (error) {
1438
+ throw this.createProtocolV2UsbIoError('write', error);
1439
+ }
1296
1440
  assertCurrentGeneration();
1297
1441
  }),
1298
1442
  readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
@@ -1300,13 +1444,15 @@ class ProtocolV2UsbTransportBase {
1300
1444
  const assembler = this.getProtocolV2UsbAssembler(key);
1301
1445
  let frame = assembler.push(new Uint8Array(0));
1302
1446
  while (!frame) {
1303
- const packetRead = this.readProtocolV2UsbPacket(key, context).then(packet => ({
1304
- packet,
1305
- }));
1447
+ const packetRead = this.readProtocolV2UsbPacket(key, context)
1448
+ .then(packet => ({ packet }))
1449
+ .catch(error => {
1450
+ throw this.createProtocolV2UsbIoError('read', error);
1451
+ });
1306
1452
  const cancelled = cancellation.promise.then(reason => ({ reason }));
1307
1453
  const result = yield Promise.race([packetRead, cancelled]);
1308
1454
  if ('reason' in result) {
1309
- throw new Error(result.reason);
1455
+ throw new ProtocolV2LinkError('generation', result.reason);
1310
1456
  }
1311
1457
  assertCurrentGeneration();
1312
1458
  frame = assembler.push(result.packet);
@@ -1347,8 +1493,17 @@ class ProtocolV2UsbTransportBase {
1347
1493
  };
1348
1494
  return cancellation;
1349
1495
  }
1496
+ createProtocolV2UsbIoError(operation, error) {
1497
+ if (isProtocolV2LinkError(error))
1498
+ return error;
1499
+ return new ProtocolV2LinkError('io', `Protocol V2 USB ${operation} failed: ${getErrorMessage(error) || 'unknown error'}`, error);
1500
+ }
1350
1501
  }
1351
1502
 
1503
+ const TRANSPORT_EVENT = {
1504
+ DEVICE_DISCONNECT: 'transport-device-disconnect',
1505
+ };
1506
+
1352
1507
  exports.AptosTransactionType = void 0;
1353
1508
  (function (AptosTransactionType) {
1354
1509
  AptosTransactionType[AptosTransactionType["STANDARD"] = 0] = "STANDARD";
@@ -1595,6 +1750,24 @@ exports.EthereumDataType = void 0;
1595
1750
  EthereumDataType[EthereumDataType["ARRAY"] = 7] = "ARRAY";
1596
1751
  EthereumDataType[EthereumDataType["STRUCT"] = 8] = "STRUCT";
1597
1752
  })(exports.EthereumDataType || (exports.EthereumDataType = {}));
1753
+ exports.Enum_KaspaInputScriptType = void 0;
1754
+ (function (Enum_KaspaInputScriptType) {
1755
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_SCHNORR"] = 0] = "KASPA_SPEND_P2PK_SCHNORR";
1756
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_ECDSA"] = 1] = "KASPA_SPEND_P2PK_ECDSA";
1757
+ })(exports.Enum_KaspaInputScriptType || (exports.Enum_KaspaInputScriptType = {}));
1758
+ exports.Enum_KaspaOutputScriptType = void 0;
1759
+ (function (Enum_KaspaOutputScriptType) {
1760
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOADDRESS"] = 0] = "KASPA_PAYTOADDRESS";
1761
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOCHANGE"] = 1] = "KASPA_PAYTOCHANGE";
1762
+ })(exports.Enum_KaspaOutputScriptType || (exports.Enum_KaspaOutputScriptType = {}));
1763
+ exports.Enum_KaspaRequestType = void 0;
1764
+ (function (Enum_KaspaRequestType) {
1765
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_INPUT"] = 0] = "KASPA_TX_INPUT";
1766
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_OUTPUT"] = 1] = "KASPA_TX_OUTPUT";
1767
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PAYLOAD"] = 2] = "KASPA_TX_PAYLOAD";
1768
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_FINISHED"] = 3] = "KASPA_TX_FINISHED";
1769
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PREV_META"] = 4] = "KASPA_TX_PREV_META";
1770
+ })(exports.Enum_KaspaRequestType || (exports.Enum_KaspaRequestType = {}));
1598
1771
  exports.Enum_BackupType = void 0;
1599
1772
  (function (Enum_BackupType) {
1600
1773
  Enum_BackupType[Enum_BackupType["Bip39"] = 0] = "Bip39";
@@ -1788,11 +1961,6 @@ exports.CommandFlags = void 0;
1788
1961
  CommandFlags[CommandFlags["Default"] = 0] = "Default";
1789
1962
  CommandFlags[CommandFlags["Factory_Only"] = 1] = "Factory_Only";
1790
1963
  })(exports.CommandFlags || (exports.CommandFlags = {}));
1791
- exports.WallpaperTarget = void 0;
1792
- (function (WallpaperTarget) {
1793
- WallpaperTarget[WallpaperTarget["Home"] = 0] = "Home";
1794
- WallpaperTarget[WallpaperTarget["Lock"] = 1] = "Lock";
1795
- })(exports.WallpaperTarget || (exports.WallpaperTarget = {}));
1796
1964
  exports.MoneroNetworkType = void 0;
1797
1965
  (function (MoneroNetworkType) {
1798
1966
  MoneroNetworkType[MoneroNetworkType["MAINNET"] = 0] = "MAINNET";
@@ -1800,19 +1968,18 @@ exports.MoneroNetworkType = void 0;
1800
1968
  MoneroNetworkType[MoneroNetworkType["STAGENET"] = 2] = "STAGENET";
1801
1969
  MoneroNetworkType[MoneroNetworkType["FAKECHAIN"] = 3] = "FAKECHAIN";
1802
1970
  })(exports.MoneroNetworkType || (exports.MoneroNetworkType = {}));
1803
- exports.ViewTipType = void 0;
1804
- (function (ViewTipType) {
1805
- ViewTipType[ViewTipType["Default"] = 0] = "Default";
1806
- ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
1807
- ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
1808
- ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
1809
- ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
1810
- })(exports.ViewTipType || (exports.ViewTipType = {}));
1811
- exports.ViewSignLayout = void 0;
1812
- (function (ViewSignLayout) {
1813
- ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
1814
- ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
1815
- })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
1971
+ exports.UiAnimationType = void 0;
1972
+ (function (UiAnimationType) {
1973
+ UiAnimationType[UiAnimationType["Unknown"] = 0] = "Unknown";
1974
+ UiAnimationType[UiAnimationType["Signing"] = 1] = "Signing";
1975
+ })(exports.UiAnimationType || (exports.UiAnimationType = {}));
1976
+ exports.UiAnimationCommand = void 0;
1977
+ (function (UiAnimationCommand) {
1978
+ UiAnimationCommand[UiAnimationCommand["CommandUnknown"] = 0] = "CommandUnknown";
1979
+ UiAnimationCommand[UiAnimationCommand["Start"] = 1] = "Start";
1980
+ UiAnimationCommand[UiAnimationCommand["Stop"] = 2] = "Stop";
1981
+ UiAnimationCommand[UiAnimationCommand["Refresh"] = 3] = "Refresh";
1982
+ })(exports.UiAnimationCommand || (exports.UiAnimationCommand = {}));
1816
1983
  exports.DeviceErrorCode = void 0;
1817
1984
  (function (DeviceErrorCode) {
1818
1985
  DeviceErrorCode[DeviceErrorCode["DeviceError_None"] = 0] = "DeviceError_None";
@@ -1839,6 +2006,11 @@ exports.DeviceSettingsPage = void 0;
1839
2006
  DeviceSettingsPage[DeviceSettingsPage["DevicePassphrase"] = 2] = "DevicePassphrase";
1840
2007
  DeviceSettingsPage[DeviceSettingsPage["DeviceAirgap"] = 3] = "DeviceAirgap";
1841
2008
  })(exports.DeviceSettingsPage || (exports.DeviceSettingsPage = {}));
2009
+ exports.DeviceFactoryAck = void 0;
2010
+ (function (DeviceFactoryAck) {
2011
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
2012
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
2013
+ })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1842
2014
  exports.DeviceFirmwareTargetType = void 0;
1843
2015
  (function (DeviceFirmwareTargetType) {
1844
2016
  DeviceFirmwareTargetType[DeviceFirmwareTargetType["FW_MGMT_TARGET_INVALID"] = 0] = "FW_MGMT_TARGET_INVALID";
@@ -1867,11 +2039,6 @@ exports.DeviceFirmwareUpdateTaskStatus = void 0;
1867
2039
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY"] = 9] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY";
1868
2040
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS"] = 10] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS";
1869
2041
  })(exports.DeviceFirmwareUpdateTaskStatus || (exports.DeviceFirmwareUpdateTaskStatus = {}));
1870
- exports.DeviceFactoryAck = void 0;
1871
- (function (DeviceFactoryAck) {
1872
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1873
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1874
- })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1875
2042
  exports.DeviceType = void 0;
1876
2043
  (function (DeviceType) {
1877
2044
  DeviceType[DeviceType["CLASSIC1"] = 0] = "CLASSIC1";
@@ -1894,22 +2061,116 @@ exports.DeviceSEState = void 0;
1894
2061
  DeviceSEState[DeviceSEState["APP_FACTORY"] = 51] = "APP_FACTORY";
1895
2062
  DeviceSEState[DeviceSEState["APP"] = 85] = "APP";
1896
2063
  })(exports.DeviceSEState || (exports.DeviceSEState = {}));
1897
- exports.DevOnboardingStage = void 0;
1898
- (function (DevOnboardingStage) {
1899
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_UNKNOWN"] = 0] = "DEV_ONBOARDING_STAGE_UNKNOWN";
1900
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SAFETY_CHECK"] = 1] = "DEV_ONBOARDING_STAGE_SAFETY_CHECK";
1901
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_PERSONALIZATION"] = 2] = "DEV_ONBOARDING_STAGE_PERSONALIZATION";
1902
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SELECT_SETUP_METHOD"] = 3] = "DEV_ONBOARDING_STAGE_SELECT_SETUP_METHOD";
1903
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_NEW_DEVICE"] = 4] = "DEV_ONBOARDING_STAGE_NEW_DEVICE";
1904
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SELECT_RESTORE_METHOD"] = 5] = "DEV_ONBOARDING_STAGE_SELECT_RESTORE_METHOD";
1905
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_RESTORE_MNEMONIC"] = 6] = "DEV_ONBOARDING_STAGE_RESTORE_MNEMONIC";
1906
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_RESTORE_SEEDCARD"] = 7] = "DEV_ONBOARDING_STAGE_RESTORE_SEEDCARD";
1907
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_WALLET_READY"] = 8] = "DEV_ONBOARDING_STAGE_WALLET_READY";
1908
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP_PROMPT"] = 9] = "DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP_PROMPT";
1909
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SELECT_SEEDCARD_BACKUP_METHOD"] = 10] = "DEV_ONBOARDING_STAGE_SELECT_SEEDCARD_BACKUP_METHOD";
1910
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP"] = 11] = "DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP";
1911
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_DONE"] = 12] = "DEV_ONBOARDING_STAGE_DONE";
1912
- })(exports.DevOnboardingStage || (exports.DevOnboardingStage = {}));
2064
+ exports.DeviceSessionErrorCode = void 0;
2065
+ (function (DeviceSessionErrorCode) {
2066
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_None"] = 0] = "DeviceSessionError_None";
2067
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_UserCancelled"] = 1] = "DeviceSessionError_UserCancelled";
2068
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_InvalidSession"] = 2] = "DeviceSessionError_InvalidSession";
2069
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_AttachPinUnavailable"] = 3] = "DeviceSessionError_AttachPinUnavailable";
2070
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_PassphraseDisabled"] = 4] = "DeviceSessionError_PassphraseDisabled";
2071
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_Busy"] = 5] = "DeviceSessionError_Busy";
2072
+ })(exports.DeviceSessionErrorCode || (exports.DeviceSessionErrorCode = {}));
2073
+ exports.DeviceSessionSeedDomain = void 0;
2074
+ (function (DeviceSessionSeedDomain) {
2075
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Standard"] = 1] = "SeedDomain_Standard";
2076
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Cardano"] = 2] = "SeedDomain_Cardano";
2077
+ })(exports.DeviceSessionSeedDomain || (exports.DeviceSessionSeedDomain = {}));
2078
+ exports.DeviceSessionPinType = void 0;
2079
+ (function (DeviceSessionPinType) {
2080
+ DeviceSessionPinType[DeviceSessionPinType["Any"] = 1] = "Any";
2081
+ DeviceSessionPinType[DeviceSessionPinType["Main"] = 2] = "Main";
2082
+ DeviceSessionPinType[DeviceSessionPinType["AttachToPin"] = 3] = "AttachToPin";
2083
+ })(exports.DeviceSessionPinType || (exports.DeviceSessionPinType = {}));
2084
+ exports.DeviceSessionAskPin_FailureSubCodes = void 0;
2085
+ (function (DeviceSessionAskPin_FailureSubCodes) {
2086
+ DeviceSessionAskPin_FailureSubCodes[DeviceSessionAskPin_FailureSubCodes["UserCancel"] = 1] = "UserCancel";
2087
+ })(exports.DeviceSessionAskPin_FailureSubCodes || (exports.DeviceSessionAskPin_FailureSubCodes = {}));
2088
+ exports.OnboardingStep = void 0;
2089
+ (function (OnboardingStep) {
2090
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_UNKNOWN"] = 0] = "ONBOARDING_STEP_UNKNOWN";
2091
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_CHECKING"] = 1] = "ONBOARDING_STEP_CHECKING";
2092
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PERSONALIZATION"] = 2] = "ONBOARDING_STEP_PERSONALIZATION";
2093
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PIN"] = 3] = "ONBOARDING_STEP_PIN";
2094
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_SETUP"] = 4] = "ONBOARDING_STEP_SETUP";
2095
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_DONE"] = 5] = "ONBOARDING_STEP_DONE";
2096
+ })(exports.OnboardingStep || (exports.OnboardingStep = {}));
2097
+ exports.OnboardingPhase = void 0;
2098
+ (function (OnboardingPhase) {
2099
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_UNKNOWN"] = 0] = "ONBOARDING_PHASE_UNKNOWN";
2100
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SAFETY_CHECK"] = 1] = "ONBOARDING_PHASE_SAFETY_CHECK";
2101
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_PIN_SETUP"] = 2] = "ONBOARDING_PHASE_PIN_SETUP";
2102
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_FINGERPRINT_SETUP"] = 3] = "ONBOARDING_PHASE_FINGERPRINT_SETUP";
2103
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SETUP_CHOICE"] = 4] = "ONBOARDING_PHASE_SETUP_CHOICE";
2104
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_CREATE_START"] = 5] = "ONBOARDING_PHASE_WALLET_CREATE_START";
2105
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW"] = 6] = "ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW";
2106
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM"] = 7] = "ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM";
2107
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RESTORE_METHOD_CHOICE"] = 8] = "ONBOARDING_PHASE_RESTORE_METHOD_CHOICE";
2108
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE"] = 9] = "ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE";
2109
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_RESTORE"] = 10] = "ONBOARDING_PHASE_SEEDCARD_RESTORE";
2110
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_READY"] = 11] = "ONBOARDING_PHASE_WALLET_READY";
2111
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT"] = 12] = "ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT";
2112
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP"] = 13] = "ONBOARDING_PHASE_SEEDCARD_BACKUP";
2113
+ })(exports.OnboardingPhase || (exports.OnboardingPhase = {}));
2114
+ exports.OnboardingSetupKind = void 0;
2115
+ (function (OnboardingSetupKind) {
2116
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_UNKNOWN"] = 0] = "ONBOARDING_SETUP_KIND_UNKNOWN";
2117
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CHOICE"] = 1] = "ONBOARDING_SETUP_KIND_CHOICE";
2118
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CREATE"] = 2] = "ONBOARDING_SETUP_KIND_CREATE";
2119
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_RESTORE"] = 3] = "ONBOARDING_SETUP_KIND_RESTORE";
2120
+ })(exports.OnboardingSetupKind || (exports.OnboardingSetupKind = {}));
2121
+ exports.OnboardingSetupMethod = void 0;
2122
+ (function (OnboardingSetupMethod) {
2123
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_UNKNOWN"] = 0] = "ONBOARDING_SETUP_METHOD_UNKNOWN";
2124
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE"] = 1] = "ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE";
2125
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_SEEDCARD"] = 2] = "ONBOARDING_SETUP_METHOD_SEEDCARD";
2126
+ })(exports.OnboardingSetupMethod || (exports.OnboardingSetupMethod = {}));
2127
+ exports.ViewTipType = void 0;
2128
+ (function (ViewTipType) {
2129
+ ViewTipType[ViewTipType["Default"] = 0] = "Default";
2130
+ ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
2131
+ ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
2132
+ ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
2133
+ ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
2134
+ })(exports.ViewTipType || (exports.ViewTipType = {}));
2135
+ exports.ViewSignLayout = void 0;
2136
+ (function (ViewSignLayout) {
2137
+ ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
2138
+ ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
2139
+ ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
2140
+ ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
2141
+ ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
2142
+ ViewSignLayout[ViewSignLayout["LayoutEthApprove"] = 5] = "LayoutEthApprove";
2143
+ })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
2144
+ exports.ProtocolV2FailureType = void 0;
2145
+ (function (ProtocolV2FailureType) {
2146
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_InvalidMessage"] = 1] = "Failure_InvalidMessage";
2147
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_UndefinedError"] = 2] = "Failure_UndefinedError";
2148
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_UsageError"] = 3] = "Failure_UsageError";
2149
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_DataError"] = 4] = "Failure_DataError";
2150
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_ProcessError"] = 5] = "Failure_ProcessError";
2151
+ })(exports.ProtocolV2FailureType || (exports.ProtocolV2FailureType = {}));
2152
+ exports.Enum_ProtocolV2Capability = void 0;
2153
+ (function (Enum_ProtocolV2Capability) {
2154
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Bitcoin"] = 1] = "Capability_Bitcoin";
2155
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Bitcoin_like"] = 2] = "Capability_Bitcoin_like";
2156
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Binance"] = 3] = "Capability_Binance";
2157
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Cardano"] = 4] = "Capability_Cardano";
2158
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Crypto"] = 5] = "Capability_Crypto";
2159
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_EOS"] = 6] = "Capability_EOS";
2160
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Ethereum"] = 7] = "Capability_Ethereum";
2161
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Lisk"] = 8] = "Capability_Lisk";
2162
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Monero"] = 9] = "Capability_Monero";
2163
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_NEM"] = 10] = "Capability_NEM";
2164
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Ripple"] = 11] = "Capability_Ripple";
2165
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Stellar"] = 12] = "Capability_Stellar";
2166
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Tezos"] = 13] = "Capability_Tezos";
2167
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_U2F"] = 14] = "Capability_U2F";
2168
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Shamir"] = 15] = "Capability_Shamir";
2169
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_ShamirGroups"] = 16] = "Capability_ShamirGroups";
2170
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_PassphraseEntry"] = 17] = "Capability_PassphraseEntry";
2171
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_AttachToPin"] = 18] = "Capability_AttachToPin";
2172
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_EthereumTypedData"] = 1000] = "Capability_EthereumTypedData";
2173
+ })(exports.Enum_ProtocolV2Capability || (exports.Enum_ProtocolV2Capability = {}));
1913
2174
 
1914
2175
  var messages = /*#__PURE__*/Object.freeze({
1915
2176
  __proto__: null,
@@ -1942,6 +2203,9 @@ var messages = /*#__PURE__*/Object.freeze({
1942
2203
  get EthereumGnosisSafeTxOperation () { return exports.EthereumGnosisSafeTxOperation; },
1943
2204
  get EthereumDataTypeOneKey () { return exports.EthereumDataTypeOneKey; },
1944
2205
  get EthereumDataType () { return exports.EthereumDataType; },
2206
+ get Enum_KaspaInputScriptType () { return exports.Enum_KaspaInputScriptType; },
2207
+ get Enum_KaspaOutputScriptType () { return exports.Enum_KaspaOutputScriptType; },
2208
+ get Enum_KaspaRequestType () { return exports.Enum_KaspaRequestType; },
1945
2209
  get Enum_BackupType () { return exports.Enum_BackupType; },
1946
2210
  get Enum_SafetyCheckLevel () { return exports.Enum_SafetyCheckLevel; },
1947
2211
  get OneKeyDeviceType () { return exports.OneKeyDeviceType; },
@@ -1973,22 +2237,114 @@ var messages = /*#__PURE__*/Object.freeze({
1973
2237
  get TronResourceCode () { return exports.TronResourceCode; },
1974
2238
  get TronMessageType () { return exports.TronMessageType; },
1975
2239
  get CommandFlags () { return exports.CommandFlags; },
1976
- get WallpaperTarget () { return exports.WallpaperTarget; },
1977
2240
  get MoneroNetworkType () { return exports.MoneroNetworkType; },
1978
- get ViewTipType () { return exports.ViewTipType; },
1979
- get ViewSignLayout () { return exports.ViewSignLayout; },
2241
+ get UiAnimationType () { return exports.UiAnimationType; },
2242
+ get UiAnimationCommand () { return exports.UiAnimationCommand; },
1980
2243
  get DeviceErrorCode () { return exports.DeviceErrorCode; },
1981
2244
  get DeviceRebootType () { return exports.DeviceRebootType; },
1982
2245
  get DeviceSettingsPage () { return exports.DeviceSettingsPage; },
2246
+ get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1983
2247
  get DeviceFirmwareTargetType () { return exports.DeviceFirmwareTargetType; },
1984
2248
  get DeviceFirmwareUpdateTaskStatus () { return exports.DeviceFirmwareUpdateTaskStatus; },
1985
- get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1986
2249
  get DeviceType () { return exports.DeviceType; },
1987
2250
  get DeviceSeType () { return exports.DeviceSeType; },
1988
2251
  get DeviceSEState () { return exports.DeviceSEState; },
1989
- get DevOnboardingStage () { return exports.DevOnboardingStage; }
2252
+ get DeviceSessionErrorCode () { return exports.DeviceSessionErrorCode; },
2253
+ get DeviceSessionSeedDomain () { return exports.DeviceSessionSeedDomain; },
2254
+ get DeviceSessionPinType () { return exports.DeviceSessionPinType; },
2255
+ get DeviceSessionAskPin_FailureSubCodes () { return exports.DeviceSessionAskPin_FailureSubCodes; },
2256
+ get OnboardingStep () { return exports.OnboardingStep; },
2257
+ get OnboardingPhase () { return exports.OnboardingPhase; },
2258
+ get OnboardingSetupKind () { return exports.OnboardingSetupKind; },
2259
+ get OnboardingSetupMethod () { return exports.OnboardingSetupMethod; },
2260
+ get ViewTipType () { return exports.ViewTipType; },
2261
+ get ViewSignLayout () { return exports.ViewSignLayout; },
2262
+ get ProtocolV2FailureType () { return exports.ProtocolV2FailureType; },
2263
+ get Enum_ProtocolV2Capability () { return exports.Enum_ProtocolV2Capability; }
1990
2264
  });
1991
2265
 
2266
+ const REDACTED = '[REDACTED]';
2267
+ const SENSITIVE_LOG_KEYS = new Set([
2268
+ 'accesstoken',
2269
+ 'address',
2270
+ 'apikey',
2271
+ 'connectid',
2272
+ 'devicestate',
2273
+ 'deviceid',
2274
+ 'entropy',
2275
+ 'expectedpassphrasestate',
2276
+ 'mnemonic',
2277
+ 'passphrase',
2278
+ 'passphrasestate',
2279
+ 'password',
2280
+ 'pin',
2281
+ 'privatekey',
2282
+ 'publickey',
2283
+ 'seed',
2284
+ 'serialnumber',
2285
+ 'session',
2286
+ 'sessionid',
2287
+ 'signature',
2288
+ 'token',
2289
+ 'uuid',
2290
+ 'walletsessionid',
2291
+ 'xprv',
2292
+ 'xpub',
2293
+ ]);
2294
+ const normalizeLogKey = (key) => key.replace(/[_-]/g, '').toLowerCase();
2295
+ const isSensitiveLogKey = (key) => {
2296
+ const normalizedKey = normalizeLogKey(key);
2297
+ return (SENSITIVE_LOG_KEYS.has(normalizedKey) ||
2298
+ normalizedKey.endsWith('address') ||
2299
+ normalizedKey.endsWith('privatekey') ||
2300
+ normalizedKey.endsWith('publickey') ||
2301
+ normalizedKey.endsWith('signature'));
2302
+ };
2303
+ const isSigningMessage = (messageName) => Boolean(messageName && /(?:sign|txack|transaction)/i.test(messageName));
2304
+ const redactLogValue = (value, seen) => {
2305
+ if (ArrayBuffer.isView(value)) {
2306
+ return `[BINARY:${value.byteLength}]`;
2307
+ }
2308
+ if (value instanceof ArrayBuffer) {
2309
+ return `[BINARY:${value.byteLength}]`;
2310
+ }
2311
+ if (Array.isArray(value)) {
2312
+ return value.map(item => redactLogValue(item, seen));
2313
+ }
2314
+ if (!value || typeof value !== 'object') {
2315
+ return value;
2316
+ }
2317
+ if (seen.has(value)) {
2318
+ return '[CIRCULAR]';
2319
+ }
2320
+ seen.add(value);
2321
+ const redacted = Object.fromEntries(Object.entries(value).map(([key, item]) => [
2322
+ key,
2323
+ isSensitiveLogKey(key) && item !== null && item !== undefined
2324
+ ? REDACTED
2325
+ : redactLogValue(item, seen),
2326
+ ]));
2327
+ seen.delete(value);
2328
+ return redacted;
2329
+ };
2330
+ function getSafeTransportLogPayload(value, messageName) {
2331
+ if (isSigningMessage(messageName)) {
2332
+ return REDACTED;
2333
+ }
2334
+ return redactLogValue(value, new WeakSet());
2335
+ }
2336
+ function createTransportCallLog(name, protocol, data) {
2337
+ return {
2338
+ name,
2339
+ protocol,
2340
+ request: getSafeTransportLogPayload(data, name),
2341
+ };
2342
+ }
2343
+ const HIGH_VOLUME_CALLS = new Set(['FileWrite', 'FilesystemFileWrite', 'EmmcFileWrite']);
2344
+ function shouldSuppressHighVolumeCallLog(name) {
2345
+ return HIGH_VOLUME_CALLS.has(name);
2346
+ }
2347
+
1992
2348
  protobuf__namespace.util.Long = Long__default["default"];
1993
2349
  protobuf__namespace.configure();
1994
2350
  var index = {
@@ -2025,29 +2381,38 @@ exports.PROTOCOL_V1_REPORT_ID = PROTOCOL_V1_REPORT_ID;
2025
2381
  exports.PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_USB_PACKET_SIZE;
2026
2382
  exports.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
2027
2383
  exports.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE;
2384
+ exports.PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE;
2028
2385
  exports.PROTOCOL_V2_BLE_FRAME_MAX_BYTES = PROTOCOL_V2_BLE_FRAME_MAX_BYTES;
2029
2386
  exports.PROTOCOL_V2_CHANNEL_BLE_UART = PROTOCOL_V2_CHANNEL_BLE_UART;
2030
2387
  exports.PROTOCOL_V2_CHANNEL_SOCKET = PROTOCOL_V2_CHANNEL_SOCKET;
2031
2388
  exports.PROTOCOL_V2_CHANNEL_USB = PROTOCOL_V2_CHANNEL_USB;
2389
+ exports.PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
2032
2390
  exports.PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_FILE_CHUNK_SIZE;
2033
2391
  exports.PROTOCOL_V2_FRAME_MAX_BYTES = PROTOCOL_V2_FRAME_MAX_BYTES;
2034
2392
  exports.PROTOCOL_V2_PACKET_SRC_COMMAND = PROTOCOL_V2_PACKET_SRC_COMMAND;
2035
2393
  exports.PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = PROTOCOL_V2_SYS_MESSAGE_THRESHOLD;
2036
2394
  exports.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
2037
- exports.PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS;
2038
2395
  exports.ProtocolV1 = ProtocolV1;
2039
2396
  exports.ProtocolV2 = ProtocolV2;
2040
2397
  exports.ProtocolV2FrameAssembler = ProtocolV2FrameAssembler;
2398
+ exports.ProtocolV2LinkError = ProtocolV2LinkError;
2041
2399
  exports.ProtocolV2LinkManager = ProtocolV2LinkManager;
2042
2400
  exports.ProtocolV2SequenceCursor = ProtocolV2SequenceCursor;
2043
2401
  exports.ProtocolV2Session = ProtocolV2Session;
2044
2402
  exports.ProtocolV2UsbTransportBase = ProtocolV2UsbTransportBase;
2403
+ exports.TRANSPORT_EVENT = TRANSPORT_EVENT;
2045
2404
  exports.bytesToHex = bytesToHex;
2046
2405
  exports.concatUint8Arrays = concatUint8Arrays;
2406
+ exports.createTransportCallLog = createTransportCallLog;
2047
2407
  exports["default"] = index;
2048
2408
  exports.getErrorMessage = getErrorMessage;
2409
+ exports.getSafeTransportLogPayload = getSafeTransportLogPayload;
2049
2410
  exports.hexToBytes = hexToBytes;
2411
+ exports.isProtocolV2HighThroughputCall = isProtocolV2HighThroughputCall;
2412
+ exports.isProtocolV2LinkError = isProtocolV2LinkError;
2050
2413
  exports.probeProtocolV2 = probeProtocolV2;
2051
2414
  exports.protocolV1 = index$1;
2052
2415
  exports.protocolV2 = protocolV2Codec;
2416
+ exports.shouldSuppressHighVolumeCallLog = shouldSuppressHighVolumeCallLog;
2053
2417
  exports.withProtocolTimeout = withProtocolTimeout;
2418
+ exports.writeProtocolV2BleFrame = writeProtocolV2BleFrame;