@doorstepai/dropoff-sdk 2.1.2 → 2.2.2

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 (43) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +308 -41
  3. package/android/build.gradle +5 -1
  4. package/android/src/main/java/com/doorstepai/dropoffsdk/DoorstepAIModule.kt +566 -2
  5. package/ios/DoorstepAI.mm +12 -2
  6. package/ios/DoorstepAI.swift +151 -2
  7. package/ios/DoorstepDropoffSDK.xcframework/Info.plist +5 -5
  8. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/DoorstepDropoffSDK +0 -0
  9. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.abi.json +10582 -5745
  10. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.private.swiftinterface +95 -4
  11. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  12. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios.swiftinterface +95 -4
  13. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/DoorstepDropoffSDK.framework/_CodeSignature/CodeResources +10 -10
  14. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/DWARF/DoorstepDropoffSDK +0 -0
  15. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/aarch64/DoorstepDropoffSDK.yml +3833 -2687
  16. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/DoorstepDropoffSDK +0 -0
  17. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.abi.json +10582 -5745
  18. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.private.swiftinterface +95 -4
  19. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  20. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/arm64-apple-ios-simulator.swiftinterface +95 -4
  21. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.abi.json +10582 -5745
  22. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.private.swiftinterface +95 -4
  23. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  24. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/Modules/DoorstepDropoffSDK.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +95 -4
  25. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/DoorstepDropoffSDK.framework/_CodeSignature/CodeResources +20 -20
  26. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/DWARF/DoorstepDropoffSDK +0 -0
  27. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/aarch64/DoorstepDropoffSDK.yml +3833 -2687
  28. package/ios/DoorstepDropoffSDK.xcframework/ios-arm64_x86_64-simulator/dSYMs/DoorstepDropoffSDK.framework.dSYM/Contents/Resources/Relocations/x86_64/DoorstepDropoffSDK.yml +3802 -2674
  29. package/lib/module/DoorstepAI.js +425 -12
  30. package/lib/module/DoorstepAI.js.map +1 -1
  31. package/lib/module/RootDoorstepAI.js +88 -26
  32. package/lib/module/RootDoorstepAI.js.map +1 -1
  33. package/lib/module/index.js.map +1 -1
  34. package/lib/typescript/src/DoorstepAI.d.ts +349 -7
  35. package/lib/typescript/src/DoorstepAI.d.ts.map +1 -1
  36. package/lib/typescript/src/RootDoorstepAI.d.ts +31 -3
  37. package/lib/typescript/src/RootDoorstepAI.d.ts.map +1 -1
  38. package/lib/typescript/src/index.d.ts +1 -1
  39. package/lib/typescript/src/index.d.ts.map +1 -1
  40. package/package.json +2 -1
  41. package/src/DoorstepAI.tsx +575 -23
  42. package/src/RootDoorstepAI.tsx +130 -47
  43. package/src/index.tsx +10 -0
@@ -1,5 +1,10 @@
1
1
  package com.doorstepai.dropoffsdk
2
2
 
3
+ import android.content.pm.PackageManager
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import androidx.core.content.ContextCompat
7
+ import com.facebook.react.bridge.LifecycleEventListener
3
8
  import com.facebook.react.bridge.NativeModule
4
9
  import com.facebook.react.bridge.ReactApplicationContext
5
10
  import com.facebook.react.bridge.ReactContext
@@ -10,13 +15,19 @@ import com.doorstepai.sdks.tracking.DoorstepAI
10
15
  import com.doorstepai.sdks.tracking.AddressType
11
16
  import com.doorstepai.sdks.tracking.DropoffType
12
17
  import com.doorstepai.sdks.tracking.LatLngObject
18
+ import com.facebook.react.bridge.Dynamic
13
19
  import com.facebook.react.bridge.ReadableMap
14
20
  import com.facebook.react.bridge.ReadableArray
21
+ import com.facebook.react.bridge.ReadableType
15
22
  import com.facebook.react.bridge.WritableMap
16
23
  import com.facebook.react.bridge.Arguments
24
+ import com.facebook.react.bridge.UiThreadUtil
17
25
  import com.facebook.react.modules.core.DeviceEventManagerModule
18
26
  import com.doorstepai.sdks.tracking.DeliveryStop
19
27
  import com.doorstepai.sdks.tracking.RouteGeofenceOptions
28
+ import com.doorstepai.sdks.tracking.DoorstepPermission
29
+ import com.doorstepai.sdks.tracking.DoorstepPermissionState
30
+ import com.doorstepai.sdks.tracking.DoorstepPermissionStatus
20
31
  import kotlinx.coroutines.Dispatchers
