@onekeyfe/hd-transport-react-native 1.2.8-alpha.2 → 1.2.8-alpha.4

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.
package/dist/index.js CHANGED
@@ -46,6 +46,76 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
46
46
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
47
47
  };
48
48
 
49
+ const lastKeyMissingAt = new Map();
50
+ const listeners$1 = new Set();
51
+ let unsubscribeNative$1;
52
+ const normalizeDeviceId$1 = (deviceId) => deviceId.toLowerCase();
53
+ const getCapableBleUtils$1 = () => {
54
+ if (reactNative.Platform.OS !== 'android')
55
+ return undefined;
56
+ const bleUtils = BleUtils__default["default"];
57
+ if (typeof bleUtils.supportsDeviceKeyMissing !== 'function' ||
58
+ typeof bleUtils.onDeviceKeyMissing !== 'function') {
59
+ return undefined;
60
+ }
61
+ return bleUtils.supportsDeviceKeyMissing() ? bleUtils : undefined;
62
+ };
63
+ const isBleKeyMissingSupported = () => getCapableBleUtils$1() !== undefined;
64
+ const startBleKeyMissingTracking = () => {
65
+ if (unsubscribeNative$1)
66
+ return true;
67
+ const bleUtils = getCapableBleUtils$1();
68
+ if (!(bleUtils === null || bleUtils === void 0 ? void 0 : bleUtils.onDeviceKeyMissing))
69
+ return false;
70
+ unsubscribeNative$1 = bleUtils.onDeviceKeyMissing(event => {
71
+ if (typeof (event === null || event === void 0 ? void 0 : event.id) !== 'string')
72
+ return;
73
+ const deviceId = normalizeDeviceId$1(event.id);
74
+ lastKeyMissingAt.set(deviceId, Date.now());
75
+ listeners$1.forEach(listener => listener(deviceId));
76
+ });
77
+ return true;
78
+ };
79
+ const stopBleKeyMissingTracking = () => {
80
+ unsubscribeNative$1 === null || unsubscribeNative$1 === void 0 ? void 0 : unsubscribeNative$1();
81
+ unsubscribeNative$1 = undefined;
82
+ lastKeyMissingAt.clear();
83
+ listeners$1.clear();
84
+ };
85
+ const hasBleKeyMissingSince = (deviceId, sinceMs) => {
86
+ const at = lastKeyMissingAt.get(normalizeDeviceId$1(deviceId));
87
+ return at !== undefined && at >= sinceMs;
88
+ };
89
+ const onBleKeyMissing = (deviceId, callback) => {
90
+ const target = normalizeDeviceId$1(deviceId);
91
+ const listener = id => {
92
+ if (id === target)
93
+ callback();
94
+ };
95
+ listeners$1.add(listener);
96
+ return () => {
97
+ listeners$1.delete(listener);
98
+ };
99
+ };
100
+ const waitForBleKeyMissing = (deviceId, sinceMs, timeoutMs) => {
101
+ if (!startBleKeyMissingTracking())
102
+ return Promise.resolve(false);
103
+ if (hasBleKeyMissingSince(deviceId, sinceMs))
104
+ return Promise.resolve(true);
105
+ return new Promise(resolve => {
106
+ const settle = (found) => {
107
+ clearTimeout(timer);
108
+ cleanup();
109
+ resolve(found);
110
+ };
111
+ const cleanup = onBleKeyMissing(deviceId, () => {
112
+ if (hasBleKeyMissingSince(deviceId, sinceMs))
113
+ settle(true);
114
+ });
115
+ const timer = setTimeout(() => settle(false), timeoutMs);
116
+ });
117
+ };
118
+
49
119
  let activeLogger;
