@onekeyfe/hd-transport 1.2.0-alpha.13 → 1.2.0-alpha.131

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 (59) hide show
  1. package/__tests__/messages.test.js +144 -4
  2. package/__tests__/protocol-v2-ble-frame-writer.test.js +119 -0
  3. package/__tests__/protocol-v2-link-manager.test.js +176 -9
  4. package/__tests__/protocol-v2-usb-transport-base.test.js +36 -2
  5. package/__tests__/protocol-v2.test.js +540 -108
  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 +645 -217
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +679 -153
  12. package/dist/protocols/index.d.ts +17 -1
  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 +11 -0
  17. package/dist/protocols/v2/decode.d.ts.map +1 -1
  18. package/dist/protocols/v2/errors.d.ts +16 -0
  19. package/dist/protocols/v2/errors.d.ts.map +1 -0
  20. package/dist/protocols/v2/frame-assembler.d.ts.map +1 -1
  21. package/dist/protocols/v2/index.d.ts +2 -0
  22. package/dist/protocols/v2/index.d.ts.map +1 -1
  23. package/dist/protocols/v2/link-manager.d.ts +5 -0
  24. package/dist/protocols/v2/link-manager.d.ts.map +1 -1
  25. package/dist/protocols/v2/session.d.ts +14 -4
  26. package/dist/protocols/v2/session.d.ts.map +1 -1
  27. package/dist/protocols/v2/usb-transport-base.d.ts +2 -0
  28. package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -1
  29. package/dist/serialization/protobuf/decode.d.ts.map +1 -1
  30. package/dist/serialization/protobuf/encode.d.ts.map +1 -1
  31. package/dist/types/messages.d.ts +301 -156
  32. package/dist/types/messages.d.ts.map +1 -1
  33. package/dist/types/transport.d.ts +21 -3
  34. package/dist/types/transport.d.ts.map +1 -1
  35. package/dist/utils/transportLog.d.ts +9 -0
  36. package/dist/utils/transportLog.d.ts.map +1 -0
  37. package/messages-protocol-v2.json +523 -449
  38. package/package.json +2 -2
  39. package/scripts/protobuf-build.sh +112 -32
  40. package/scripts/protobuf-patches/index.js +1 -0
  41. package/scripts/protobuf-types.js +10 -1
  42. package/src/constants.ts +30 -16
  43. package/src/index.ts +5 -1
  44. package/src/protocols/index.ts +114 -3
  45. package/src/protocols/v2/ble-frame-writer.ts +77 -0
  46. package/src/protocols/v2/crc8.ts +1 -1
  47. package/src/protocols/v2/decode.ts +49 -12
  48. package/src/protocols/v2/encode.ts +1 -1
  49. package/src/protocols/v2/errors.ts +54 -0
  50. package/src/protocols/v2/frame-assembler.ts +6 -4
  51. package/src/protocols/v2/index.ts +2 -0
  52. package/src/protocols/v2/link-manager.ts +65 -5
  53. package/src/protocols/v2/session.ts +224 -80
  54. package/src/protocols/v2/usb-transport-base.ts +42 -10
  55. package/src/serialization/protobuf/decode.ts +4 -1
  56. package/src/serialization/protobuf/encode.ts +5 -1
  57. package/src/types/messages.ts +375 -198
  58. package/src/types/transport.ts +30 -3
  59. package/src/utils/transportLog.ts +102 -0
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;
@@ -425,7 +430,7 @@ function encodeFrame(payload, packetSrc, router, seq) {
425
430
  const payloadLen = payload ? payload.length : 0;
426
431
  const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
427
432
  if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
428
- throw new Error(`Protocol V2 frame too large: ${frameLen}`);
433
+ throw new Error(`Protocol V2 frame too large: ${frameLen} > ${PROTOCOL_V2_FRAME_MAX_BYTES}`);
429
434
  }
430
435
  const frame = new Uint8Array(frameLen);
431
436
  frame[0] = PROTO_HEAD_SOF;
@@ -450,7 +455,7 @@ function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, seq) {
450
455
  return encodeFrame(payload, packetSrc, router, seq);
451
456
  }
452
457
 
453
- function validateFrame(data) {
458
+ function inspectFrameHeader(data) {
454
459
  if (data.length < PROTO_HEAD_CRC_SIZE) {
455
460
  throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
456
461
  }
@@ -458,8 +463,8 @@ function validateFrame(data) {
458
463
  throw new Error(`Invalid SOF byte: expected 0x5A, got 0x${data[0].toString(16).padStart(2, '0')}`);
459
464
  }
460
465
  const frameLen = data[1] + data[2] * 256;
461
- if (data.length < frameLen) {
462
- 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}`);
463
468
  }
464
469
  const expectedHeaderCrc = crc8(data, 3);
465
470
  if (data[3] !== expectedHeaderCrc) {
@@ -473,30 +478,66 @@ function validateFrame(data) {
473
478
  .toString(16)
474
479
  .padStart(2, '0')}, got 0x${data[frameLen - 1].toString(16).padStart(2, '0')}`);
475
480
  }
476
- 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
+ };
477
494
  }
478
495
  function isAckFrame(data) {
479
496
  if (data.length < 6 || (data[5] & 0x03) !== PROTO_DATA_TYPE_ACK) {
480
497
  return false;
481
498
  }
482
- const frameLen = validateFrame(data);
483
- if (frameLen !== PROTO_HEAD_CRC_SIZE) {
484
- 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}`);
485
502
  }
486
503
  return true;
487
504
  }
488
505
  function decodeFrame(data) {
489
- const frameLen = validateFrame(data);
490
- const seq = data[6];
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
+ }
491
510
  const payloadData = data.slice(7, frameLen - 1);
492
511
  if (payloadData.length < 2) {
493
512
  throw new Error(`Protocol V2 payload too short (need >=2 bytes for messageTypeId)`);
494
513
  }
495
514
  const messageTypeId = payloadData[0] + payloadData[1] * 256;
496
515
  const pbPayload = payloadData.slice(2);
497
- return { messageTypeId, pbPayload, seq };
516
+ return { messageTypeId, pbPayload, seq, router, packetSrc, dataType };
498
517
  }
499
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
+ }
526
+ }
527
+ const isProtocolV2LinkError = (error) => error instanceof ProtocolV2LinkError;
528
+ const createProtocolV2LinkDisabledError = (failureCode, firmwareMessage) => Object.assign(new Error(firmwareMessage), {
529
+ name: 'ProtocolV2LinkDisabledError',
530
+ failureCode,
531
+ firmwareMessage,
532
+ });
533
+ const isProtocolV2LinkDisabledError = (error) => error instanceof Error &&
534
+ error.name === 'ProtocolV2LinkDisabledError' &&
535
+ 'failureCode' in error &&
536
+ 'firmwareMessage' in error;
537
+ const isProtocolV2LinkDisabledFailure = (failureCode, firmwareMessage) => (failureCode === 'Failure_ProcessError' || failureCode === 5) &&
538
+ typeof firmwareMessage === 'string' &&
539
+ firmwareMessage.trim().toLowerCase() === 'link disabled';
540
+
500
541
  function concatUint8Arrays(arrays) {
501
542
  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
502
543
  const result = new Uint8Array(totalLength);
@@ -540,23 +581,23 @@ class ProtocolV2FrameAssembler {
540
581
  return undefined;
541
582
  if (this.buffer[0] !== PROTO_HEAD_SOF) {
542
583
  this.reset();
543
- throw new Error('Invalid Protocol V2 SOF');
584
+ throw new ProtocolV2LinkError('frame', 'Invalid Protocol V2 SOF');
544
585
  }
545
586
  const expectedLen = this.buffer[1] + this.buffer[2] * 256;
546
587
  if (expectedLen < PROTO_HEAD_CRC_SIZE) {
547
588
  this.reset();
548
- throw new Error(`Protocol V2 frame length too small: ${expectedLen}`);
589
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame length too small: ${expectedLen}`);
549
590
  }
550
591
  if (expectedLen > this.maxFrameBytes) {
551
592
  this.reset();
552
- throw new Error(`Protocol V2 frame too large: ${expectedLen}`);
593
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame too large: ${expectedLen}`);
553
594
  }
554
595
  if (this.buffer.length < PROTO_PRE_HEAD_SIZE)
555
596
  return undefined;
556
597
  const expectedHeaderCrc = crc8(this.buffer, 3);
557
598
  if (this.buffer[3] !== expectedHeaderCrc) {
558
599
  this.reset();
559
- throw new Error(`Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
600
+ throw new ProtocolV2LinkError('frame', `Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
560
601
  .toString(16)
561
602
  .padStart(2, '0')}`);
562
603
  }