21
32
  import kotlinx.coroutines.CoroutineScope
22
33
  import kotlinx.coroutines.SupervisorJob
@@ -212,11 +223,21 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
212
223
  }
213
224
  }
214
225
 
226
+ /**
227
+ * Resolves on the SDK's own callback rather than immediately. The previous
228
+ * version discarded the `Result` and always resolved, so a rejected event —
229
+ * unknown deliveryId, no session — reached JS as a success.
230
+ */
215
231
  @ReactMethod
216
232
  fun newEvent(eventName: String, deliveryId: String, timestamp: Double?, promise: Promise) {
217
233
  try {
218
- DoorstepAI.newEvent(eventName, deliveryId, timestamp) { /* Callback not needed here */ }
219
- promise.resolve("Event $eventName triggered for $deliveryId")
234
+ DoorstepAI.newEvent(eventName, deliveryId, timestamp) { result ->
235
+ result.onSuccess { message ->
236
+ promise.resolve(message)
237
+ }.onFailure { error ->
238
+ promise.reject("EVENT_CREATION_ERROR", error.message ?: "Failed to save event")
239
+ }
240
+ }
220
241
  } catch (e: Exception) {
221
242
  promise.reject("EVENT_CREATION_ERROR", e.message ?: "Failed to save event")
222
243
  }
@@ -258,6 +279,27 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
258
279
  return true
259
280
  }
260
281
 
282
+ @ReactMethod(isBlockingSynchronousMethod = true)
283
+ fun setDoorstepGoApiKey(key: String): Boolean {
284
+ DoorstepAI.setDoorstepGoApiKey(key)
285
+ return true
286
+ }
287
+
288
+ /**
289
+ * Re-registers the raw-GNSS callbacks. Some devices (the S22U among them) stop
290
+ * delivering measurements without reporting an error; this is the SDK's recovery
291
+ * hook for that. Android-only by nature — iOS has no raw-GNSS API at all.
292
+ */
293
+ @ReactMethod
294
+ fun retryGnssCallbacks(promise: Promise) {
295
+ try {
296
+ DoorstepAI.retryGnssCallbacks()
297
+ promise.resolve(true)
298
+ } catch (e: Exception) {
299
+ promise.reject("GNSS_RETRY_ERROR", e.message ?: "Failed to retry GNSS callbacks")
300
+ }
301
+ }
302
+
261
303
  @ReactMethod
262
304
  fun enableDevMode(promise: Promise) {
263
305
  CoroutineScope(Dispatchers.IO).launch {
@@ -292,6 +334,459 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
292
334
  }
293
335
  }
294
336
 