50
120
  const setBleLogger = (logger) => {
51
121
  activeLogger = logger;
@@ -70,6 +140,7 @@ const bondFailureReasons = {
70
140
  };
71
141
  const getConnectedDeviceIds = (serviceUuids) => BleUtils__default["default"].getConnectedPeripherals(serviceUuids);
72
142
  const pairDevice = (macAddress) => BleUtils__default["default"].pairDevice(macAddress);
143
+ const SYSTEM_BONDING_RESTART_WINDOW_MS = 1500;
73
144
  const createBondFailureError = (bondState) => {
74
145
  var _a;
75
146
  const nativeReason = 'reason' in bondState && typeof bondState.reason === 'number' ? bondState.reason : undefined;
@@ -83,17 +154,21 @@ const createBondFailureError = (bondState) => {
83
154
  }
84
155
  return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing failed', params);
85
156
  };
86
- const onDeviceBondState = (bleMacAddress, signal) => new Promise((resolve, reject) => {
157
+ const onDeviceBondState = (bleMacAddress, signal, options) => new Promise((resolve, reject) => {
87
158
  if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
88
159
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
89
160
  return;
90
161
  }
162
+ let pendingFailure;
91
163
  const cleanup = () => {
92
164
  if (timeout) {
93
165
  clearTimeout(timeout);
94
166
  }
167
+ if (pendingFailure)
168
+ clearTimeout(pendingFailure);
95
169
  if (cleanupListener)
96
170
  cleanupListener();
171
+ cleanupKeyMissing === null || cleanupKeyMissing === void 0 ? void 0 : cleanupKeyMissing();
97
172
  signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
98
173
  };
99
174
  const onAbort = () => {
@@ -108,6 +183,15 @@ const onDeviceBondState = (bleMacAddress, signal) => new Promise((resolve, rejec
108
183
  reason: 'timeout',
109
184
  }));
110
185
  }, 60 * 1000);
186
+ const cleanupKeyMissing = startBleKeyMissingTracking()
187
+ ? onBleKeyMissing(bleMacAddress, () => {
188
+ cleanup();
189
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
190
+ phase: 'bond',
191
+ reason: 'key_missing',
192
+ }));
193
+ })
194
+ : undefined;
111
195
  const cleanupListener = BleUtils__default["default"].onDeviceBondState(peripheral => {
112
196
  var _a;
113
197
  if (((_a = peripheral.id) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== bleMacAddress.toLowerCase()) {
@@ -116,11 +200,24 @@ const onDeviceBondState = (bleMacAddress, signal) => new Promise((resolve, rejec
116
200
  const { bondState } = peripheral;
117
201
  const hasBonded = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_BONDED';
118
202
  const hasFailed = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_NONE';
203
+ const hasRestarted = bondState.preState === 'BOND_NONE' && bondState.state === 'BOND_BONDING';
119
204
  Logger.debug('onDeviceBondState bondState:', bondState);
120
205
  if (hasBonded) {
121
206
  cleanup();
122
207
  resolve(peripheral);
123
208
  }
209
+ else if (hasRestarted && pendingFailure) {
210
+ clearTimeout(pendingFailure);
211
+ pendingFailure = undefined;
212
+ }
213
+ else if (hasFailed && (options === null || options === void 0 ? void 0 : options.systemInitiated)) {
214
+ if (pendingFailure)
215
+ clearTimeout(pendingFailure);
216
+ pendingFailure = setTimeout(() => {
217
+ cleanup();
218
+ reject(createBondFailureError(bondState));
219
+ }, SYSTEM_BONDING_RESTART_WINDOW_MS);
220
+ }
124
221
  else if (hasFailed) {
125
222
  cleanup();
126
223
  reject(createBondFailureError(bondState));
@@ -211,53 +308,252 @@ const timer = process.env.NODE_ENV === 'development'
211
308
  },
212
309
  };
213
310
 
214
- const subscribeBleOn = (bleManager, ms = 2000) => new Promise((resolve, reject) => {
311
+ const subscribeBleOn = (bleManager, ms = 1000) => new Promise((resolve, reject) => {
215
312
  let done = false;
216
- let pendingError;
217
- let cancelTimeout = () => undefined;
218
- let removeSubscription = () => undefined;
219
- const finish = (error) => {
220
- if (done)
221
- return;
222
- done = true;
223
- cancelTimeout();
224
- removeSubscription();
225
- if (error)
226
- reject(error);
227
- else
228
- resolve();
229
- };
230
313
  const subscription = bleManager.onStateChange(state => {
231
314
  if (state === 'PoweredOn') {
232
- finish();
233
- }
234
- else if (state === 'PoweredOff') {
235
- pendingError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePoweredOff);
315
+ if (done)
316
+ return;
317
+ clearTimeout();
318
+ done = true;
319
+ subscription.remove();
320
+ resolve();
236
321
  }
237
- else if (state === 'Unsupported') {
238
- pendingError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleUnsupported);
322
+ }, true);
323
+ const clearTimeout = timer.timeout(() => {
324
+ if (done)
325
+ return;
326
+ subscription.remove();
327
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
328
+ }, ms);
329
+ });
330
+
331
+ const HCI_PIN_OR_KEY_MISSING = 0x06;
332
+ const lastEncryption = new Map();
333
+ const lastAclDisconnectAt = new Map();
334
+ const listeners = new Set();
335
+ let unsubscribeNative;
336
+ const normalizeDeviceId = (deviceId) => deviceId.toLowerCase();
337
+ const isEncrypted = (record) => record.status === 0 && record.enabled;
338
+ const getCapableBleUtils = () => {
339
+ if (reactNative.Platform.OS !== 'android')
340
+ return undefined;
341
+ const bleUtils = BleUtils__default["default"];
342
+ if (typeof bleUtils.supportsDeviceEncryptionChange !== 'function' ||
343
+ typeof bleUtils.onDeviceEncryptionChange !== 'function' ||
344
+ typeof bleUtils.onDeviceAclDisconnected !== 'function') {
345
+ return undefined;
346
+ }
347
+ return bleUtils.supportsDeviceEncryptionChange() ? bleUtils : undefined;
348
+ };
349
+ const notify = (deviceId) => {
350
+ listeners.forEach(listener => listener(deviceId));
351
+ };
352
+ const startBleEncryptionTracking = () => {
353
+ if (unsubscribeNative)
354
+ return true;
355
+ const bleUtils = getCapableBleUtils();
356
+ if (!(bleUtils === null || bleUtils === void 0 ? void 0 : bleUtils.onDeviceEncryptionChange) || !bleUtils.onDeviceAclDisconnected)
357
+ return false;
358
+ unsubscribeNative = [
359
+ bleUtils.onDeviceEncryptionChange(event => {
360
+ if (typeof (event === null || event === void 0 ? void 0 : event.id) !== 'string')
361
+ return;
362
+ const deviceId = normalizeDeviceId(event.id);
363
+ lastEncryption.set(deviceId, {
364
+ at: Date.now(),
365
+ status: Number(event.status),
366
+ enabled: event.enabled === true,
367
+ });
368
+ notify(deviceId);
369
+ }),
370
+ bleUtils.onDeviceAclDisconnected(event => {
371
+ if (typeof (event === null || event === void 0 ? void 0 : event.id) !== 'string')
372
+ return;
373
+ const deviceId = normalizeDeviceId(event.id);
374
+ lastAclDisconnectAt.set(deviceId, Date.now());
375
+ notify(deviceId);
376
+ }),
377
+ ];
378
+ return true;
379
+ };
380
+ const stopBleEncryptionTracking = () => {
381
+ unsubscribeNative === null || unsubscribeNative === void 0 ? void 0 : unsubscribeNative.forEach(unsubscribe => unsubscribe());
382
+ unsubscribeNative = undefined;
383
+ lastEncryption.clear();
384
+ lastAclDisconnectAt.clear();
385
+ listeners.clear();
386
+ };
387
+ const markBleLinkEncrypted = (deviceId) => {
388
+ if (!unsubscribeNative)
389
+ return;
390
+ lastEncryption.set(normalizeDeviceId(deviceId), { at: Date.now(), status: 0, enabled: true });
391
+ };
392
+ const waitForAndroidLinkEncryption = ({ deviceId, linkStartedAt, resultTimeoutMs, repairTimeoutMs, keyMissingGraceMs, signal, onRepairStarted, }) => {
393
+ if (!startBleEncryptionTracking())
394
+ return Promise.resolve('unresolved');
395
+ startBleKeyMissingTracking();
396
+ const target = normalizeDeviceId(deviceId);
397
+ const previous = lastEncryption.get(target);
398
+ const previousDropAt = lastAclDisconnectAt.get(target);
399
+ if (previous &&
400
+ previous.at < linkStartedAt &&
401
+ isEncrypted(previous) &&
402
+ (previousDropAt === undefined || previousDropAt < previous.at)) {
403
+ return Promise.resolve('already-encrypted');
404
+ }
405
+ return new Promise((resolve, reject) => {
406
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
407
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
408
+ return;
239
409
  }
240
- else if (state === 'Unauthorized') {
241
- pendingError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError);
410
+ let repairStartedAt;
411
+ let droppedDuringRepair = false;
412
+ let timer;
413
+ let settled = false;
414
+ const cleanup = () => {
415
+ settled = true;
416
+ if (timer)
417
+ clearTimeout(timer);
418
+ listeners.delete(onLinkEvent);
419
+ cleanupKeyMissing();
420
+ signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
421
+ };
422
+ const finish = (result) => {
423
+ cleanup();
424
+ resolve(result);
425
+ };
426
+ const fail = (error) => {
427
+ cleanup();
428
+ reject(error);
429
+ };
430
+ const arm = (ms, onExpire) => {
431
+ if (timer)
432
+ clearTimeout(timer);
433
+ timer = setTimeout(onExpire, ms);
434
+ };
435
+ const bondInvalid = () => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
436
+ phase: 'connect',
437
+ reason: 'key_missing',
438
+ });
439
+ const evaluate = () => {
440
+ if (settled)
441
+ return;
442
+ const record = lastEncryption.get(target);
443
+ const dropAt = lastAclDisconnectAt.get(target);
444
+ if (repairStartedAt === undefined) {
445
+ if (hasBleKeyMissingSince(target, linkStartedAt)) {
446
+ fail(bondInvalid());
447
+ return;
448
+ }
449
+ if (dropAt !== undefined && dropAt >= linkStartedAt) {
450
+ finish('unresolved');
451
+ return;
452
+ }
453
+ if (!record || record.at < linkStartedAt)
454
+ return;
455
+ if (isEncrypted(record)) {
456
+ finish('encrypted');
457
+ return;
458
+ }
459
+ if (record.status !== HCI_PIN_OR_KEY_MISSING) {
460
+ finish('unresolved');
461
+ return;
462
+ }
463
+ repairStartedAt = record.at;
464
+ onRepairStarted === null || onRepairStarted === void 0 ? void 0 : onRepairStarted();
465
+ arm(repairTimeoutMs, () => fail(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'Bluetooth pairing timed out', {
466
+ phase: 'bond',
467
+ reason: 'timeout',
468
+ })));
469
+ return;
470
+ }
471
+ if (hasBleKeyMissingSince(target, repairStartedAt)) {
472
+ fail(bondInvalid());
473
+ return;
474
+ }
475
+ if (record && record.at > repairStartedAt && isEncrypted(record)) {
476
+ finish('re-paired');
477
+ return;
478
+ }
479
+ if (!droppedDuringRepair && dropAt !== undefined && dropAt >= repairStartedAt) {
480
+ droppedDuringRepair = true;
481
+ arm(keyMissingGraceMs, () => fail(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected)));
482
+ }
483
+ };
484
+ const onLinkEvent = id => {
485
+ if (id === target)
486
+ evaluate();
487
+ };
488
+ const onAbort = () => fail(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected));
489
+ listeners.add(onLinkEvent);
490
+ const cleanupKeyMissing = onBleKeyMissing(target, evaluate);
491
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onAbort, { once: true });
492
+ arm(resultTimeoutMs, () => finish('unresolved'));
493
+ evaluate();
494
+ });
495
+ };
496
+
497
+ const IOS_PERIPHERAL_DISCONNECTED$1 = 7;
498
+ const IOS_PEER_TERMINATION_LINK_WINDOW_MS = 10000;
499
+ const IOS_PEER_TERMINATION_REPEAT_WINDOW_MS = 60000;
500
+ const isIosPeerTerminationError = (error) => (error === null || error === void 0 ? void 0 : error.iosErrorCode) ===
501
+ IOS_PERIPHERAL_DISCONNECTED$1;
502
+ class IosPeerTerminationTracker {
503
+ constructor() {
504
+ this.linkStartedAt = new Map();
505
+ this.terminatedAt = new Map();
506
+ this.evidenceAt = new Map();
507
+ }
508
+ attemptStarted(deviceId) {
509
+ this.linkStartedAt.delete(deviceId);
510
+ this.terminatedAt.delete(deviceId);
511
+ }
512
+ linkStarted(deviceId) {
513
+ this.linkStartedAt.set(deviceId, Date.now());
514
+ this.terminatedAt.delete(deviceId);
515
+ }
516
+ note(deviceId, error) {
517
+ if (!isIosPeerTerminationError(error))
518
+ return;
519
+ if (!this.terminatedAt.has(deviceId))
520
+ this.terminatedAt.set(deviceId, Date.now());
521
+ }
522
+ linkProven(deviceId) {
523
+ this.forget(deviceId);
524
+ }
525
+ forget(deviceId) {
526
+ this.linkStartedAt.delete(deviceId);
527
+ this.terminatedAt.delete(deviceId);
528
+ this.evidenceAt.delete(deviceId);
529
+ }
530
+ attemptFailed(deviceId) {
531
+ const startedAt = this.linkStartedAt.get(deviceId);
532
+ const terminatedAt = this.terminatedAt.get(deviceId);
533
+ const previous = this.evidenceAt.get(deviceId);
534
+ this.forget(deviceId);
535
+ if (startedAt === undefined ||
536
+ terminatedAt === undefined ||
537
+ terminatedAt - startedAt > IOS_PEER_TERMINATION_LINK_WINDOW_MS) {
538
+ return false;
242
539
  }
243
- else {
244
- pendingError = undefined;
540
+ if (previous !== undefined &&
541
+ terminatedAt - previous <= IOS_PEER_TERMINATION_REPEAT_WINDOW_MS) {
542
+ return true;
245
543
  }
246
- }, true);
247
- removeSubscription = () => subscription.remove();
248
- if (done) {
249
- removeSubscription();
544
+ this.evidenceAt.set(deviceId, terminatedAt);
545
+ return false;
250
546
  }
251
- else {
252
- cancelTimeout = timer.timeout(() => {
253
- finish(pendingError !== null && pendingError !== void 0 ? pendingError : hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError));
254
- }, ms);
547
+ reset() {
548
+ this.linkStartedAt.clear();
549
+ this.terminatedAt.clear();
550
+ this.evidenceAt.clear();
255
551
  }
256
- });
552
+ }
257
553
 