@@ -568,6 +609,51 @@ class ProtocolV2FrameAssembler {
568
609
  }
569
610
  }
570
611
 
612
+ const defaultWait = (timeoutMs) => new Promise(resolve => {
613
+ setTimeout(resolve, timeoutMs);
614
+ });
615
+ function writeProtocolV2BleFrame({ frame, packetCapacity, writePacket, assertActive, signal, abortMessage = 'Protocol V2 BLE write aborted', initialDelayMs = 0, burstSize, burstPauseMs = 0, flushDelayMs = 0, wait = defaultWait, }) {
616
+ return __awaiter(this, void 0, void 0, function* () {
617
+ if (!Number.isInteger(packetCapacity) || packetCapacity <= 0) {
618
+ throw new Error('Protocol V2 BLE packet capacity must be a positive integer');
619
+ }
620
+ if (burstSize !== undefined && (!Number.isInteger(burstSize) || burstSize <= 0)) {
621
+ throw new Error('Protocol V2 BLE burst size must be a positive integer');
622
+ }
623
+ const assertWritable = () => {
624
+ assertActive === null || assertActive === void 0 ? void 0 : assertActive();
625
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
626
+ throw new Error(abortMessage);
627
+ }
628
+ };
629
+ if (frame.length > 0 && initialDelayMs > 0) {
630
+ assertWritable();
631
+ yield wait(initialDelayMs);
632
+ assertWritable();
633
+ }
634
+ let packetsWritten = 0;
635
+ for (let offset = 0; offset < frame.length; offset += packetCapacity) {
636
+ assertWritable();
637
+ const packet = frame.slice(offset, offset + packetCapacity);
638
+ yield writePacket(packet, packetsWritten);
639
+ packetsWritten += 1;
640
+ assertWritable();
641
+ const hasMorePackets = offset + packetCapacity < frame.length;
642
+ if (hasMorePackets &&
643
+ burstSize !== undefined &&
644
+ packetsWritten % burstSize === 0 &&
645
+ burstPauseMs > 0) {
646
+ yield wait(burstPauseMs);
647
+ assertWritable();
648
+ }
649
+ }
650
+ if (burstSize !== undefined && packetsWritten > burstSize && flushDelayMs > 0) {
651
+ yield wait(flushDelayMs);
652
+ assertWritable();
653
+ }
654
+ });
655
+ }
656
+
571
657
  var protocolV2Codec = /*#__PURE__*/Object.freeze({
572
658
  __proto__: null,
573
659
  PROTO_HEAD_SOF: PROTO_HEAD_SOF,
@@ -582,13 +668,95 @@ var protocolV2Codec = /*#__PURE__*/Object.freeze({
582
668
  nextProtoSeq: nextProtoSeq,
583
669
  encodeFrame: encodeFrame,
584
670
  encodeProtobufFrame: encodeProtobufFrame,
671
+ inspectFrameHeader: inspectFrameHeader,
585
672
  isAckFrame: isAckFrame,
586
673
  decodeFrame: decodeFrame,
674
+ ProtocolV2LinkError: ProtocolV2LinkError,
675
+ isProtocolV2LinkError: isProtocolV2LinkError,
676
+ createProtocolV2LinkDisabledError: createProtocolV2LinkDisabledError,
677
+ isProtocolV2LinkDisabledError: isProtocolV2LinkDisabledError,
678
+ isProtocolV2LinkDisabledFailure: isProtocolV2LinkDisabledFailure,
587
679
  concatUint8Arrays: concatUint8Arrays,
588
- ProtocolV2FrameAssembler: ProtocolV2FrameAssembler
680
+ ProtocolV2FrameAssembler: ProtocolV2FrameAssembler,
681
+ writeProtocolV2BleFrame: writeProtocolV2BleFrame
589
682
  });
590
683
 
591
684
  const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
685
+ const LEGACY_PROTOCOL_V2_PROTOCOL_INFO = protobuf.Type.fromJSON('LegacyProtocolInfo', {
686
+ fields: {
687
+ version: {
688
+ rule: 'required',
689
+ type: 'uint32',
690
+ id: 1,
691
+ },
692
+ supported_messages: {
693
+ rule: 'repeated',
694
+ type: 'uint32',
695
+ id: 2,
696
+ options: {
697
+ packed: false,
698
+ },
699
+ },
700
+ protobuf_definition: {
701
+ type: 'string',
702
+ id: 3,
703
+ },
704
+ },
705
+ });
706
+ const decodeLegacyProtocolV2ProtocolInfo = (pbPayload) => {
707
+ var _a;
708
+ const byteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
709
+ const legacy = decode(LEGACY_PROTOCOL_V2_PROTOCOL_INFO, byteBuffer);
710
+ return {
711
+ version: legacy.version,
712
+ build_fingerprint: '',
713
+ supported_messages: (_a = legacy.supported_messages) !== null && _a !== void 0 ? _a : [],
714
+ protobuf_definition: null,
715
+ };
716
+ };
717
+ const isLegacyProtocolV2ProtocolInfoWireLayout = (pbPayload) => {
718
+ const reader = protobuf.Reader.create(pbPayload);
719
+ let hasVersion = false;
720
+ try {
721
+ while (reader.pos < reader.len) {
722
+ const tag = reader.uint32();
723
+ const fieldNumber = tag >>> 3;
724
+ const wireType = tag & 0x07;
725
+ if (fieldNumber === 1) {
726
+ if (wireType !== 0)
727
+ return false;
728
+ hasVersion = true;
729
+ }
730
+ else if (fieldNumber === 2) {
731
+ if (wireType !== 0)
732
+ return false;
733
+ }
734
+ else if (fieldNumber === 3) {
735
+ if (wireType !== 2)
736
+ return false;
737
+ }
738
+ else {
739
+ return false;
740
+ }
741
+ reader.skipType(wireType);
742
+ }
743
+ }
744
+ catch (_a) {
745
+ return false;
746
+ }
747
+ return hasVersion;
748
+ };
749
+ const tryDecodeLegacyProtocolV2ProtocolInfo = (messageName, pbPayload) => {
750
+ if (messageName !== 'ProtocolInfo' || !isLegacyProtocolV2ProtocolInfoWireLayout(pbPayload)) {
751
+ return undefined;
752
+ }
753
+ try {
754
+ return decodeLegacyProtocolV2ProtocolInfo(pbPayload);
755
+ }
756
+ catch (_a) {
757
+ return undefined;
758
+ }
759
+ };
592
760
  const resolveProtocolV2EncodeSchema = (name, schemas) => {
593
761
  try {
594
762
  schemas.protocolV2.lookupType(name);
@@ -634,14 +802,18 @@ const ProtocolV1 = {
634
802
  };
635
803
  const ProtocolV2 = {
636
804
  isAckFrame,
805
+ inspectFrameHeader,
637
806
  inspectFrame(schemas, frame) {
638
- const { messageTypeId, pbPayload, seq } = decodeFrame(frame);
807
+ const { messageTypeId, pbPayload, seq, router, packetSrc, dataType } = decodeFrame(frame);
639
808
  const { messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
640
809
  return {
641
810
  messageName,
642
811
  messageTypeId,
643
812
  pbPayload,
644
813
  seq,
814
+ router,
815
+ packetSrc,
816
+ dataType,
645
817
  type: messageName,
646
818
  };
647
819
  },
@@ -658,7 +830,28 @@ const ProtocolV2 = {
658
830
  const { messageTypeId, pbPayload, seq, messageName } = this.inspectFrame(schemas, frame);
659
831
  const { Message } = createProtocolV2MessageFromType(messageTypeId, schemas);
660
832
  const rxByteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
661
- const message = decode(Message, rxByteBuffer);
833
+ let message;
834
+ try {
835
+ message = decode(Message, rxByteBuffer);
836
+ }
837
+ catch (cause) {
838
+ const legacyProtocolInfo = tryDecodeLegacyProtocolV2ProtocolInfo(messageName, pbPayload);
839
+ if (legacyProtocolInfo) {
840
+ return {
841
+ message: legacyProtocolInfo,
842
+ messageName,
843
+ messageTypeId,
844
+ pbPayload,
845
+ seq,
846
+ type: messageName,
847
+ };
848
+ }
849
+ const error = new Error(`Protocol V2 protobuf decode failed for "${messageName}" ` +
850
+ `(${messageTypeId}, ${pbPayload.length}-byte payload); ` +
851
+ 'the payload is malformed or incompatible with the active SDK schema.');
852
+ error.cause = cause;
853
+ throw error;
854
+ }
662
855
  return {
663
856
  message,
664
857
  messageName,
@@ -807,14 +1000,27 @@ function bytesToHex(bytes) {
807
1000
  .map(b => b.toString(16).padStart(2, '0'))
808
1001
  .join('');
809
1002
  }
810
- const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
1003
+ const REDUCED_DEBUG_PROTOCOL_V2_CALLS = new Set([
811
1004
  ...LogBlockCommand,
812
1005
  'FilesystemFileRead',
813
1006
  'FileRead',
814
1007
  'EmmcFileRead',
815
1008
  ]);
816
1009
  function shouldReduceProtocolV2Debug(name) {
817
- return HIGH_VOLUME_PROTOCOL_V2_CALLS.has(name);
1010
+ return REDUCED_DEBUG_PROTOCOL_V2_CALLS.has(name);
1011
+ }
1012
+ const HIGH_THROUGHPUT_PROTOCOL_V2_CALLS = new Set([
1013
+ 'FilesystemFileWrite',
1014
+ 'FileWrite',
1015
+ 'EmmcFileWrite',
1016
+ 'FirmwareUpload',
1017
+ 'ResourceAck',
1018
+ 'FilesystemFileRead',
1019
+ 'FileRead',
1020
+ 'EmmcFileRead',
1021
+ ]);
1022
+ function isProtocolV2HighThroughputCall(name) {
1023
+ return HIGH_THROUGHPUT_PROTOCOL_V2_CALLS.has(name);
818
1024
  }
819
1025
  const COMMON_TERMINAL_RESPONSE_TYPES = new Set([
820
1026
  'Failure',
@@ -841,11 +1047,12 @@ function getErrorMessage(error) {
841
1047
  }
842
1048
  return String(error);
843
1049
  }
844
- function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout) {
1050
+ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout, abortSignal) {
845
1051
  return __awaiter(this, void 0, void 0, function* () {
846
1052
  if (!timeoutMs)
847
1053
  return promise;
848
1054
  let timer;
1055
+ let abortHandler;
849
1056
  try {
850
1057
  return yield Promise.race([
851
1058
  promise,
@@ -855,19 +1062,37 @@ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout)
855
1062
  reject(createTimeoutError());
856
1063
  }, timeoutMs);
857
1064
  }),
1065
+ ...(abortSignal
1066
+ ? [
1067
+ new Promise((_, reject) => {
1068
+ abortHandler = () => {
1069
+ reject(new Error('Protocol V2 operation aborted'));
1070
+ };
1071
+ if (abortSignal.aborted) {
1072
+ abortHandler();
1073
+ }
1074
+ else {
1075
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
1076
+ }
1077
+ }),
1078
+ ]
1079
+ : []),
858
1080
  ]);
859
1081
  }
860
1082
  finally {
861
1083
  if (timer)
862
1084
  clearTimeout(timer);
1085
+ if (abortHandler) {
1086
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener('abort', abortHandler);
1087
+ }
863
1088
  }
864
1089
  });
865
1090
  }
866
- const PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = 0;
867
1091
  class ProtocolV2Session {
868
1092
  constructor(options) {
869
1093
  var _a;
870
1094
  this.pendingCall = Promise.resolve();
1095
+ this.pendingWrite = Promise.resolve();
871
1096
  this.options = options;
872
1097
  this.sequenceCursor = (_a = options.sequenceCursor) !== null && _a !== void 0 ? _a : new ProtocolV2SequenceCursor();
873
1098
  }
@@ -877,100 +1102,161 @@ class ProtocolV2Session {
877
1102
  this.pendingCall = result.catch(() => undefined);
878
1103
  return result;
879
1104
  }
1105
+ sendFlowControl(name, data) {
1106
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, writeFrame, generation = 0, } = this.options;
1107
+ const abortController = new AbortController();
1108
+ const context = {
1109
+ messageName: name,
1110
+ highThroughput: false,
1111
+ generation,
1112
+ signal: abortController.signal,
1113
+ };
1114
+ const protoSeq = this.sequenceCursor.next();
1115
+ const frame = ProtocolV2.encodeFrame(schemas, name, data, {
1116
+ packetSrc,
1117
+ router,
1118
+ seq: protoSeq,
1119
+ });
1120
+ if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
1121
+ return Promise.reject(new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`));
1122
+ }
1123
+ return this.serializeWrite(() => writeFrame(frame, context)).then(() => ({
1124
+ type: 'WriteCompleted',
1125
+ message: {},
1126
+ }));
1127
+ }
1128
+ serializeWrite(write) {
1129
+ const result = this.pendingWrite.then(write, write);
1130
+ this.pendingWrite = result.catch(() => undefined);
1131
+ return result;
1132
+ }
880
1133
  executeCall(name, data, callOptions) {
881
- var _a;
882
- return __awaiter(this, void 0, void 0, function* () {
883
- const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
884
- const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
885
- const callContext = {
886
- messageName: name,
887
- timeoutMs: callOptions.timeoutMs,
888
- highVolume: shouldReduceDebug,
889
- generation,
890
- };
891
- yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(callContext));
1134
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
1135
+ const timeoutMs = callOptions.timeoutMs && callOptions.timeoutMs > 0
1136
+ ? callOptions.timeoutMs
1137
+ : PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1138
+ const abortController = new AbortController();
1139
+ const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
1140
+ const baseCallContext = Object.assign(Object.assign({ messageName: name, timeoutMs, highThroughput: isProtocolV2HighThroughputCall(name) }, (callOptions.writeWithResponse === undefined
1141
+ ? {}
1142
+ : { writeWithResponse: callOptions.writeWithResponse })), { generation, signal: abortController.signal });
1143
+ const runCall = () => __awaiter(this, void 0, void 0, function* () {
1144
+ var _a, _b, _c, _d, _e, _f;
1145
+ yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(baseCallContext));
892
1146
  const protoSeq = this.sequenceCursor.next();
893
1147
  const frame = ProtocolV2.encodeFrame(schemas, name, data, {
894
1148
  packetSrc,
895
1149
  router,
896
1150
  seq: protoSeq,
897
1151
  });
898
- const txMetadata = ProtocolV2.inspectFrame(schemas, frame);
899
1152
  if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
900
1153
  throw new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`);
901
1154
  }
902
- if (!shouldReduceDebug) {
903
- (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] TX`, {
904
- method: name,
905
- type: name,
906
- typeId: txMetadata.messageTypeId,
907
- seq: txMetadata.seq,
908
- bytes: frame.length,
1155
+ const writeStartedAt = Date.now();
1156
+ yield this.serializeWrite(() => writeFrame(frame, baseCallContext));
1157
+ try {
1158
+ (_a = callOptions.onWriteCompleted) === null || _a === void 0 ? void 0 : _a.call(callOptions, {
1159
+ elapsedMs: Math.max(Date.now() - writeStartedAt, 0),
1160
+ frameBytes: frame.byteLength,
909
1161
  });
910
1162
  }
911
- 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}`));
912
- const cancellation = { cancelled: false };
913
- const readResponse = () => __awaiter(this, void 0, void 0, function* () {
914
- var _b, _c, _d, _e, _f;
915
- while (!cancellation.cancelled) {
916
- const rxFrame = yield readFrame(callContext);
917
- if (cancellation.cancelled) {
918
- break;
1163
+ catch (error) {
1164
+ (_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)}`);
1165
+ }
1166
+ if (callOptions.returnAfterWrite) {
1167
+ return { type: 'WriteCompleted', message: {} };
1168
+ }
1169
+ while (!abortController.signal.aborted) {
1170
+ const rxFrame = yield readFrame(baseCallContext);
1171
+ if (abortController.signal.aborted)
1172
+ break;
1173
+ let header;
1174
+ try {
1175
+ header = ProtocolV2.inspectFrameHeader(rxFrame);
1176
+ }
1177
+ catch (cause) {
1178
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame validation failed: ${getErrorMessage(cause)}`, cause);
1179
+ }
1180
+ if (header.router !== router) {
1181
+ throw new ProtocolV2LinkError('router', `Protocol V2 router mismatch: expected ${router}, got ${header.router}`);
1182
+ }
1183
+ if (header.packetSrc !== packetSrc) {
1184
+ throw new ProtocolV2LinkError('packet-source', `Protocol V2 packet source mismatch: expected ${packetSrc}, got ${header.packetSrc}`);
1185
+ }
1186
+ let isAck;
1187
+ try {
1188
+ isAck = ProtocolV2.isAckFrame(rxFrame);
1189
+ }
1190
+ catch (cause) {
1191
+ throw new ProtocolV2LinkError('frame', `Protocol V2 ACK validation failed: ${getErrorMessage(cause)}`, cause);
1192
+ }
1193
+ if (isAck) {
1194
+ if (header.seq !== protoSeq) {
1195
+ throw new ProtocolV2LinkError('ack-sequence', `Protocol V2 ACK sequence mismatch: expected ${protoSeq}, got ${header.seq}`);
1196
+ }
1197
+ }
1198
+ else {
1199
+ let decoded;
1200
+ try {
1201
+ decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
1202
+ }
1203
+ catch (cause) {
1204
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame decode failed: ${getErrorMessage(cause)}`, cause);
919
1205
  }
920
- const isAck = ProtocolV2.isAckFrame(rxFrame);
921
- if (!isAck) {
922
- const rxMetadata = ProtocolV2.inspectFrame(schemas, rxFrame);
923
- if (!shouldReduceDebug) {
924
- (_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, `[${logPrefix}] RX`, {
925
- method: name,
926
- type: rxMetadata.type,
927
- typeId: rxMetadata.messageTypeId,
928
- seq: rxMetadata.seq,
929
- bytes: rxFrame.length,
930
- });
931
- }
932
- const decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
933
- const response = call(decoded);
934
- if ((_c = callOptions.intermediateTypes) === null || _c === void 0 ? void 0 : _c.includes(response.type)) {
935
- (_d = callOptions.onIntermediateResponse) === null || _d === void 0 ? void 0 : _d.call(callOptions, response);
936
- }
937
- else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
938
- return response;
939
- }
940
- else if (!shouldReduceDebug) {
941
- (_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}`);
942
- }
1206
+ if (this.lastResponseSequence === decoded.seq) {
1207
+ throw new ProtocolV2LinkError('response-sequence', `Protocol V2 duplicate response sequence: ${decoded.seq}`);
1208
+ }
1209
+ this.lastResponseSequence = decoded.seq;
1210
+ const response = call(decoded);
1211
+ if ((_c = callOptions.intermediateTypes) === null || _c === void 0 ? void 0 : _c.includes(response.type)) {
1212
+ (_d = callOptions.onIntermediateResponse) === null || _d === void 0 ? void 0 : _d.call(callOptions, response);
1213
+ }
1214
+ else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1215
+ return response;
1216
+ }
1217
+ else if (!shouldReduceDebug) {
1218
+ (_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}`);
943
1219
  }
944
1220
  }
945
- throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
946
- });
947
- return withProtocolTimeout(readResponse(), callOptions.timeoutMs, () => {
948
- var _a;
949
- return createTimeoutError
950
- ? createTimeoutError(name, (_a = callOptions.timeoutMs) !== null && _a !== void 0 ? _a : 0)
951
- : new Error(`Protocol V2 response timeout after ${callOptions.timeoutMs}ms for ${name}`);
952
- }, () => {
953
- cancellation.cancelled = true;
954
- });
1221
+ }
1222
+ throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1223
+ });
1224
+ return withProtocolTimeout(runCall(), timeoutMs, () => createTimeoutError
1225
+ ? createTimeoutError(name, timeoutMs)
1226
+ : new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${name}`), () => {
1227
+ abortController.abort();
955
1228
  });
956
1229
  }
957
1230
  }