337
+ // ---- Runtime permissions ----
338
+ // Pass-through to the SDK's own permission API. The SDK owns the permission list
339
+ // and the request ordering; the JS layer this replaced kept its own list and
340
+ // asked for ACCESS_FINE_LOCATION with no ACCESS_COARSE_LOCATION, which Android
341
+ // 12+ ignores outright, and never asked for ACCESS_BACKGROUND_LOCATION at all.
342
+ //
343
+ // An absent `includeBluetooth` means "whatever native defaults to", so the
344
+ // branches below omit the argument rather than restating a literal — the default
345
+ // is not the same on every method (true when requesting, false when checking).
346
+
347
+ /**
348
+ * `Dynamic` rather than `Boolean?` because RN's boxed-Boolean argument extractor
349
+ * calls `ReadableArray.getBoolean`, which throws on a JS `null` — "unset" cannot
350
+ * be expressed as a nullable Boolean parameter. Read it before leaving the
351
+ * @ReactMethod body: Dynamic instances are pooled and recycled.
352
+ */
353
+ private fun Dynamic.optionalBoolean(): Boolean? =
354
+ if (isNull || type != ReadableType.Boolean) null else asBoolean()
355
+
356
+ @ReactMethod
357
+ fun getRequiredPermissions(includeBluetooth: Dynamic, promise: Promise) {
358
+ try {
359
+ val bluetooth = includeBluetooth.optionalBoolean()
360
+ val permissions =
361
+ if (bluetooth == null) DoorstepAI.getRequiredPermissions()
362
+ else DoorstepAI.getRequiredPermissions(bluetooth)
363
+ val arr = Arguments.createArray()
364
+ permissions.forEach { arr.pushString(it) }
365
+ promise.resolve(arr)
366
+ } catch (e: Exception) {
367
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read required permissions")
368
+ }
369
+ }
370
+
371
+ @ReactMethod
372
+ fun hasRequiredPermissions(includeBluetooth: Dynamic, promise: Promise) {
373
+ try {
374
+ val bluetooth = includeBluetooth.optionalBoolean()
375
+ promise.resolve(
376
+ if (bluetooth == null) DoorstepAI.hasRequiredPermissions(reactContext)
377
+ else DoorstepAI.hasRequiredPermissions(reactContext, bluetooth)
378
+ )
379
+ } catch (e: Exception) {
380
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to check required permissions")
381
+ }
382
+ }
383
+
384
+ @ReactMethod
385
+ fun hasBackgroundLocationPermission(promise: Promise) {
386
+ try {
387
+ promise.resolve(DoorstepAI.hasBackgroundLocationPermission(reactContext))
388
+ } catch (e: Exception) {
389
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to check background location permission")
390
+ }
391
+ }
392
+
393
+ // ---- checkPermissions / requestPermissions (the whitelist surface) ----
394
+ //
395
+ // Pass-throughs to the SDK's whitelist permission API. The SDK owns the buckets,
396
+ // the eight-state vocabulary and the request plan — including the two rules a
397
+ // wrapper must never re-derive: LOCATION_ALWAYS is requested only alone and only
398
+ // after foreground location is granted, and a permanently-denied bucket is not
399
+ // asked at all (the OS would answer with an instant denial and no dialog).
400
+ //
401
+ // What used to live here was a hand-rolled `location`/`motion`/`bluetooth`
402
+ // bucketing over `getRequiredPermissions()` plus a three-value state machine.
403
+ // It could not express WHEN_IN_USE_ONLY (foreground held, background not — the
404
+ // state in which background collection and route geofencing silently do not
405
+ // work), nor NOT_DECLARED (a host-manifest omission, which is not a user
406
+ // refusal). Both are now reported verbatim from native.
407
+
408
+ /** The public bucket names, in native's own `wireName` spelling. */
409
+ private fun parseWhitelist(arr: ReadableArray?): Set<DoorstepPermission> {
410
+ // An ABSENT array means "no whitelist" — every bucket. An EMPTY array is a
411
+ // different statement: the caller narrowed it down to nothing, and answering
412
+ // that with "then I'll ask for everything" would invert their intent.
413
+ if (arr == null) return DoorstepPermission.ALL
414
+ val out = linkedSetOf<DoorstepPermission>()
415
+ for (i in 0 until arr.size()) {
416
+ val name = if (arr.getType(i) == ReadableType.String) arr.getString(i) else null
417
+ DoorstepPermission.fromWireName(name ?: continue)?.let { out.add(it) }
418
+ }
419
+ return out
420
+ }
421
+
422
+ /**
423
+ * Legacy three-key view of the eight-state buckets, kept so hosts written
424
+ * against the published 2.x wrapper API keep working. `location` is the
425
+ * foreground bucket — the Always-vs-When-In-Use distinction cannot survive three
426
+ * values, which is exactly what `statuses.locationAlways` is for.
427
+ */
428
+ private fun legacyPermissionsView(
429
+ statuses: Map<DoorstepPermission, DoorstepPermissionStatus>
430
+ ): WritableMap {
431
+ fun collapse(permission: DoorstepPermission): String =
432
+ when (statuses[permission]?.state) {
433
+ DoorstepPermissionState.GRANTED,
434
+ DoorstepPermissionState.WHEN_IN_USE_ONLY,
435
+ DoorstepPermissionState.UNAVAILABLE -> "granted"
436
+ DoorstepPermissionState.NOT_DETERMINED -> "prompt"
437
+ null -> "prompt"
438
+ else -> "denied"
439
+ }
440
+ val m = Arguments.createMap()
441
+ m.putString("location", collapse(DoorstepPermission.LOCATION_WHEN_IN_USE))
442
+ // `motion` answers "can the SDK collect motion data", and on Android the answer
443
+ // is unconditionally yes: the IMU streams (accel, gyro, mag, rotation vectors,
444
+ // barometer) need NO runtime grant. ACTIVITY_RECOGNITION adds only the
445
+ // step-counter/step-detector streams, which is why the SDK leaves it out of
446
+ // `getRequiredPermissions()` and never blocks a session on it.
447
+ //
448
+ // So this is NOT collapsed from the ACTIVITY_RECOGNITION bucket, deliberately.
449
+ // Collapsing it would report `prompt`/`denied` for an optional stream and hand
450
+ // hosts a value that reads like "motion is unavailable" — and host code of the
451
+ // shape `if (permissions.motion === 'granted') startDelivery(...)` would then
452
+ // fail closed across a whole fleet on wrapper upgrade, silently, for a
453
+ // permission this wrapper could not even request before 2.2.0. Read
454
+ // `statuses.activityRecognition` for the real bucket state.
455
+ m.putString("motion", "granted")
456
+ m.putString("bluetooth", collapse(DoorstepPermission.BLUETOOTH_SCAN))
457
+ return m
458
+ }
459
+
460
+ private fun serializeStatuses(
461
+ statuses: Map<DoorstepPermission, DoorstepPermissionStatus>
462
+ ): WritableMap {
463
+ val out = Arguments.createMap()
464
+ statuses.forEach { (permission, status) ->
465
+ val m = Arguments.createMap()
466
+ m.putString("permission", permission.wireName)
467
+ m.putString("state", status.state.name.toWireState())
468
+ m.putString("osStatus", status.osStatus)
469
+ m.putBoolean("canRequest", status.canRequest)
470
+ out.putMap(permission.wireName, m)
471
+ }
472
+ return out
473
+ }
474
+
475
+ /**
476
+ * `WHEN_IN_USE_ONLY` -> `whenInUseOnly`. Android's enum is SCREAMING_SNAKE and
477
+ * iOS's is lowerCamel; the JS surface uses one spelling on both platforms so
478
+ * host code can branch once, and lowerCamel is the one iOS already ships.
479
+ */
480
+ private fun String.toWireState(): String =
481
+ split('_').mapIndexed { i, part ->
482
+ if (i == 0) part.lowercase() else part.lowercase().replaceFirstChar { it.uppercase() }
483
+ }.joinToString("")
484
+
485
+ private fun statusPayload(
486
+ statuses: Map<DoorstepPermission, DoorstepPermissionStatus>
487
+ ): WritableMap {
488
+ val out = Arguments.createMap()
489
+ out.putMap("statuses", serializeStatuses(statuses))
490
+ out.putMap("permissions", legacyPermissionsView(statuses))
491
+ out.putArray("unsupported", Arguments.createArray())
492
+ return out
493
+ }
494
+
495
+ /**
496
+ * Pass an Activity when there is one: it is the only way
497
+ * `shouldShowRequestPermissionRationale` can be consulted, and without that
498
+ * signal a refusal reports as the re-askable DENIED instead of
499
+ * PERMANENTLY_DENIED.
500
+ */
501
+ private fun permissionContext() = currentActivity ?: reactContext
502
+
503
+ @ReactMethod
504
+ fun checkPermissions(permissions: ReadableArray?, promise: Promise) {
505
+ try {
506
+ promise.resolve(statusPayload(DoorstepAI.checkPermissions(permissionContext(), parseWhitelist(permissions))))
507
+ } catch (e: Exception) {
508
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
509
+ }
510
+ }
511
+
512
+ @ReactMethod
513
+ fun checkPermissionsJson(permissions: ReadableArray?, promise: Promise) {
514
+ try {
515
+ promise.resolve(DoorstepAI.checkPermissionsJson(permissionContext(), parseWhitelist(permissions)))
516
+ } catch (e: Exception) {
517
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
518
+ }
519
+ }
520
+
521
+ // In-flight request state. Main-thread confined.
522
+ private var pendingPermissionPromise: Promise? = null
523
+ private var pendingPermissionRequested: Set<String> = emptySet()
524
+ private var pendingPermissionWhitelist: Set<DoorstepPermission> = emptySet()
525
+ private var pendingPermissionPlan: WritableMap? = null
526
+ private var pendingPermissionActivity: java.lang.ref.WeakReference<android.app.Activity>? = null
527
+ private var permissionLifecycleListener: LifecycleEventListener? = null
528
+ private var permissionTimeoutRunnable: Runnable? = null
529
+ private var permissionPollRunnable: Runnable? = null
530
+ private val mainHandler = Handler(Looper.getMainLooper())
531
+
532
+ /**
533
+ * Android half of the cross-platform requester.
534
+ *
535
+ * `options.permissions` is the whitelist and it is honoured exactly: absent
536
+ * requests every bucket, an array requests only those buckets. Everything the
537
+ * native planner declines to ask comes back explained — `alreadyDetermined`,
538
+ * `unavailable`, `deferred` — rather than silently not happening.
539
+ *
540
+ * Resolves a PermissionStatus **after the user has answered**. The grant result
541
+ * of `ActivityCompat.requestPermissions` lands in the Activity's
542
+ * `onRequestPermissionsResult`, which RN does not route back to a module that
543
+ * did not issue the request itself, so the answer is observed three ways:
544
+ * - the host can forward the real result ([notePermissionRequestResult]) —
545
+ * the only path that also lets native tell DENIED from PERMANENTLY_DENIED;
546
+ * - otherwise the dialog pauses the host activity, so a pause→resume pair
547
+ * means it is gone;
548
+ * - a poll catches a grant that somehow arrives without that pair, and a
549
+ * timeout keeps the promise from hanging if the user never answers.
550
+ */
551
+ @ReactMethod
552
+ fun requestPermissions(options: ReadableMap?, promise: Promise) {
553
+ val whitelist =
554
+ if (options != null && options.hasKey("permissions") && !options.isNull("permissions")) {
555
+ parseWhitelist(options.getArray("permissions") ?: Arguments.createArray())
556
+ } else {
557
+ DoorstepPermission.ALL
558
+ }
559
+
560
+ // Same knob as iOS, where it is a native parameter: how long to wait for the
561
+ // user's answer before resolving with the state as it stands. Android's
562
+ // requester has no native timeout, so the wait lives here.
563
+ val answerTimeoutMs =
564
+ if (options != null && options.hasKey("timeoutSeconds") && !options.isNull("timeoutSeconds")) {
565
+ (options.getDouble("timeoutSeconds") * 1000).toLong().coerceAtLeast(1_000L)
566
+ } else {
567
+ PERMISSION_ANSWER_TIMEOUT_MS
568
+ }
569
+
570
+ val activity = currentActivity
571
+ if (activity == null) {
572
+ promise.reject("NO_ACTIVITY", "requestPermissions needs a resumed Activity to prompt from")
573
+ return
574
+ }
575
+ // ActivityCompat.requestPermissions must be issued from the main thread;
576
+ // @ReactMethod bodies run on the native-modules thread.
577
+ UiThreadUtil.runOnUiThread {
578
+ if (pendingPermissionPromise != null) {
579
+ promise.reject(
580
+ "E_PERMISSION_REQUEST_IN_FLIGHT",
581
+ "A permission request is already awaiting the user's answer."
582
+ )
583
+ return@runOnUiThread
584
+ }
585
+ try {
586
+ val result = DoorstepAI.requestPermissions(activity, whitelist)
587
+ android.util.Log.i(
588
+ LOG_TAG,
589
+ "requestPermissions whitelist=${whitelist.map { it.wireName }} " +
590
+ "asked=${result.requested} didRequest=${result.didRequest} " +
591
+ "deferred=${result.deferred.keys.map { it.wireName }}"
592
+ )
593
+ val plan = Arguments.createMap()
594
+ plan.putArray("requested", wireNames(result.requestedBuckets))
595
+ plan.putArray("alreadyDetermined", wireNames(result.alreadyGranted))
596
+ plan.putArray("unavailable", wireNames(result.unavailable))
597
+ plan.putBoolean("didRequest", result.didRequest)
598
+ val deferred = Arguments.createMap()
599
+ result.deferred.forEach { (permission, reason) -> deferred.putString(permission.wireName, reason) }
600
+ plan.putMap("deferred", deferred)
601
+ val androidPermissions = Arguments.createArray()
602
+ result.requested.forEach { androidPermissions.pushString(it) }
603
+ plan.putArray("androidPermissions", androidPermissions)
604
+
605
+ if (!result.didRequest) {
606
+ // No dialog was shown and onRequestPermissionsResult will never fire, so
607
+ // the state on file is already the final answer — do not wait for one.
608
+ promise.resolve(mergePlan(statusPayload(DoorstepAI.checkPermissions(activity, whitelist)), plan))
609
+ return@runOnUiThread
610
+ }
611
+
612
+ pendingPermissionPromise = promise
613
+ pendingPermissionRequested = result.requested.toSet()
614
+ pendingPermissionWhitelist = whitelist
615
+ pendingPermissionPlan = plan
616
+ pendingPermissionActivity = java.lang.ref.WeakReference(activity)
617
+
618
+ // How the answer is observed, in order of how much it actually proves.
619
+ //
620
+ // NOT by the activity-lifecycle pause→resume pair, which is what this code
621
+ // used to do and which is WRONG: on this device the pair arrives ~19 ms
622
+ // after `ActivityCompat.requestPermissions` — RN's own startup lifecycle
623
+ // transitions land on the UI thread right behind the request — so the
624
+ // promise resolved with pre-answer state while the dialog was still on
625
+ // screen (measured, Moto G stylus 5G / API 34). "The host was paused and
626
+ // resumed" is not "the user answered".
627
+ //
628
+ // Window focus is the signal that tracks the dialog: the permission
629
+ // controller takes focus off the host activity for the whole sequence of
630
+ // prompts and hands it back only when the last one is gone. It is a local
631
+ // read, no IPC, and it does not care how many dialogs the OS decided to
632
+ // show.
633
+ val listener = object : LifecycleEventListener {
634
+ override fun onHostResume() = Unit
635
+ override fun onHostPause() = Unit
636
+ override fun onHostDestroy() {
637
+ settlePermissionRequest(answered = false, source = "destroy")
638
+ }
639
+ }
640
+ permissionLifecycleListener = listener
641
+ reactContext.addLifecycleEventListener(listener)
642
+
643
+ val requestedAt = android.os.SystemClock.elapsedRealtime()
644
+ val poll = object : Runnable {
645
+ private var sawFocusLost = false
646
+ override fun run() {
647
+ if (pendingPermissionPromise == null) return
648
+ // A grant is visible: nothing left to wait for, whatever the window is
649
+ // doing. (Not sufficient on its own — a denial never shows up here.)
650
+ if (pendingPermissionRequested.isNotEmpty() &&
651
+ pendingPermissionRequested.all {
652
+ ContextCompat.checkSelfPermission(reactContext, it) ==
653
+ PackageManager.PERMISSION_GRANTED
654
+ }
655
+ ) {
656
+ settlePermissionRequest(answered = true, source = "granted")
657
+ return
658
+ }
659
+ val act = pendingPermissionActivity?.get()
660
+ val hasFocus = act?.hasWindowFocus() ?: true
661
+ if (!hasFocus) {
662
+ sawFocusLost = true
663
+ } else if (sawFocusLost) {
664
+ // Focus left for the dialog and has come back: the sequence is over
665
+ // and anything still not granted was refused.
666
+ settlePermissionRequest(answered = true, source = "focusReturned")
667
+ return
668
+ } else if (android.os.SystemClock.elapsedRealtime() - requestedAt >
669
+ minOf(PERMISSION_DIALOG_GRACE_MS, answerTimeoutMs)
670
+ ) {
671
+ // Focus never left. The OS decided not to show a dialog at all (it
672
+ // does that for an instantly-refused request), so there is no answer
673
+ // coming and waiting out the full timeout would just hang the host.
674
+ settlePermissionRequest(answered = false, source = "noDialog")
675
+ return
676
+ }
677
+ mainHandler.postDelayed(this, PERMISSION_POLL_MS)
678
+ }
679
+ }
680
+ permissionPollRunnable = poll
681
+ mainHandler.postDelayed(poll, PERMISSION_POLL_MS)
682
+
683
+ // Last resort: the user never answers. Resolve with the state as it stands
684
+ // rather than leaving the promise pending forever.
685
+ val timeout = Runnable { settlePermissionRequest(answered = false, source = "timeout") }
686
+ permissionTimeoutRunnable = timeout
687
+ mainHandler.postDelayed(timeout, answerTimeoutMs)
688
+ } catch (e: Exception) {
689
+ pendingPermissionPromise = null
690
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to request permissions")
691
+ }
692
+ }
693
+ }
694
+
695
+ private fun wireNames(permissions: Collection<DoorstepPermission>) =
696
+ Arguments.createArray().also { arr -> permissions.forEach { arr.pushString(it.wireName) } }
697
+
698
+ private fun mergePlan(payload: WritableMap, plan: WritableMap): WritableMap {
699
+ payload.merge(plan)
700
+ return payload
701
+ }
702
+
703
+ /**
704
+ * Forwards a real `onRequestPermissionsResult` to the SDK, from either the host
705
+ * Activity or JS.
706
+ *
707
+ * This is the ONLY way native can tell a refusal it may re-ask (DENIED) from one
708
+ * only Settings can fix (PERMANENTLY_DENIED): after a permanent denial the OS
709
+ * reports exactly what "never asked" reports, and a CANCELLED dialog leaves the
710
+ * same trace as a denial. Native therefore refuses to guess, and neither does
711
+ * this bridge — an empty `grantResults` (which is what a cancelled interaction
712
+ * delivers) is passed through as empty and native records nothing from it.
713
+ *
714
+ * A forwarded result also settles an in-flight [requestPermissions] immediately,
715
+ * which is strictly better than the lifecycle backstop: it is the answer itself
716
+ * rather than the observation that a dialog went away.
717
+ */
718
+ @ReactMethod
719
+ fun notePermissionRequestResult(
720
+ permissions: ReadableArray,
721
+ grantResults: ReadableArray,
722
+ promise: Promise
723
+ ) {
724
+ try {
725
+ val names = (0 until permissions.size()).mapNotNull { permissions.getString(it) }.toTypedArray()
726
+ val results = IntArray(grantResults.size()) { grantResults.getInt(it) }
727
+ DoorstepAI.notePermissionRequestResult(reactContext, names, results)
728
+ promise.resolve(true)
729
+ if (results.isNotEmpty()) settlePermissionRequest(answered = true, source = "noteResult")
730
+ } catch (e: Exception) {
731
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to record permission request result")
732
+ }
733
+ }
734
+
735
+ /**
736
+ * @param answered true when the dialog is known to be gone, which is what makes
737
+ * "requested but still not granted" mean DENIED. On a timeout it is false: the
738
+ * prompt may still be up, and calling that a denial would be a guess.
739
+ */
740
+ private fun settlePermissionRequest(answered: Boolean, source: String = "?") {
741
+ UiThreadUtil.runOnUiThread {
742
+ // Two lines per permission request, on purpose: "why did my promise resolve
743
+ // when it did" is the question hosts actually ask about this API, and the
744
+ // settle SOURCE is the answer. The SDK's own logger is silenced in release
745
+ // builds, so this is the only trace a host has.
746
+ android.util.Log.i(LOG_TAG, "requestPermissions settled: source=$source answered=$answered pending=${pendingPermissionPromise != null}")
747
+ val promise = pendingPermissionPromise ?: return@runOnUiThread
748
+ val whitelist = pendingPermissionWhitelist
749
+ val plan = pendingPermissionPlan
750
+ pendingPermissionPromise = null
751
+ pendingPermissionRequested = emptySet()
752
+ pendingPermissionWhitelist = emptySet()
753
+ pendingPermissionPlan = null
754
+ pendingPermissionActivity = null
755
+ permissionLifecycleListener?.let { reactContext.removeLifecycleEventListener(it) }
756
+ permissionLifecycleListener = null
757
+ permissionTimeoutRunnable?.let { mainHandler.removeCallbacks(it) }
758
+ permissionTimeoutRunnable = null
759
+ permissionPollRunnable?.let { mainHandler.removeCallbacks(it) }
760
+ permissionPollRunnable = null
761
+ try {
762
+ // `answered` is not forwarded to native as a denial: only a real
763
+ // host-forwarded grantResults array may write that ledger. It only decides
764
+ // whether this promise waits any longer.
765
+ val statuses = DoorstepAI.checkPermissions(permissionContext(), whitelist)
766
+ val payload = statusPayload(statuses)
767
+ promise.resolve(if (plan != null) mergePlan(payload, plan) else payload)
768
+ } catch (e: Exception) {
769
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to read permission status")
770
+ }
771
+ }
772
+ }
773
+
774
+ @ReactMethod
775
+ fun requestBackgroundLocationPermission(promise: Promise) {
776
+ val activity = currentActivity
777
+ if (activity == null) {
778
+ promise.reject("NO_ACTIVITY", "requestBackgroundLocationPermission needs a resumed Activity to prompt from")
779
+ return
780
+ }
781
+ UiThreadUtil.runOnUiThread {
782
+ try {
783
+ promise.resolve(DoorstepAI.requestBackgroundLocationPermission(activity))
784
+ } catch (e: Exception) {
785
+ promise.reject("PERMISSION_ERROR", e.message ?: "Failed to request background location permission")
786
+ }
787
+ }
788
+ }
789
+
295
790
  private fun parseCoordinates(map: ReadableMap?): LatLngObject? {
296
791
  if (map == null) return null
297
792
  val lat = if (map.hasKey("lat")) map.getDouble("lat") else return null
@@ -395,9 +890,18 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
395
890
  // is torn down in invalidate(); no per-listener teardown is needed.
396
891
  }