258
554
  const BLE_PLX_DEVICE_DISCONNECTED = 201;
259
555
  const IOS_PERIPHERAL_DISCONNECTED = 7;
260
- const nativeErrorText = (error) => [error.reason, error.message]
556
+ const nativeErrorText$1 = (error) => [error.reason, error.message]
261
557
  .filter((value) => typeof value === 'string')
262
558
  .join(' ');
263
559
  const isNativeBleDisconnectError = (error) => {
@@ -266,15 +562,48 @@ const isNativeBleDisconnectError = (error) => {
266
562
  }
267
563
  const nativeError = error;
268
564
  return (nativeError.errorCode === BLE_PLX_DEVICE_DISCONNECTED ||
269
- nativeError.iosErrorCode === IOS_PERIPHERAL_DISCONNECTED ||
270
- nativeErrorText(nativeError).toLowerCase().includes('was disconnected'));
565
+ nativeError.iosErrorCode === IOS_PERIPHERAL_DISCONNECTED);
271
566
  };
272
567
  const toBleDisconnectHardwareError = (error) => {
273
568
  if ((error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleDeviceDisconnected) {
274
569
  return error;
275
570
  }
276
571
  const nativeError = (error !== null && error !== void 0 ? error : {});
277
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected, nativeErrorText(nativeError) || undefined);
572
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected, nativeErrorText$1(nativeError) || undefined);
573
+ };
574
+
575
+ const ATT_INSUFFICIENT_AUTHENTICATION = 5;
576
+ const ATT_INSUFFICIENT_ENCRYPTION = 15;
577
+ const IOS_PEER_REMOVED_PAIRING_INFORMATION = 14;
578
+ const nativeErrorText = (error) => [error.reason, error.message]
579
+ .filter((value) => typeof value === 'string')
580
+ .join(' ');
581
+ const isNativeBleStaleBondError = (error) => {
582
+ if (!error || typeof error !== 'object') {
583
+ return typeof error === 'string' ? hdShared.isBleStaleBondErrorText(error) : false;
584
+ }
585
+ const nativeError = error;
586
+ if (nativeError.attErrorCode === ATT_INSUFFICIENT_AUTHENTICATION ||
587
+ nativeError.attErrorCode === ATT_INSUFFICIENT_ENCRYPTION ||
588
+ nativeError.androidErrorCode === ATT_INSUFFICIENT_AUTHENTICATION ||
589
+ nativeError.androidErrorCode === ATT_INSUFFICIENT_ENCRYPTION ||
590
+ nativeError.iosErrorCode === IOS_PEER_REMOVED_PAIRING_INFORMATION) {
591
+ return true;
592
+ }
593
+ return hdShared.isBleStaleBondErrorText(nativeErrorText(nativeError));
594
+ };
595
+ const toBleStaleBondHardwareError = (error) => {
596
+ if (hdShared.isBleStaleBondHardwareError(error)) {
597
+ return error;
598
+ }
599
+ const nativeError = (error !== null && error !== void 0 ? error : {});
600
+ const text = nativeErrorText(nativeError);
601
+ const normalizedText = text.toLowerCase();
602
+ const peerRemoved = nativeError.iosErrorCode === IOS_PEER_REMOVED_PAIRING_INFORMATION ||
603
+ normalizedText.includes('peer removed pairing information');
604
+ return hdShared.ERRORS.TypedError(peerRemoved
605
+ ? hdShared.HardwareErrorCode.BlePeerRemovedPairingInformation
606
+ : hdShared.HardwareErrorCode.BleDeviceBondError, text || undefined);
278
607
  };