958
1231
  function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', onBeforeProbe, onProbeFailed, }) {
959
- var _a;
1232
+ var _a, _b, _c;
960
1233
  return __awaiter(this, void 0, void 0, function* () {
961
1234
  let probeError;
962
1235
  try {
963
1236
  yield (onBeforeProbe === null || onBeforeProbe === void 0 ? void 0 : onBeforeProbe());
964
- const response = yield call('Ping', { message: 'protocol-v2-probe' }, { timeoutMs, expectedTypes: ['Success'] });
1237
+ const response = yield call('Ping', { message: 'protocol-v2-probe' }, {
1238
+ timeoutMs,
1239
+ expectedTypes: ['Success'],
1240
+ });
965
1241
  if (response.type === 'Success') {
966
1242
  return true;
967
1243
  }
1244
+ if (response.type === 'Failure') {
1245
+ const failureCode = (_a = response.message) === null || _a === void 0 ? void 0 : _a.code;
1246
+ const firmwareMessage = (_b = response.message) === null || _b === void 0 ? void 0 : _b.message;
1247
+ if (isProtocolV2LinkDisabledFailure(failureCode, firmwareMessage)) {
1248
+ throw createProtocolV2LinkDisabledError(failureCode, firmwareMessage);
1249
+ }
1250
+ }
968
1251
  probeError = new Error(`unexpected response type ${response.type}`);
969
1252
  }
970
1253
  catch (error) {
1254
+ if (isProtocolV2LinkDisabledError(error)) {
1255
+ throw error;
1256
+ }
971
1257
  probeError = error;
972
1258
  }
973
- (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] Protocol V2 probe failed:`, getErrorMessage(probeError));
1259
+ (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] Protocol V2 probe failed:`, getErrorMessage(probeError));
974
1260
  yield (onProbeFailed === null || onProbeFailed === void 0 ? void 0 : onProbeFailed(probeError));
975
1261
  return false;
976
1262
  });