397
892
 
893
+ override fun initialize() {
894
+ super.initialize()
895
+ activeInstance = this
896
+ }
897
+
398
898
  override fun invalidate() {
899
+ if (activeInstance === this) activeInstance = null
399
900
  geofenceJob?.cancel()
400
901
  geofenceJob = null
902
+ // A permission request outliving the module would leave the JS promise pending
903
+ // forever; settle it with whatever the OS currently reports.
904
+ settlePermissionRequest(answered = false, source = "invalidate")
401
905
  super.invalidate()
402
906
  }
403
907
 
@@ -447,6 +951,66 @@ class DoorstepAIModule(private val reactContext: ReactApplicationContext) :
447
951
 
448
952
  companion object {
449
953
  const val NAME = "DoorstepAI"
954
+ private const val LOG_TAG = "DoorstepAI-RN"
450
955
  private const val GEOFENCE_EVENT = "DoorstepGeofenceSessionEvent"
956
+
957
+ /**
958
+ * The live module, so the host-Activity hook below can reach it. Cleared in
959
+ * [invalidate]; null before the bridge is up, which is exactly when there is no
960
+ * in-flight request to settle.
961
+ */
962
+ @Volatile
963
+ private var activeInstance: DoorstepAIModule? = null
964
+
965
+ /**
966
+ * **The host wiring worth copying.** Call this from your Activity's
967
+ * `onRequestPermissionsResult` and it does both halves at once:
968
+ *
969
+ * 1. forwards the answer to `DoorstepAI.notePermissionRequestResult`, which is
970
+ * the only way the SDK can tell a refusal it may re-ask (`denied`) from one
971
+ * only Settings can fix (`permanentlyDenied`) — Android reports identical
972
+ * signals for "permanently denied" and "never asked", and a *cancelled*
973
+ * dialog leaves the same trace as a denial, so the SDK will not guess;
974
+ * 2. settles an in-flight JS `requestPermissions()` on the real answer instead
975
+ * of on the window-focus heuristic.
976
+ *
977
+ * ```kotlin
978
+ * override fun onRequestPermissionsResult(
979
+ * requestCode: Int, permissions: Array<out String>, grantResults: IntArray
980
+ * ) {
981
+ * super.onRequestPermissionsResult(requestCode, permissions, grantResults)
982
+ * DoorstepAIModule.notePermissionRequestResult(this, permissions, grantResults)
983
+ * }
984
+ * ```
985
+ *
986
+ * An EMPTY [grantResults] is a cancelled interaction, not a denial: it is
987
+ * forwarded (the SDK records nothing from it) and it does not settle the
988
+ * promise, because the OS may still be showing the rest of the sequence.
989
+ */
990
+ @JvmStatic
991
+ fun notePermissionRequestResult(
992
+ context: android.content.Context,
993
+ permissions: Array<out String>,
994
+ grantResults: IntArray
995
+ ) {
996
+ DoorstepAI.notePermissionRequestResult(context, permissions, grantResults)
997
+ if (grantResults.isNotEmpty()) {
998
+ activeInstance?.settlePermissionRequest(answered = true, source = "hostResult")
999
+ }
1000
+ }
1001
+
1002
+ /** The three public permission keys, in a fixed order. */
1003
+ private val PUBLIC_PERMISSION_BUCKETS = listOf("location", "motion", "bluetooth")
1004
+ private const val PERMISSION_POLL_MS = 250L
1005
+ private const val PERMISSION_ANSWER_TIMEOUT_MS = 120_000L
1006
+
1007
+ /**
1008
+ * How long a request waits for the permission dialog to take window focus
1009
+ * before concluding the OS is not going to show one. Generous because the
1010
+ * permission-controller process may have to cold-start; the cost of being
1011
+ * wrong in this direction is only a slower resolve, while being wrong in the
1012
+ * other direction resolves with pre-answer state.
1013
+ */
1014
+ private const val PERMISSION_DIALOG_GRACE_MS = 8_000L
451
1015
  }