279
608
 
280
609
  const isHeaderChunk = (chunk) => {
@@ -368,7 +697,8 @@ const isWedgedWriteError = (error) => (error === null || error === void 0 ? void
368
697
  error.message.startsWith(WEDGED_WRITE_MESSAGE);
369
698
  const shouldRethrowProtocolProbeError = (error) => {
370
699
  const code = error === null || error === void 0 ? void 0 : error.errorCode;
371
- return (isNativeBleDisconnectError(error) ||
700
+ return (hdShared.isBleStaleBondHardwareError(error) ||
701
+ isNativeBleDisconnectError(error) ||
372
702
  code === hdShared.HardwareErrorCode.BleDeviceNotBonded ||
373
703
  code === hdShared.HardwareErrorCode.BleDeviceBondedCanceled ||
374
704
  code === hdShared.HardwareErrorCode.BleDeviceDisconnected ||
@@ -376,6 +706,18 @@ const shouldRethrowProtocolProbeError = (error) => {
376
706
  code === hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure ||
377
707
  code === hdShared.HardwareErrorCode.BleWriteCharacteristicError);
378
708
  };
709
+ const ANDROID_KEY_MISSING_LINK_WINDOW_MS = 10000;
710
+ const ANDROID_KEY_MISSING_GRACE_MS = 500;
711
+ const ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS = 1500;
712
+ const ANDROID_SYSTEM_REPAIR_TIMEOUT_MS = 35000;
713
+ const isAndroidLinkLossError = (error) => {
714
+ const code = error === null || error === void 0 ? void 0 : error.errorCode;
715
+ return (isNativeBleDisconnectError(error) ||
716
+ code === hdShared.HardwareErrorCode.BleDeviceNotBonded ||
717
+ code === hdShared.HardwareErrorCode.BleDeviceDisconnected ||
718
+ code === hdShared.HardwareErrorCode.BleCharacteristicNotifyError ||
719
+ code === hdShared.HardwareErrorCode.BleConnectedError);
720
+ };
379
721
  const BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
380
722
  const DEVICE_SCAN_TIMEOUT_MS = 3000;
381
723
  const IOS_NOTIFY_READY_DELAY_MS = 150;
@@ -535,14 +877,21 @@ const resolveNegotiatedMtu = (device, cancelTransaction) => shouldRefreshNegotia
535
877
  ? requestNegotiatedMtu(device, 'connected', 0, cancelTransaction)
536
878
  : Promise.resolve({ device, timedOut: false });
537
879
  function remapError(error) {
538
- var _a, _b;
539
- if (isNativeBleDisconnectError(error)) {
540
- throw toBleDisconnectHardwareError(error);
880
+ var _a;
881
+ if (error instanceof reactNativeBlePlx.BleError) {
882
+ if (isNativeBleStaleBondError(error)) {
883
+ throw toBleStaleBondHardwareError(error);
884
+ }
885
+ if ((error === null || error === void 0 ? void 0 : error.attErrorCode) === 22) {
886
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceBondError);
887
+ }
541
888
  }
542
- if (error instanceof Error && ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('not found'))) {
889
+ if (error instanceof Error &&
890
+ error.message &&
891
+ (error.message.includes('was disconnected') || error.message.includes('not found'))) {
543
892
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
544
893
  }
545
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_b = error.reason) !== null && _b !== void 0 ? _b : error);
894
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_a = error.reason) !== null && _a !== void 0 ? _a : error);
546
895
  }