@@ -981,12 +1267,19 @@ class ProtocolV2LinkManager {
981
1267
  this.links = new Map();
982
1268
  this.sequences = new Map();
983
1269
  this.callQueues = new Map();
1270
+ this.generations = new Map();
1271
+ this.invalidationReasons = new Map();
1272
+ this.invalidations = new Map();
984
1273
  this.options = options;
985
1274
  }
986
1275
  call(key, createAdapter, name, data, options) {
987
- var _a;
988
- const run = () => this.executeCall(key, createAdapter, name, data, options);
989
- const previous = (_a = this.callQueues.get(key)) !== null && _a !== void 0 ? _a : Promise.resolve();
1276
+ var _a, _b;
1277
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1278
+ const run = () => {
1279
+ this.assertCallGeneration(key, generation);
1280
+ return this.executeCall(key, createAdapter, name, data, options);
1281
+ };
1282
+ const previous = (_b = this.callQueues.get(key)) !== null && _b !== void 0 ? _b : Promise.resolve();
990
1283
  const result = previous.then(run, run);
991
1284
  const queue = result.catch(() => undefined);
992
1285
  this.callQueues.set(key, queue);
@@ -995,21 +1288,51 @@ class ProtocolV2LinkManager {
995
1288
  .catch(() => undefined);
996
1289
  return result;
997
1290
  }
1291
+ sendFlowControl(key, createAdapter, name, data) {
1292
+ var _a;
1293
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1294
+ this.assertCallGeneration(key, generation);
1295
+ return this.getOrCreateLink(key, createAdapter).session.sendFlowControl(name, data);
1296
+ }
998
1297
  invalidateLink(key, reason) {
999
- var _a, _b;
1298
+ var _a;
1000
1299
  return __awaiter(this, void 0, void 0, function* () {
1300
+ const generation = ((_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1301
+ this.generations.set(key, generation);
1302
+ this.invalidationReasons.set(key, { generation, reason });
1303
+ const pendingInvalidation = this.invalidations.get(key);
1001
1304
  const link = this.links.get(key);
1002
- if (!link)
1305
+ if (!link) {
1306
+ yield pendingInvalidation;
1003
1307
  return;
1308
+ }
1004
1309
  this.links.delete(key);
1005
1310
  link.state.invalidatedReason = reason;
1006
- yield link.adapter.reset(reason);
1007
- yield ((_b = (_a = this.options).onLinkInvalidated) === null || _b === void 0 ? void 0 : _b.call(_a, key, reason));
1311
+ const invalidation = (() => __awaiter(this, void 0, void 0, function* () {
1312
+ var _b, _c;
1313
+ yield (pendingInvalidation === null || pendingInvalidation === void 0 ? void 0 : pendingInvalidation.catch(() => undefined));
1314
+ yield link.adapter.reset(reason);
1315
+ yield ((_c = (_b = this.options).onLinkInvalidated) === null || _c === void 0 ? void 0 : _c.call(_b, key, reason));
1316
+ }))();
1317
+ this.invalidations.set(key, invalidation);
1318
+ try {
1319
+ yield invalidation;
1320
+ }
1321
+ finally {
1322
+ if (this.invalidations.get(key) === invalidation) {
1323
+ this.invalidations.delete(key);
1324
+ }
1325
+ }
1008
1326
  });
1009
1327
  }
1010
1328
  invalidateAllLinks(reason) {
1011
1329
  return __awaiter(this, void 0, void 0, function* () {
1012
- yield Promise.all(Array.from(this.links.keys(), key => this.invalidateLink(key, reason)));
1330
+ const keys = new Set([
1331
+ ...this.links.keys(),
1332
+ ...this.callQueues.keys(),
1333
+ ...this.invalidations.keys(),
1334
+ ]);
1335
+ yield Promise.all(Array.from(keys, key => this.invalidateLink(key, reason)));
1013
1336
  });
1014
1337
  }
1015
1338
  dispose(reason) {
@@ -1017,6 +1340,7 @@ class ProtocolV2LinkManager {
1017
1340
  yield this.invalidateAllLinks(reason);
1018
1341
  this.sequences.clear();
1019
1342
  this.callQueues.clear();
1343
+ this.invalidations.clear();
1020
1344
  });
1021
1345
  }
1022
1346
  getOrCreateLink(key, createAdapter) {
@@ -1084,6 +1408,17 @@ class ProtocolV2LinkManager {
1084
1408
  this.callQueues.delete(key);
1085
1409
  }
1086
1410
  }
1411
+ assertCallGeneration(key, generation) {
1412
+ var _a;
1413
+ const currentGeneration = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1414
+ if (currentGeneration === generation)
1415
+ return;
1416
+ const invalidation = this.invalidationReasons.get(key);
1417
+ const reason = (invalidation === null || invalidation === void 0 ? void 0 : invalidation.generation) === currentGeneration
1418
+ ? invalidation.reason
1419
+ : 'Protocol V2 link generation changed';
1420
+ throw new ProtocolV2LinkError('generation', reason);
1421
+ }
1087
1422
  }
1088
1423
 
1089
1424
  class ProtocolV2UsbTransportBase {
@@ -1094,7 +1429,7 @@ class ProtocolV2UsbTransportBase {
1094
1429
  this.protocolV2UsbOptions = options;
1095
1430
  this.protocolV2UsbLinks = new ProtocolV2LinkManager({
1096
1431
  getSchemas: () => this.getProtocolV2UsbSchemas(),
1097
- classifyError: () => 'link-fatal',
1432
+ classifyError: error => (isProtocolV2LinkError(error) ? 'link-fatal' : 'recoverable'),
1098
1433
  onLinkInvalidated: (key, reason) => __awaiter(this, void 0, void 0, function* () {
1099
1434
  var _a;
1100
1435
  (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
@@ -1119,6 +1454,9 @@ class ProtocolV2UsbTransportBase {
1119
1454
  callProtocolV2Usb(key, name, data, options) {
1120
1455
  return this.protocolV2UsbLinks.call(key, () => this.createProtocolV2UsbAdapter(key), name, data, options);
1121
1456
  }
1457
+ sendProtocolV2UsbFlowControl(key, name, data) {
1458
+ return this.protocolV2UsbLinks.sendFlowControl(key, () => this.createProtocolV2UsbAdapter(key), name, data);
1459
+ }
1122
1460
  invalidateProtocolV2UsbLink(key, reason) {
1123
1461
  return this.protocolV2UsbLinks.invalidateLink(key, reason);
1124
1462
  }
@@ -1144,10 +1482,10 @@ class ProtocolV2UsbTransportBase {
1144
1482
  }
1145
1483
  const assertCurrentGeneration = () => {
1146
1484
  if (cancellation.reason) {
1147
- throw new Error(cancellation.reason);
1485
+ throw new ProtocolV2LinkError('generation', cancellation.reason);
1148
1486
  }
1149
1487
  if (this.protocolV2UsbGenerations.get(key) !== generation) {
1150
- throw new Error('Protocol V2 USB connection generation changed');
1488
+ throw new ProtocolV2LinkError('generation', 'Protocol V2 USB connection generation changed');
1151
1489
  }
1152
1490
  };
1153
1491
  return {
@@ -1156,11 +1494,15 @@ class ProtocolV2UsbTransportBase {
1156
1494
  generation,
1157
1495
  prepareCall: () => {
1158
1496
  assertCurrentGeneration();
1159
- this.getProtocolV2UsbAssembler(key).reset();
1160
1497
  },
1161
1498
  writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1162
1499
  assertCurrentGeneration();
1163
- yield this.writeProtocolV2UsbPacket(key, frame, context);
1500
+ try {
1501
+ yield this.writeProtocolV2UsbPacket(key, frame, context);
1502
+ }
1503
+ catch (error) {
1504
+ throw this.createProtocolV2UsbIoError('write', error);
1505
+ }
1164
1506
  assertCurrentGeneration();
1165
1507
  }),
1166
1508
  readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
@@ -1168,13 +1510,15 @@ class ProtocolV2UsbTransportBase {
1168
1510
  const assembler = this.getProtocolV2UsbAssembler(key);
1169
1511
  let frame = assembler.push(new Uint8Array(0));
1170
1512
  while (!frame) {
1171
- const packetRead = this.readProtocolV2UsbPacket(key, context).then(packet => ({
1172
- packet,
1173
- }));
1513
+ const packetRead = this.readProtocolV2UsbPacket(key, context)
1514
+ .then(packet => ({ packet }))
1515
+ .catch(error => {
1516
+ throw this.createProtocolV2UsbIoError('read', error);
1517
+ });
1174
1518
  const cancelled = cancellation.promise.then(reason => ({ reason }));
1175
1519
  const result = yield Promise.race([packetRead, cancelled]);
1176
1520
  if ('reason' in result) {
1177
- throw new Error(result.reason);
1521
+ throw new ProtocolV2LinkError('generation', result.reason);
1178
1522
  }
1179
1523
  assertCurrentGeneration();
1180
1524
  frame = assembler.push(result.packet);
@@ -1215,8 +1559,17 @@ class ProtocolV2UsbTransportBase {
1215
1559
  };
1216
1560
  return cancellation;
1217
1561
  }
1562
+ createProtocolV2UsbIoError(operation, error) {
1563
+ if (isProtocolV2LinkError(error))
1564
+ return error;
1565
+ return new ProtocolV2LinkError('io', `Protocol V2 USB ${operation} failed: ${getErrorMessage(error) || 'unknown error'}`, error);
1566
+ }
1218
1567
  }
1219
1568
 
1569
+ const TRANSPORT_EVENT = {
1570
+ DEVICE_DISCONNECT: 'transport-device-disconnect',
1571
+ };
1572
+
1220
1573
  exports.AptosTransactionType = void 0;
1221
1574
  (function (AptosTransactionType) {
1222
1575
  AptosTransactionType[AptosTransactionType["STANDARD"] = 0] = "STANDARD";
@@ -1463,6 +1816,24 @@ exports.EthereumDataType = void 0;
1463
1816
  EthereumDataType[EthereumDataType["ARRAY"] = 7] = "ARRAY";
1464
1817
  EthereumDataType[EthereumDataType["STRUCT"] = 8] = "STRUCT";
1465
1818
  })(exports.EthereumDataType || (exports.EthereumDataType = {}));
1819
+ exports.Enum_KaspaInputScriptType = void 0;
1820
+ (function (Enum_KaspaInputScriptType) {
1821
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_SCHNORR"] = 0] = "KASPA_SPEND_P2PK_SCHNORR";
1822
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_ECDSA"] = 1] = "KASPA_SPEND_P2PK_ECDSA";
1823
+ })(exports.Enum_KaspaInputScriptType || (exports.Enum_KaspaInputScriptType = {}));
1824
+ exports.Enum_KaspaOutputScriptType = void 0;
1825
+ (function (Enum_KaspaOutputScriptType) {
1826
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOADDRESS"] = 0] = "KASPA_PAYTOADDRESS";
1827
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOCHANGE"] = 1] = "KASPA_PAYTOCHANGE";
1828
+ })(exports.Enum_KaspaOutputScriptType || (exports.Enum_KaspaOutputScriptType = {}));
1829
+ exports.Enum_KaspaRequestType = void 0;
1830
+ (function (Enum_KaspaRequestType) {
1831
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_INPUT"] = 0] = "KASPA_TX_INPUT";
1832
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_OUTPUT"] = 1] = "KASPA_TX_OUTPUT";
1833
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PAYLOAD"] = 2] = "KASPA_TX_PAYLOAD";
1834
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_FINISHED"] = 3] = "KASPA_TX_FINISHED";
1835
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PREV_META"] = 4] = "KASPA_TX_PREV_META";
1836
+ })(exports.Enum_KaspaRequestType || (exports.Enum_KaspaRequestType = {}));
1466
1837
  exports.Enum_BackupType = void 0;
1467
1838
  (function (Enum_BackupType) {
1468
1839
  Enum_BackupType[Enum_BackupType["Bip39"] = 0] = "Bip39";
@@ -1656,11 +2027,6 @@ exports.CommandFlags = void 0;
1656
2027
  CommandFlags[CommandFlags["Default"] = 0] = "Default";
1657
2028
  CommandFlags[CommandFlags["Factory_Only"] = 1] = "Factory_Only";
1658
2029
  })(exports.CommandFlags || (exports.CommandFlags = {}));
1659
- exports.WallpaperTarget = void 0;
1660
- (function (WallpaperTarget) {
1661
- WallpaperTarget[WallpaperTarget["Home"] = 0] = "Home";
1662
- WallpaperTarget[WallpaperTarget["Lock"] = 1] = "Lock";
1663
- })(exports.WallpaperTarget || (exports.WallpaperTarget = {}));
1664
2030
  exports.MoneroNetworkType = void 0;
1665
2031
  (function (MoneroNetworkType) {
1666
2032
  MoneroNetworkType[MoneroNetworkType["MAINNET"] = 0] = "MAINNET";
@@ -1668,22 +2034,18 @@ exports.MoneroNetworkType = void 0;
1668
2034
  MoneroNetworkType[MoneroNetworkType["STAGENET"] = 2] = "STAGENET";
1669
2035
  MoneroNetworkType[MoneroNetworkType["FAKECHAIN"] = 3] = "FAKECHAIN";
1670
2036
  })(exports.MoneroNetworkType || (exports.MoneroNetworkType = {}));
1671
- exports.ViewTipType = void 0;
1672
- (function (ViewTipType) {
1673
- ViewTipType[ViewTipType["Default"] = 0] = "Default";
1674
- ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
1675
- ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
1676
- ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
1677
- ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
1678
- })(exports.ViewTipType || (exports.ViewTipType = {}));
1679
- exports.ViewSignLayout = void 0;
1680
- (function (ViewSignLayout) {
1681
- ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
1682
- ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
1683
- ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
1684
- ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
1685
- ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
1686
- })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
2037
+ exports.UiAnimationType = void 0;
2038
+ (function (UiAnimationType) {
2039
+ UiAnimationType[UiAnimationType["Unknown"] = 0] = "Unknown";
2040
+ UiAnimationType[UiAnimationType["Signing"] = 1] = "Signing";
2041
+ })(exports.UiAnimationType || (exports.UiAnimationType = {}));
2042
+ exports.UiAnimationCommand = void 0;
2043
+ (function (UiAnimationCommand) {
2044
+ UiAnimationCommand[UiAnimationCommand["CommandUnknown"] = 0] = "CommandUnknown";
2045
+ UiAnimationCommand[UiAnimationCommand["Start"] = 1] = "Start";
2046
+ UiAnimationCommand[UiAnimationCommand["Stop"] = 2] = "Stop";
2047
+ UiAnimationCommand[UiAnimationCommand["Refresh"] = 3] = "Refresh";
2048
+ })(exports.UiAnimationCommand || (exports.UiAnimationCommand = {}));
1687
2049
  exports.DeviceErrorCode = void 0;
1688
2050
  (function (DeviceErrorCode) {
1689
2051
  DeviceErrorCode[DeviceErrorCode["DeviceError_None"] = 0] = "DeviceError_None";
@@ -1710,6 +2072,11 @@ exports.DeviceSettingsPage = void 0;
1710
2072
  DeviceSettingsPage[DeviceSettingsPage["DevicePassphrase"] = 2] = "DevicePassphrase";
1711
2073
  DeviceSettingsPage[DeviceSettingsPage["DeviceAirgap"] = 3] = "DeviceAirgap";
1712
2074
  })(exports.DeviceSettingsPage || (exports.DeviceSettingsPage = {}));
2075
+ exports.DeviceFactoryAck = void 0;
2076
+ (function (DeviceFactoryAck) {
2077
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
2078
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
2079
+ })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1713
2080
  exports.DeviceFirmwareTargetType = void 0;
1714
2081
  (function (DeviceFirmwareTargetType) {
1715
2082
  DeviceFirmwareTargetType[DeviceFirmwareTargetType["FW_MGMT_TARGET_INVALID"] = 0] = "FW_MGMT_TARGET_INVALID";
@@ -1738,11 +2105,6 @@ exports.DeviceFirmwareUpdateTaskStatus = void 0;
1738
2105
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY"] = 9] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY";
1739
2106
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS"] = 10] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS";
1740
2107
  })(exports.DeviceFirmwareUpdateTaskStatus || (exports.DeviceFirmwareUpdateTaskStatus = {}));
1741
- exports.DeviceFactoryAck = void 0;
1742
- (function (DeviceFactoryAck) {
1743
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1744
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1745
- })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1746
2108
  exports.DeviceType = void 0;
1747
2109
  (function (DeviceType) {
1748
2110
  DeviceType[DeviceType["CLASSIC1"] = 0] = "CLASSIC1";
@@ -1765,26 +2127,86 @@ exports.DeviceSEState = void 0;
1765
2127
  DeviceSEState[DeviceSEState["APP_FACTORY"] = 51] = "APP_FACTORY";
1766
2128
  DeviceSEState[DeviceSEState["APP"] = 85] = "APP";
1767
2129
  })(exports.DeviceSEState || (exports.DeviceSEState = {}));
2130
+ exports.DeviceSessionErrorCode = void 0;
2131
+ (function (DeviceSessionErrorCode) {
2132
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_None"] = 0] = "DeviceSessionError_None";
2133
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_UserCancelled"] = 1] = "DeviceSessionError_UserCancelled";
2134
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_InvalidSession"] = 2] = "DeviceSessionError_InvalidSession";
2135
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_AttachPinUnavailable"] = 3] = "DeviceSessionError_AttachPinUnavailable";
2136
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_PassphraseDisabled"] = 4] = "DeviceSessionError_PassphraseDisabled";
2137
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_Busy"] = 5] = "DeviceSessionError_Busy";
2138
+ })(exports.DeviceSessionErrorCode || (exports.DeviceSessionErrorCode = {}));
2139
+ exports.DeviceSessionSeedDomain = void 0;
2140
+ (function (DeviceSessionSeedDomain) {
2141
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Standard"] = 1] = "SeedDomain_Standard";
2142
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Cardano"] = 2] = "SeedDomain_Cardano";
2143
+ })(exports.DeviceSessionSeedDomain || (exports.DeviceSessionSeedDomain = {}));
2144
+ exports.DeviceSessionPinType = void 0;
2145
+ (function (DeviceSessionPinType) {
2146
+ DeviceSessionPinType[DeviceSessionPinType["Any"] = 1] = "Any";
2147
+ DeviceSessionPinType[DeviceSessionPinType["Main"] = 2] = "Main";
2148
+ DeviceSessionPinType[DeviceSessionPinType["AttachToPin"] = 3] = "AttachToPin";
2149
+ })(exports.DeviceSessionPinType || (exports.DeviceSessionPinType = {}));
1768
2150
  exports.DeviceSessionAskPin_FailureSubCodes = void 0;
1769
2151
  (function (DeviceSessionAskPin_FailureSubCodes) {
1770
2152
  DeviceSessionAskPin_FailureSubCodes[DeviceSessionAskPin_FailureSubCodes["UserCancel"] = 1] = "UserCancel";
1771
2153
  })(exports.DeviceSessionAskPin_FailureSubCodes || (exports.DeviceSessionAskPin_FailureSubCodes = {}));
1772
- exports.DevOnboardingStage = void 0;
1773
- (function (DevOnboardingStage) {
1774
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_UNKNOWN"] = 0] = "DEV_ONBOARDING_STAGE_UNKNOWN";
1775
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SAFETY_CHECK"] = 1] = "DEV_ONBOARDING_STAGE_SAFETY_CHECK";
1776
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_PERSONALIZATION"] = 2] = "DEV_ONBOARDING_STAGE_PERSONALIZATION";
1777
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SELECT_SETUP_METHOD"] = 3] = "DEV_ONBOARDING_STAGE_SELECT_SETUP_METHOD";
1778
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_NEW_DEVICE"] = 4] = "DEV_ONBOARDING_STAGE_NEW_DEVICE";
1779
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SELECT_RESTORE_METHOD"] = 5] = "DEV_ONBOARDING_STAGE_SELECT_RESTORE_METHOD";
1780
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_RESTORE_MNEMONIC"] = 6] = "DEV_ONBOARDING_STAGE_RESTORE_MNEMONIC";
1781
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_RESTORE_SEEDCARD"] = 7] = "DEV_ONBOARDING_STAGE_RESTORE_SEEDCARD";
1782
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_WALLET_READY"] = 8] = "DEV_ONBOARDING_STAGE_WALLET_READY";
1783
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP_PROMPT"] = 9] = "DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP_PROMPT";
1784
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SELECT_SEEDCARD_BACKUP_METHOD"] = 10] = "DEV_ONBOARDING_STAGE_SELECT_SEEDCARD_BACKUP_METHOD";
1785
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP"] = 11] = "DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP";
1786
- DevOnboardingStage[DevOnboardingStage["DEV_ONBOARDING_STAGE_DONE"] = 12] = "DEV_ONBOARDING_STAGE_DONE";
1787
- })(exports.DevOnboardingStage || (exports.DevOnboardingStage = {}));
2154
+ exports.OnboardingStep = void 0;
2155
+ (function (OnboardingStep) {
2156
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_UNKNOWN"] = 0] = "ONBOARDING_STEP_UNKNOWN";
2157
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_CHECKING"] = 1] = "ONBOARDING_STEP_CHECKING";
2158
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PERSONALIZATION"] = 2] = "ONBOARDING_STEP_PERSONALIZATION";
2159
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PIN"] = 3] = "ONBOARDING_STEP_PIN";
2160
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_SETUP"] = 4] = "ONBOARDING_STEP_SETUP";
2161
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_DONE"] = 5] = "ONBOARDING_STEP_DONE";
2162
+ })(exports.OnboardingStep || (exports.OnboardingStep = {}));
2163
+ exports.OnboardingPhase = void 0;
2164
+ (function (OnboardingPhase) {
2165
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_UNKNOWN"] = 0] = "ONBOARDING_PHASE_UNKNOWN";
2166
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SAFETY_CHECK"] = 1] = "ONBOARDING_PHASE_SAFETY_CHECK";
2167
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_PIN_SETUP"] = 2] = "ONBOARDING_PHASE_PIN_SETUP";
2168
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_FINGERPRINT_SETUP"] = 3] = "ONBOARDING_PHASE_FINGERPRINT_SETUP";
2169
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SETUP_CHOICE"] = 4] = "ONBOARDING_PHASE_SETUP_CHOICE";
2170
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_CREATE_START"] = 5] = "ONBOARDING_PHASE_WALLET_CREATE_START";
2171
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW"] = 6] = "ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW";
2172
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM"] = 7] = "ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM";
2173
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RESTORE_METHOD_CHOICE"] = 8] = "ONBOARDING_PHASE_RESTORE_METHOD_CHOICE";
2174
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE"] = 9] = "ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE";
2175
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_RESTORE"] = 10] = "ONBOARDING_PHASE_SEEDCARD_RESTORE";
2176
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_READY"] = 11] = "ONBOARDING_PHASE_WALLET_READY";
2177
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT"] = 12] = "ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT";
2178
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP"] = 13] = "ONBOARDING_PHASE_SEEDCARD_BACKUP";
2179
+ })(exports.OnboardingPhase || (exports.OnboardingPhase = {}));
2180
+ exports.OnboardingSetupKind = void 0;
2181
+ (function (OnboardingSetupKind) {
2182
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_UNKNOWN"] = 0] = "ONBOARDING_SETUP_KIND_UNKNOWN";
2183
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CHOICE"] = 1] = "ONBOARDING_SETUP_KIND_CHOICE";
2184
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CREATE"] = 2] = "ONBOARDING_SETUP_KIND_CREATE";
2185
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_RESTORE"] = 3] = "ONBOARDING_SETUP_KIND_RESTORE";
2186
+ })(exports.OnboardingSetupKind || (exports.OnboardingSetupKind = {}));
2187
+ exports.OnboardingSetupMethod = void 0;
2188
+ (function (OnboardingSetupMethod) {
2189
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_UNKNOWN"] = 0] = "ONBOARDING_SETUP_METHOD_UNKNOWN";
2190
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE"] = 1] = "ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE";
2191
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_SEEDCARD"] = 2] = "ONBOARDING_SETUP_METHOD_SEEDCARD";
2192
+ })(exports.OnboardingSetupMethod || (exports.OnboardingSetupMethod = {}));
2193
+ exports.ViewTipType = void 0;
2194
+ (function (ViewTipType) {
2195
+ ViewTipType[ViewTipType["Default"] = 0] = "Default";
2196
+ ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
2197
+ ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
2198
+ ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
2199
+ ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
2200
+ })(exports.ViewTipType || (exports.ViewTipType = {}));
2201
+ exports.ViewSignLayout = void 0;
2202
+ (function (ViewSignLayout) {
2203
+ ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
2204
+ ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
2205
+ ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
2206
+ ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
2207
+ ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
2208
+ ViewSignLayout[ViewSignLayout["LayoutEthApprove"] = 5] = "LayoutEthApprove";
2209
+ })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
1788
2210
  exports.ProtocolV2FailureType = void 0;
1789
2211
  (function (ProtocolV2FailureType) {
1790
2212
  ProtocolV2FailureType[ProtocolV2FailureType["Failure_InvalidMessage"] = 1] = "Failure_InvalidMessage";
@@ -1847,6 +2269,9 @@ var messages = /*#__PURE__*/Object.freeze({
1847
2269
  get EthereumGnosisSafeTxOperation () { return exports.EthereumGnosisSafeTxOperation; },
1848
2270
  get EthereumDataTypeOneKey () { return exports.EthereumDataTypeOneKey; },
1849
2271
  get EthereumDataType () { return exports.EthereumDataType; },
2272
+ get Enum_KaspaInputScriptType () { return exports.Enum_KaspaInputScriptType; },
2273
+ get Enum_KaspaOutputScriptType () { return exports.Enum_KaspaOutputScriptType; },
2274
+ get Enum_KaspaRequestType () { return exports.Enum_KaspaRequestType; },
1850
2275
  get Enum_BackupType () { return exports.Enum_BackupType; },
1851
2276
  get Enum_SafetyCheckLevel () { return exports.Enum_SafetyCheckLevel; },
1852
2277
  get OneKeyDeviceType () { return exports.OneKeyDeviceType; },
@@ -1878,25 +2303,114 @@ var messages = /*#__PURE__*/Object.freeze({
1878
2303
  get TronResourceCode () { return exports.TronResourceCode; },
1879
2304
  get TronMessageType () { return exports.TronMessageType; },
1880
2305
  get CommandFlags () { return exports.CommandFlags; },
1881
- get WallpaperTarget () { return exports.WallpaperTarget; },
1882
2306
  get MoneroNetworkType () { return exports.MoneroNetworkType; },
1883
- get ViewTipType () { return exports.ViewTipType; },
1884
- get ViewSignLayout () { return exports.ViewSignLayout; },
2307
+ get UiAnimationType () { return exports.UiAnimationType; },
2308
+ get UiAnimationCommand () { return exports.UiAnimationCommand; },
1885
2309
  get DeviceErrorCode () { return exports.DeviceErrorCode; },
1886
2310
  get DeviceRebootType () { return exports.DeviceRebootType; },
1887
2311
  get DeviceSettingsPage () { return exports.DeviceSettingsPage; },
2312
+ get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1888
2313
  get DeviceFirmwareTargetType () { return exports.DeviceFirmwareTargetType; },
1889
2314
  get DeviceFirmwareUpdateTaskStatus () { return exports.DeviceFirmwareUpdateTaskStatus; },
1890
- get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1891
2315
  get DeviceType () { return exports.DeviceType; },
1892
2316
  get DeviceSeType () { return exports.DeviceSeType; },
1893
2317
  get DeviceSEState () { return exports.DeviceSEState; },
2318
+ get DeviceSessionErrorCode () { return exports.DeviceSessionErrorCode; },
2319
+ get DeviceSessionSeedDomain () { return exports.DeviceSessionSeedDomain; },
2320
+ get DeviceSessionPinType () { return exports.DeviceSessionPinType; },
1894
2321
  get DeviceSessionAskPin_FailureSubCodes () { return exports.DeviceSessionAskPin_FailureSubCodes; },
1895
- get DevOnboardingStage () { return exports.DevOnboardingStage; },
2322
+ get OnboardingStep () { return exports.OnboardingStep; },
2323
+ get OnboardingPhase () { return exports.OnboardingPhase; },
2324
+ get OnboardingSetupKind () { return exports.OnboardingSetupKind; },
2325
+ get OnboardingSetupMethod () { return exports.OnboardingSetupMethod; },
2326
+ get ViewTipType () { return exports.ViewTipType; },
2327
+ get ViewSignLayout () { return exports.ViewSignLayout; },
1896
2328
  get ProtocolV2FailureType () { return exports.ProtocolV2FailureType; },
1897
2329
  get Enum_ProtocolV2Capability () { return exports.Enum_ProtocolV2Capability; }
1898
2330
  });
1899
2331
 
2332
+ const REDACTED = '[REDACTED]';
2333
+ const SENSITIVE_LOG_KEYS = new Set([
2334
+ 'accesstoken',
2335
+ 'address',
2336
+ 'apikey',
2337
+ 'connectid',
2338
+ 'devicestate',
2339
+ 'deviceid',
2340
+ 'entropy',
2341
+ 'expectedpassphrasestate',
2342
+ 'mnemonic',
2343
+ 'passphrase',
2344
+ 'passphrasestate',
2345
+ 'password',
2346
+ 'pin',
2347
+ 'privatekey',
2348
+ 'publickey',
2349
+ 'seed',
2350
+ 'serialnumber',
2351
+ 'session',
2352
+ 'sessionid',
2353
+ 'signature',
2354
+ 'token',
2355
+ 'uuid',
2356
+ 'walletsessionid',
2357
+ 'xprv',
2358
+ 'xpub',
2359
+ ]);
2360
+ const normalizeLogKey = (key) => key.replace(/[_-]/g, '').toLowerCase();
2361
+ const isSensitiveLogKey = (key) => {
2362
+ const normalizedKey = normalizeLogKey(key);
2363
+ return (SENSITIVE_LOG_KEYS.has(normalizedKey) ||
2364
+ normalizedKey.endsWith('address') ||
2365
+ normalizedKey.endsWith('privatekey') ||
2366
+ normalizedKey.endsWith('publickey') ||
2367
+ normalizedKey.endsWith('signature'));
2368
+ };
2369
+ const isSigningMessage = (messageName) => Boolean(messageName && /(?:sign|txack|transaction)/i.test(messageName));
2370
+ const redactLogValue = (value, seen) => {
2371
+ if (ArrayBuffer.isView(value)) {
2372
+ return `[BINARY:${value.byteLength}]`;
2373
+ }
2374
+ if (value instanceof ArrayBuffer) {
2375
+ return `[BINARY:${value.byteLength}]`;
2376
+ }
2377
+ if (Array.isArray(value)) {
2378
+ return value.map(item => redactLogValue(item, seen));
2379
+ }
2380
+ if (!value || typeof value !== 'object') {
2381
+ return value;
2382
+ }
2383
+ if (seen.has(value)) {
2384
+ return '[CIRCULAR]';
2385
+ }
2386
+ seen.add(value);
2387
+ const redacted = Object.fromEntries(Object.entries(value).map(([key, item]) => [
2388
+ key,
2389
+ isSensitiveLogKey(key) && item !== null && item !== undefined
2390
+ ? REDACTED
2391
+ : redactLogValue(item, seen),
2392
+ ]));
2393
+ seen.delete(value);
2394
+ return redacted;
2395
+ };
2396
+ function getSafeTransportLogPayload(value, messageName) {
2397
+ if (isSigningMessage(messageName)) {
2398
+ return REDACTED;
2399
+ }
2400
+ return redactLogValue(value, new WeakSet());
2401
+ }
2402
+ function createTransportCallLog(name, protocol, data) {
2403
+ return {
2404
+ name,
2405
+ protocol,
2406
+ request: getSafeTransportLogPayload(data, name),
2407
+ };
2408
+ }
2409
+ const HIGH_VOLUME_CALLS = new Set(['FileWrite', 'FilesystemFileWrite', 'EmmcFileWrite']);
2410
+ function shouldSuppressHighVolumeCallLog(name) {
2411
+ return HIGH_VOLUME_CALLS.has(name);
2412
+ }
2413
+
1900
2414
  protobuf__namespace.util.Long = Long__default["default"];
1901
2415
  protobuf__namespace.configure();
1902
2416
  var index = {
@@ -1933,29 +2447,41 @@ exports.PROTOCOL_V1_REPORT_ID = PROTOCOL_V1_REPORT_ID;
1933
2447
  exports.PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_USB_PACKET_SIZE;
1934
2448
  exports.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
1935
2449
  exports.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE;
2450
+ exports.PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE;
1936
2451
  exports.PROTOCOL_V2_BLE_FRAME_MAX_BYTES = PROTOCOL_V2_BLE_FRAME_MAX_BYTES;
1937
2452
  exports.PROTOCOL_V2_CHANNEL_BLE_UART = PROTOCOL_V2_CHANNEL_BLE_UART;
1938
2453
  exports.PROTOCOL_V2_CHANNEL_SOCKET = PROTOCOL_V2_CHANNEL_SOCKET;
1939
2454
  exports.PROTOCOL_V2_CHANNEL_USB = PROTOCOL_V2_CHANNEL_USB;
2455
+ exports.PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1940
2456
  exports.PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_FILE_CHUNK_SIZE;
1941
2457
  exports.PROTOCOL_V2_FRAME_MAX_BYTES = PROTOCOL_V2_FRAME_MAX_BYTES;
1942
2458
  exports.PROTOCOL_V2_PACKET_SRC_COMMAND = PROTOCOL_V2_PACKET_SRC_COMMAND;
1943
2459
  exports.PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = PROTOCOL_V2_SYS_MESSAGE_THRESHOLD;
1944
2460
  exports.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
1945
- exports.PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS;
1946
2461
  exports.ProtocolV1 = ProtocolV1;
1947
2462
  exports.ProtocolV2 = ProtocolV2;
1948
2463
  exports.ProtocolV2FrameAssembler = ProtocolV2FrameAssembler;
2464
+ exports.ProtocolV2LinkError = ProtocolV2LinkError;
1949
2465
  exports.ProtocolV2LinkManager = ProtocolV2LinkManager;
1950
2466
  exports.ProtocolV2SequenceCursor = ProtocolV2SequenceCursor;
1951
2467
  exports.ProtocolV2Session = ProtocolV2Session;
1952
2468
  exports.ProtocolV2UsbTransportBase = ProtocolV2UsbTransportBase;
2469
+ exports.TRANSPORT_EVENT = TRANSPORT_EVENT;
1953
2470
  exports.bytesToHex = bytesToHex;
1954
2471
  exports.concatUint8Arrays = concatUint8Arrays;
2472
+ exports.createProtocolV2LinkDisabledError = createProtocolV2LinkDisabledError;
2473
+ exports.createTransportCallLog = createTransportCallLog;
1955
2474
  exports["default"] = index;
1956
2475
  exports.getErrorMessage = getErrorMessage;
2476
+ exports.getSafeTransportLogPayload = getSafeTransportLogPayload;
1957
2477
  exports.hexToBytes = hexToBytes;
2478
+ exports.isProtocolV2HighThroughputCall = isProtocolV2HighThroughputCall;
2479
+ exports.isProtocolV2LinkDisabledError = isProtocolV2LinkDisabledError;
2480
+ exports.isProtocolV2LinkDisabledFailure = isProtocolV2LinkDisabledFailure;
2481
+ exports.isProtocolV2LinkError = isProtocolV2LinkError;
1958
2482
  exports.probeProtocolV2 = probeProtocolV2;
1959
2483
  exports.protocolV1 = index$1;
1960
2484
  exports.protocolV2 = protocolV2Codec;
2485
+ exports.shouldSuppressHighVolumeCallLog = shouldSuppressHighVolumeCallLog;
1961
2486
  exports.withProtocolTimeout = withProtocolTimeout;
2487
+ exports.writeProtocolV2BleFrame = writeProtocolV2BleFrame;