452
1016
  }
package/ios/DoorstepAI.mm CHANGED
@@ -4,8 +4,18 @@
4
4
  @interface RCT_EXTERN_MODULE(DoorstepAI, RCTEventEmitter)
5
5
 
6
6
  RCT_EXTERN_METHOD(setApiKey:(nonnull NSString *)apiKey)
7
- RCT_EXTERN_METHOD(requestAllPermissions:(BOOL)requestAlwaysLocation
8
- requestBluetooth:(BOOL)requestBluetooth)
7
+ RCT_EXTERN_METHOD(setDoorstepGoApiKey:(nonnull NSString *)apiKey)
8
+ RCT_EXTERN_METHOD(debugStateJson:(RCTPromiseResolveBlock)resolve
9
+ rejecter:(RCTPromiseRejectBlock)reject)
10
+ RCT_EXTERN_METHOD(checkPermissions:(nullable NSArray *)permissions
11
+ resolver:(RCTPromiseResolveBlock)resolve
12
+ rejecter:(RCTPromiseRejectBlock)reject)
13
+ RCT_EXTERN_METHOD(checkPermissionsJson:(nullable NSArray *)permissions
14
+ resolver:(RCTPromiseResolveBlock)resolve
15
+ rejecter:(RCTPromiseRejectBlock)reject)
16
+ RCT_EXTERN_METHOD(requestPermissions:(nullable NSDictionary *)options
17
+ resolver:(RCTPromiseResolveBlock)resolve
18
+ rejecter:(RCTPromiseRejectBlock)reject)
9
19
  RCT_EXTERN_METHOD(configureRemoteLogging:(BOOL)enabled
10
20
  minLevel:(id)minLevel
11
21
  flushIntervalSeconds:(id)flushIntervalSeconds