547
896
  class ReactNativeBleTransport {
548
897
  constructor(options) {
@@ -565,6 +914,10 @@ class ReactNativeBleTransport {
565
914
  this.protocolReprobeFailures = new Map();
566
915
  this.silentDetections = new Map();
567
916
  this.androidGattCacheRefreshes = new Set();
917
+ this.staleBondErrors = new Map();
918
+ this.androidLinkStartedAt = new Map();
919
+ this.iosPeerTermination = new IosPeerTerminationTracker();
920
+ this.acquiringProtocolV2 = new Set();
568
921
  this.protocolV2Assemblers = new Map();
569
922
  this.protocolV2FrameQueues = new Map();
570
923
  this.protocolV2FramePromises = new Map();
@@ -611,6 +964,10 @@ class ReactNativeBleTransport {
611
964
  init(logger, emitter) {
612
965
  setBleLogger(logger);
613
966
  this.emitter = emitter;
967
+ if (reactNative.Platform.OS === 'android') {
968
+ startBleKeyMissingTracking();
969
+ startBleEncryptionTracking();
970
+ }
614
971
  }
615
972
  configure(signedData) {
616
973
  const messages = parseConfigure(signedData);
@@ -833,6 +1190,7 @@ class ReactNativeBleTransport {
833
1190
  const scanStartedAt = Date.now();
834
1191
  let firstDeviceMs;
835
1192
  const blePlxManager = yield this.getPlxManager();
1193
+ yield subscribeBleOn(blePlxManager);
836
1194
  if (reactNative.Platform.OS === 'android' && reactNative.Platform.Version >= 31) {
837
1195
  Log === null || Log === void 0 ? void 0 : Log.debug('requesting permissions, please wait...');
838
1196
  const resultConnect = yield reactNative.PermissionsAndroid.requestMultiple([
@@ -845,7 +1203,6 @@ class ReactNativeBleTransport {
845
1203
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError);
846
1204
  }
847
1205
  }
848
- yield subscribeBleOn(blePlxManager);
849
1206
  if (this.stopped)
850
1207
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
851
1208
  return new Promise((resolve, reject) => {
@@ -886,14 +1243,11 @@ class ReactNativeBleTransport {
886
1243
  var _a, _b;
887
1244
  if (error) {
888
1245
  Log === null || Log === void 0 ? void 0 : Log.debug('ble scan error: ', error);
889
- if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff) {
890
- finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePoweredOff));
891
- }
892
- else if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothUnsupported) {
893
- finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleUnsupported));
1246
+ if ([reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff, reactNativeBlePlx.BleErrorCode.BluetoothInUnknownState].includes(error.errorCode)) {
1247
+ finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
894
1248
  }
895
1249
  else if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothUnauthorized) {
896
- finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
1250
+ finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleLocationError));
897
1251
  }
898
1252
  else if (error.errorCode === reactNativeBlePlx.BleErrorCode.LocationServicesDisabled) {
899
1253
  finishScan(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleLocationServicesDisabled));
@@ -1000,7 +1354,14 @@ class ReactNativeBleTransport {
1000
1354
  if (!uuid) {
1001
1355
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
1002
1356
  }
1003
- return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
1357
+ return this.runLifecycleOperation(uuid, () => __awaiter(this, void 0, void 0, function* () {
1358
+ try {
1359
+ return yield this.acquireUnlocked(input);
1360
+ }
1361
+ catch (error) {
1362
+ throw this.resolveIosBondInvalid(input, yield this.resolveAndroidBondInvalid(uuid, error));
1363
+ }
1364
+ }));
1004
1365
  });
1005
1366
  }
1006
1367
  acquireUnlocked(input) {
@@ -1009,6 +1370,10 @@ class ReactNativeBleTransport {
1009
1370
  if (this.stopped)
1010
1371
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1011
1372
  const { uuid, forceCleanRunPromise, expectedProtocol, skipProtocolProbe } = input;
1373
+ this.iosPeerTermination.attemptStarted(uuid);
1374
+ const shouldMapProtocolV2StaleBond = expectedProtocol
1375
+ ? expectedProtocol === 'V2'
1376
+ : this.confirmedProtocolV2.has(uuid);
1012
1377
  const cachedTransport = transportCache[uuid];
1013
1378
  if (skipProtocolProbe && !cachedTransport && this.blePlxManager) {
1014
1379
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] refresh uncached BLE connection for firmware install:', uuid);
@@ -1052,6 +1417,7 @@ class ReactNativeBleTransport {
1052
1417
  }
1053
1418
  let device = null;
1054
1419
  const isAndroid = reactNative.Platform.OS === 'android';
1420
+ let androidBondedBeforeConnect = false;
1055
1421
  const refreshAndroidGattCache = isAndroid && (!!skipProtocolProbe || this.androidGattCacheRefreshes.has(uuid));
1056
1422
  let nativeConnectOptions = connectOptions;
1057
1423
  if (isAndroid) {
@@ -1079,10 +1445,16 @@ class ReactNativeBleTransport {
1079
1445
  if (this.stopped)
1080
1446
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1081
1447
  if (reactNative.Platform.OS === 'android') {
1448
+ startBleKeyMissingTracking();
1449
+ startBleEncryptionTracking();
1450
+ this.androidLinkStartedAt.delete(uuid);
1082
1451
  try {
1083
1452
  const bondState = yield pairDevice(uuid);
1453
+ androidBondedBeforeConnect = !bondState.bonding && bondState.bonded;
1084
1454
  if (bondState.bonding) {
1085
- yield onDeviceBondState(uuid, this.bondAbortController.signal);
1455
+ yield onDeviceBondState(uuid, this.bondAbortController.signal, {
1456
+ systemInitiated: bondState.initiated === false,
1457
+ });
1086
1458
  }
1087
1459
  else if (!bondState.bonded) {
1088
1460
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
@@ -1094,6 +1466,7 @@ class ReactNativeBleTransport {
1094
1466
  }));
1095
1467
  throw error;
1096
1468
  }
1469
+ this.androidLinkStartedAt.set(uuid, Date.now());
1097
1470
  }
1098
1471
  if (this.stopped)
1099
1472
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
@@ -1248,7 +1621,16 @@ class ReactNativeBleTransport {
1248
1621
  if (protocolHint) {
1249
1622
  this.deviceProtocolHints.set(uuid, protocolHint);
1250
1623
  }
1624
+ if (shouldMapProtocolV2StaleBond) {
1625
+ this.acquiringProtocolV2.add(uuid);
1626
+ }
1627
+ let linkEncryption;
1251
1628
  try {
1629
+ if (androidBondedBeforeConnect && !skipProtocolProbe) {
1630
+ linkEncryption = yield this.waitForAndroidLinkSecurity(uuid);
1631
+ if (this.stopped)
1632
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1633
+ }
1252
1634
  yield this.installTransportForAcquire(uuid, acquiredDevice, {
1253
1635
  writeCharacteristic,
1254
1636
  notifyCharacteristic,
@@ -1282,17 +1664,24 @@ class ReactNativeBleTransport {
1282
1664
  }));
1283
1665
  if (this.stopped)
1284
1666
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1667
+ this.iosPeerTermination.linkProven(uuid);
1285
1668
  const currentTransport = transportCache[uuid];
1286
1669
  if (!currentTransport) {
1287
1670
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1288
1671
  }
1289
1672
  this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
1673
+ if (linkEncryption === 'unresolved') {
1674
+ markBleLinkEncrypted(uuid);
1675
+ }
1290
1676
  return { uuid, protocolType };
1291
1677
  }
1292
1678
  catch (error) {
1293
1679
  yield this.disconnectUnlocked(uuid);
1294
1680
  throw error;
1295
1681
  }
1682
+ finally {
1683
+ this.acquiringProtocolV2.delete(uuid);
1684
+ }
1296
1685
  });
1297
1686
  }
1298
1687
  _monitorCharacteristic(characteristic, uuid, monitorToken, notifyTransactionId) {
@@ -1302,6 +1691,8 @@ class ReactNativeBleTransport {
1302
1691
  var _a, _b, _c, _d, _e, _f;
1303
1692
  const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
1304
1693
  if (error) {
1694
+ if (isCurrentMonitor)
1695
+ this.noteIosLinkError(uuid, 'notify', error);
1305
1696
  Log === null || Log === void 0 ? void 0 : Log.debug(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
1306
1697
  if (this.firmwareUploadWriteRecoveryIds.has(uuid)) {
1307
1698
  Log === null || Log === void 0 ? void 0 : Log.debug('notify error ignored during FirmwareUpload write recovery: ', uuid);
@@ -1311,6 +1702,11 @@ class ReactNativeBleTransport {
1311
1702
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
1312
1703
  return;
1313
1704
  }
1705
+ if ((this.getActiveProtocol(uuid) === 'V2' || this.acquiringProtocolV2.has(uuid)) &&
1706
+ isNativeBleStaleBondError(error)) {
1707
+ this.rememberStaleBondError(uuid, toBleStaleBondHardwareError(error));
1708
+ return;
1709
+ }
1314
1710
  if (reactNative.Platform.OS === 'android' && isStaleGattTableNotifyReason(error.reason)) {
1315
1711
  this.androidGattCacheRefreshes.add(uuid);
1316
1712
  }
@@ -1439,6 +1835,8 @@ class ReactNativeBleTransport {
1439
1835
  this.protocolV2HighVolumeLogSignatures.delete(uuid);
1440
1836
  this.deviceProtocol.delete(uuid);
1441
1837
  this.probingProtocols.delete(uuid);
1838
+ this.staleBondErrors.delete(uuid);
1839
+ this.acquiringProtocolV2.delete(uuid);
1442
1840
  (_e = this.protocolV2Assemblers.get(uuid)) === null || _e === void 0 ? void 0 : _e.reset();
1443
1841
  this.protocolV2Assemblers.delete(uuid);
1444
1842
  this.resetProtocolV2Frames(uuid);
@@ -1482,9 +1880,94 @@ class ReactNativeBleTransport {
1482
1880
  if (protocol !== 'V2' && this.runPromise && !forceRun) {
1483
1881
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
1484
1882
  }
1485
- return protocol === 'V2'
1486
- ? this.callProtocolV2(uuid, name, data, options)
1487
- : this.callProtocolV1(uuid, name, data, options);
1883
+ try {
1884
+ return protocol === 'V2'
1885
+ ? yield this.callProtocolV2(uuid, name, data, options)
1886
+ : yield this.callProtocolV1(uuid, name, data, options);
1887
+ }
1888
+ catch (error) {
1889
+ throw yield this.resolveAndroidBondInvalid(uuid, error);
1890
+ }
1891
+ });
1892
+ }
1893
+ resolveAndroidBondInvalid(uuid, error) {
1894
+ return __awaiter(this, void 0, void 0, function* () {
1895
+ if (reactNative.Platform.OS !== 'android' || !isBleKeyMissingSupported())
1896
+ return error;
1897
+ if (hdShared.isBleStaleBondHardwareError(error) || !isAndroidLinkLossError(error))
1898
+ return error;
1899
+ const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1900
+ if (linkStartedAt === undefined ||
1901
+ Date.now() - linkStartedAt > ANDROID_KEY_MISSING_LINK_WINDOW_MS) {
1902
+ return error;
1903
+ }
1904
+ if (!(yield waitForBleKeyMissing(uuid, linkStartedAt, ANDROID_KEY_MISSING_GRACE_MS))) {
1905
+ return error;
1906
+ }
1907
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android key missing, bond is invalid:', uuid);
1908
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
1909
+ phase: 'connect',
1910
+ reason: 'key_missing',
1911
+ });
1912
+ });
1913
+ }
1914
+ noteIosLinkError(uuid, stage, error) {
1915
+ if (reactNative.Platform.OS !== 'ios')
1916
+ return;
1917
+ this.iosPeerTermination.note(uuid, error);
1918
+ if (stage !== 'gatt-setup' && !isNativeBleDisconnectError(error))
1919
+ return;
1920
+ const native = (error !== null && error !== void 0 ? error : {});
1921
+ const code = (value) => typeof value === 'number' || typeof value === 'string' ? value : undefined;
1922
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] iOS operation failed', {
1923
+ connectIdSuffix: uuid.slice(-8),
1924
+ stage,
1925
+ errorCode: code(native.errorCode),
1926
+ iosErrorCode: code(native.iosErrorCode),
1927
+ attErrorCode: code(native.attErrorCode),
1928
+ });
1929
+ }
1930
+ resolveIosBondInvalid(input, error) {
1931
+ if (reactNative.Platform.OS !== 'ios')
1932
+ return error;
1933
+ const { uuid, skipProtocolProbe } = input;
1934
+ if (skipProtocolProbe || hdShared.isBleStaleBondHardwareError(error)) {
1935
+ this.iosPeerTermination.forget(uuid);
1936
+ return error;
1937
+ }
1938
+ if (!this.iosPeerTermination.attemptFailed(uuid))
1939
+ return error;
1940
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] iOS peer ended two new links in a row, bond is invalid:', {
1941
+ connectIdSuffix: uuid.slice(-8),
1942
+ });
1943
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleBondInvalid, undefined, {
1944
+ phase: 'connect',
1945
+ reason: 'peer_disconnected',
1946
+ });
1947
+ }
1948
+ waitForAndroidLinkSecurity(uuid) {
1949
+ return __awaiter(this, void 0, void 0, function* () {
1950
+ const linkStartedAt = this.androidLinkStartedAt.get(uuid);
1951
+ if (linkStartedAt === undefined)
1952
+ return 'unresolved';
1953
+ const waitStartedAt = Date.now();
1954
+ const result = yield waitForAndroidLinkEncryption({
1955
+ deviceId: uuid,
1956
+ linkStartedAt,
1957
+ resultTimeoutMs: ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS,
1958
+ repairTimeoutMs: ANDROID_SYSTEM_REPAIR_TIMEOUT_MS,
1959
+ keyMissingGraceMs: ANDROID_KEY_MISSING_GRACE_MS,
1960
+ signal: this.bondAbortController.signal,
1961
+ onRepairStarted: () => {
1962
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android bond lost, waiting for system re-pairing:', uuid);
1963
+ },
1964
+ });
1965
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android link encryption', {
1966
+ connectIdSuffix: uuid.slice(-8),
1967
+ result,
1968
+ waitedMs: Date.now() - waitStartedAt,
1969
+ });
1970
+ return result;
1488
1971
  });
1489
1972
  }
1490
1973
  callProtocolV1(uuid, name, data, options) {
@@ -1700,6 +2183,10 @@ class ReactNativeBleTransport {
1700
2183
  this.androidPriorityResetTimers.forEach(timeout => clearTimeout(timeout));
1701
2184
  this.androidPriorityResetTimers.clear();
1702
2185
  this.androidHighPriorityDevices.clear();
2186
+ this.androidLinkStartedAt.clear();
2187
+ this.iosPeerTermination.reset();
2188
+ stopBleKeyMissingTracking();
2189
+ stopBleEncryptionTracking();
1703
2190
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceDisconnected);
1704
2191
  (_a = this.runPromise) === null || _a === void 0 ? void 0 : _a.reject(error);
1705
2192
  this.runPromise = null;
@@ -1760,6 +2247,7 @@ class ReactNativeBleTransport {
1760
2247
  }
1761
2248
  this.deviceProtocol.delete(session);
1762
2249
  this.probingProtocols.delete(session);
2250
+ this.staleBondErrors.delete(session);
1763
2251
  this.deviceProtocolHints.delete(session);
1764
2252
  this.sessionProtocols.delete(session);
1765
2253
  this.protocolReprobeFailures.delete(session);
@@ -1952,6 +2440,7 @@ class ReactNativeBleTransport {
1952
2440
  }),
1953
2441
  ]);
1954
2442
  succeeded = true;
2443
+ this.iosPeerTermination.linkStarted(uuid);
1955
2444
  return result;
1956
2445
  }
1957
2446
  catch (error) {
@@ -1998,15 +2487,16 @@ class ReactNativeBleTransport {
1998
2487
  return result;
1999
2488
  }
2000
2489
  catch (error) {
2490
+ this.noteIosLinkError(uuid, 'gatt-setup', error);
2491
+ if (reactNative.Platform.OS === 'ios' && isNativeBleStaleBondError(error)) {
2492
+ throw toBleStaleBondHardwareError(error);
2493
+ }
2001
2494
  if (timedOut || isNativeOperationTimeoutError(error)) {
2002
2495
  const resetManager = this.abandonStalledConnection(uuid, timedOut ? 'gatt-backstop' : 'gatt-native');
2003
2496
  if (resetManager) {
2004
2497
  throw this.createWedgedBleSetupError();
2005
2498
  }
2006
2499
  }
2007
- if (isNativeBleDisconnectError(error)) {
2008
- throw toBleDisconnectHardwareError(error);
2009
- }
2010
2500
  if (reactNative.Platform.OS === 'android' && isMissingGattShapeError(error)) {
2011
2501
  this.androidGattCacheRefreshes.add(uuid);
2012
2502
  }
@@ -2040,6 +2530,8 @@ class ReactNativeBleTransport {
2040
2530
  }
2041
2531
  this.deviceProtocol.delete(uuid);
2042
2532
  this.probingProtocols.delete(uuid);
2533
+ this.staleBondErrors.delete(uuid);
2534
+ this.acquiringProtocolV2.delete(uuid);
2043
2535
  this.protocolV2Assemblers.delete(uuid);
2044
2536
  this.resetProtocolV2Frames(uuid);
2045
2537
  if (timeouts >= BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD) {
@@ -2077,6 +2569,7 @@ class ReactNativeBleTransport {
2077
2569
  this.writeTimeoutCounts.delete(uuid);
2078
2570
  }
2079
2571
  catch (error) {
2572
+ this.noteIosLinkError(uuid, 'write', error);
2080
2573
  if (timedOut) {
2081
2574
  if (isCurrentOwner && !isCurrentOwner()) {
2082
2575
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE write timed out, link kept:', uuid);
@@ -2109,6 +2602,8 @@ class ReactNativeBleTransport {
2109
2602
  }
2110
2603
  this.deviceProtocol.delete(uuid);
2111
2604
  this.probingProtocols.delete(uuid);
2605
+ this.staleBondErrors.delete(uuid);
2606
+ this.acquiringProtocolV2.delete(uuid);
2112
2607
  this.protocolV2Assemblers.delete(uuid);
2113
2608
  this.resetProtocolV2Frames(uuid);
2114
2609
  if (timeouts >= BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD) {
@@ -2153,6 +2648,8 @@ class ReactNativeBleTransport {
2153
2648
  });
2154
2649
  this.deviceProtocol.clear();
2155
2650
  this.probingProtocols.clear();
2651
+ this.staleBondErrors.clear();
2652
+ this.acquiringProtocolV2.clear();
2156
2653
  this.sessionProtocols.clear();
2157
2654
  this.protocolReprobeFailures.clear();
2158
2655
  this.silentDetections.clear();
@@ -2205,6 +2702,9 @@ class ReactNativeBleTransport {
2205
2702
  });
2206
2703
  return 'V1';
2207
2704
  }
2705
+ if (expectedProtocol === 'V2' || this.acquiringProtocolV2.has(uuid)) {
2706
+ this.throwIfStaleBondError(uuid);
2707
+ }
2208
2708
  if (expectedProtocol === 'V2') {
2209
2709
  if (yield this.probeProtocolV2(uuid)) {
2210
2710
  this.deviceProtocol.set(uuid, 'V2');
@@ -2363,6 +2863,7 @@ class ReactNativeBleTransport {
2363
2863
  }
2364
2864
  this.probingProtocols.set(uuid, 'V2');
2365
2865
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
2866
+ this.throwIfStaleBondError(uuid);
2366
2867
  const detected = yield transport.probeProtocolV2({
2367
2868
  call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
2368
2869
  timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
@@ -2434,6 +2935,19 @@ class ReactNativeBleTransport {
2434
2935
  framePromise.reject(error);
2435
2936
  }
2436
2937
  }
2938
+ rememberStaleBondError(uuid, error) {
2939
+ this.staleBondErrors.set(uuid, error);
2940
+ this.rejectProtocolV2Frames(uuid, error);
2941
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
2942
+ this.runPromise.reject(error);
2943
+ }
2944
+ }
2945
+ throwIfStaleBondError(uuid) {
2946
+ const error = this.staleBondErrors.get(uuid);
2947
+ if (error) {
2948
+ throw error;
2949
+ }
2950
+ }
2437
2951
  readProtocolV2Frame(uuid) {
2438
2952
  return __awaiter(this, void 0, void 0, function* () {
2439
2953
  const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
@@ -2482,6 +2996,11 @@ class ReactNativeBleTransport {
2482
2996
  return;
2483
2997
  }
2484
2998
  catch (error) {
2999
+ if (isNativeBleStaleBondError(error) || hdShared.isBleStaleBondHardwareError(error)) {
3000
+ const bondError = toBleStaleBondHardwareError(error);
3001
+ this.rememberStaleBondError(uuid, bondError);
3002
+ throw bondError;
3003
+ }
2485
3004
  if (isNativeBleDisconnectError(error)) {
2486
3005
  throw toBleDisconnectHardwareError(error);
2487
3006
  }
@@ -2707,8 +3226,12 @@ class ReactNativeBleTransport {
2707
3226
  }
2708
3227
  }
2709
3228
 
3229
+ exports.ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS = ANDROID_ENCRYPTION_RESULT_TIMEOUT_MS;
3230
+ exports.ANDROID_KEY_MISSING_GRACE_MS = ANDROID_KEY_MISSING_GRACE_MS;
3231
+ exports.ANDROID_KEY_MISSING_LINK_WINDOW_MS = ANDROID_KEY_MISSING_LINK_WINDOW_MS;
2710
3232
  exports.ANDROID_LINK_DROP_QUIET_MS = ANDROID_LINK_DROP_QUIET_MS;
2711
3233
  exports.ANDROID_MTU_EXCHANGE_TIMEOUT_MS = ANDROID_MTU_EXCHANGE_TIMEOUT_MS;
3234
+ exports.ANDROID_SYSTEM_REPAIR_TIMEOUT_MS = ANDROID_SYSTEM_REPAIR_TIMEOUT_MS;
2712
3235
  exports.BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD;
2713
3236
  exports.BLE_CONNECT_TIMEOUT_MS = BLE_CONNECT_TIMEOUT_MS;
2714
3237
  exports.BLE_GATT_SETUP_TIMEOUT_MS = BLE_GATT_SETUP_TIMEOUT_MS;