@proxze/kyc-react-native 0.1.0 → 0.2.0

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.
@@ -1,44 +1,99 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BackgroundGeolocationAdapter = void 0;
4
- const GEOFENCE_ID = 'proxze-kyc-residence';
3
+ exports.__resetBackgroundGeolocationForTests = exports.BackgroundGeolocationAdapter = exports.sampleForNight = void 0;
4
+ const constants_1 = require("../constants");
5
+ const nightWindow_1 = require("../nightWindow");
6
+ /** Larger batches risk the server's 100kb JSON body limit. */
7
+ const NATIVE_MAX_BATCH = 50;
8
+ /** Undelivered records older than this are dropped (the longest window is 30 days). */
9
+ const NATIVE_MAX_DAYS_TO_PERSIST = 30;
10
+ /** One fix, as the heartbeat and the foreground scheduler take it. */
11
+ const SAMPLE_OPTIONS = {
12
+ samples: 1,
13
+ timeout: 30,
14
+ desiredAccuracy: 40,
15
+ maximumAge: 60000,
16
+ };
17
+ const DEFAULT_RATIONALE = {
18
+ title: 'Allow location all the time?',
19
+ message: 'To confirm your address, your bank checks that this phone is at home overnight. Choose "Allow all the time" on the next screen.',
20
+ positiveAction: 'Change to "Allow all the time"',
21
+ negativeAction: 'Not now',
22
+ };
23
+ /**
24
+ * The library requires `ready()` once per launch, before anything else, and
25
+ * every adapter instance in a process shares the one native plugin, so the
26
+ * promise lives at module level.
27
+ */
28
+ let readyOnce = null;
29
+ /** Most recent native sync seen in this process, for diagnostics. */
30
+ let lastHttp = null;
31
+ /**
32
+ * The heartbeat subscription takes a stored fix, so there must be exactly one
33
+ * per process. Two would store two fixes per heartbeat, and two in-fence
34
+ * pings is a whole night under ping-count. `restoreProxzeKycTracking` and the
35
+ * session each start an adapter, so this can't live on the instance.
36
+ */
37
+ let heartbeatSubscription = null;
38
+ /** Adapter instances whose listeners hear heartbeat fixes. */
39
+ const heartbeatAudience = new Set();
40
+ const loadPlugin = () => {
41
+ var _a;
42
+ let mod;
43
+ try {
44
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
45
+ mod = require('react-native-background-geolocation');
46
+ }
47
+ catch {
48
+ throw new Error('@proxze/kyc-react-native: the default location adapter needs the ' +
49
+ 'optional peer dependency "react-native-background-geolocation". ' +
50
+ 'Install and license it, or pass your own LocationAdapter.');
51
+ }
52
+ return (_a = mod === null || mod === void 0 ? void 0 : mod.default) !== null && _a !== void 0 ? _a : mod;
53
+ };
54
+ /**
55
+ * Take a fix that the library stores and syncs itself, if now is a time a
56
+ * fix can count toward a night. Shared by the JS heartbeat listener and the
57
+ * Android headless task, which is what runs once the app has been killed.
58
+ */
59
+ const sampleForNight = async (bg, now = new Date()) => {
60
+ if (!(0, nightWindow_1.isSamplingTime)(now))
61
+ return null;
62
+ return bg.getCurrentPosition({ ...SAMPLE_OPTIONS, persist: true });
63
+ };
64
+ exports.sampleForNight = sampleForNight;
5
65
  /**
6
66
  * Default adapter over `react-native-background-geolocation` (Transistorsoft).
7
67
  *
8
68
  * Chosen because it is the one battle-tested way to get what this product
9
69
  * needs on both platforms: geofence enter/exit that survives app termination,
10
- * a heartbeat that still fires under Doze, and mock-location flags. On Android
11
- * it rides Google Play Services (fused location + Geofencing API) — the same
12
- * Google location stack the rest of the Proxze platform uses; on iOS it rides
13
- * CoreLocation region monitoring, which is why the "arrived and stayed" night
14
- * strategy exists at all: iOS will not deliver 30-minute background pings, and
15
- * the service's HYBRID evaluator already accounts for that.
70
+ * a heartbeat that still fires under Doze, mock-location flags, and its own
71
+ * native HTTP sync. On Android it rides Google Play Services (fused location
72
+ * + Geofencing API); on iOS, CoreLocation region monitoring.
73
+ *
74
+ * Delivery is native. The library stores every geofence transition and every
75
+ * heartbeat fix in its own database and posts them to `/v2/sdk/locations`
76
+ * itself, so events reach the server while the app is backgrounded, killed or
77
+ * rebooting. Before this the SDK's JavaScript queue carried them, and that
78
+ * only runs while the app is open: most nights arrived late or never.
79
+ *
80
+ * Tracking is geofences-only. The library never records the customer's
81
+ * movements; the only fixes are the heartbeat samples taken inside the night
82
+ * window and the morning-check slot (`isSamplingTime`).
16
83
  *
17
84
  * The library is an optional peer dependency — constructing this adapter
18
85
  * without it installed throws with install instructions.
19
86
  */
20
87
  class BackgroundGeolocationAdapter {
21
88
  constructor(options = {}) {
22
- var _a;
23
89
  this.listeners = [];
24
90
  this.subscriptions = [];
25
91
  this.started = false;
26
- // ---------------------------------------------------------------------------
27
- this.readyPromise = null;
28
- let mod;
29
- try {
30
- // eslint-disable-next-line @typescript-eslint/no-var-requires
31
- mod = require('react-native-background-geolocation');
32
- }
33
- catch {
34
- throw new Error('@proxze/kyc-react-native: the default location adapter needs the ' +
35
- 'optional peer dependency "react-native-background-geolocation". ' +
36
- 'Install and license it, or pass your own LocationAdapter.');
37
- }
38
- this.bg = (_a = mod === null || mod === void 0 ? void 0 : mod.default) !== null && _a !== void 0 ? _a : mod;
39
- this.debug = Boolean(options.debug);
92
+ this.bg = loadPlugin();
93
+ this.options = options;
40
94
  }
41
95
  async requestPermissions() {
96
+ await this.ready();
42
97
  let status;
43
98
  try {
44
99
  status = await this.bg.requestPermission();
@@ -50,6 +105,7 @@ class BackgroundGeolocationAdapter {
50
105
  return this.toPermissionState(status);
51
106
  }
52
107
  async checkPermissions() {
108
+ await this.ready();
53
109
  const state = await this.bg.getProviderState();
54
110
  return this.toPermissionState(state === null || state === void 0 ? void 0 : state.status, state);
55
111
  }
@@ -57,10 +113,8 @@ class BackgroundGeolocationAdapter {
57
113
  var _a, _b, _c;
58
114
  const state = provider !== null && provider !== void 0 ? provider : (await this.bg.getProviderState().catch(() => null));
59
115
  // iOS 14+ "Precise Location" off / Android 12+ "Approximate" grant.
60
- // 2 = ACCURACY_AUTHORIZATION_REDUCED in the lib's constants.
61
- const precise = !((state === null || state === void 0 ? void 0 : state.accuracyAuthorization) ===
62
- ((_a = this.bg.ACCURACY_AUTHORIZATION_REDUCED) !== null && _a !== void 0 ? _a : 2) &&
63
- (state === null || state === void 0 ? void 0 : state.accuracyAuthorization) !== undefined);
116
+ const reduced = (_a = this.bg.ACCURACY_AUTHORIZATION_REDUCED) !== null && _a !== void 0 ? _a : 1;
117
+ const precise = (state === null || state === void 0 ? void 0 : state.accuracyAuthorization) !== reduced;
64
118
  // 3 = AUTHORIZATION_STATUS_ALWAYS, 4 = WHEN_IN_USE (per the lib's docs).
65
119
  if (status === ((_b = this.bg.AUTHORIZATION_STATUS_ALWAYS) !== null && _b !== void 0 ? _b : 3)) {
66
120
  return { grade: 'granted_always', precise };
@@ -70,10 +124,22 @@ class BackgroundGeolocationAdapter {
70
124
  }
71
125
  return { grade: 'denied', precise };
72
126
  }
127
+ /**
128
+ * Add the verification fence, unless the OS already holds it unchanged.
129
+ * Re-adding fires a fresh initial ENTER every time the app opens at home,
130
+ * which is noise, so an identical fence is left alone.
131
+ */
73
132
  async registerGeofence(fence) {
74
133
  await this.ready();
134
+ const existing = await this.currentGeofence();
135
+ if (existing &&
136
+ existing.latitude === fence.lat &&
137
+ existing.longitude === fence.lng &&
138
+ existing.radius === fence.radiusM) {
139
+ return;
140
+ }
75
141
  await this.bg.addGeofence({
76
- identifier: GEOFENCE_ID,
142
+ identifier: constants_1.SDK_GEOFENCE_IDENTIFIER,
77
143
  radius: fence.radiusM,
78
144
  latitude: fence.lat,
79
145
  longitude: fence.lng,
@@ -85,62 +151,84 @@ class BackgroundGeolocationAdapter {
85
151
  }
86
152
  async clearGeofence() {
87
153
  try {
88
- await this.bg.removeGeofence(GEOFENCE_ID);
154
+ await this.bg.removeGeofence(constants_1.SDK_GEOFENCE_IDENTIFIER);
89
155
  }
90
156
  catch {
91
157
  /* already gone */
92
158
  }
93
159
  }
160
+ async isGeofenceRegistered() {
161
+ await this.ready();
162
+ return Boolean(await this.currentGeofence());
163
+ }
94
164
  async start() {
95
165
  await this.ready();
166
+ this.unsubscribeAll();
96
167
  this.subscriptions.push(this.bg.onGeofence((event) => {
97
168
  var _a;
169
+ if ((event === null || event === void 0 ? void 0 : event.identifier) && event.identifier !== constants_1.SDK_GEOFENCE_IDENTIFIER)
170
+ return;
98
171
  const action = String((_a = event === null || event === void 0 ? void 0 : event.action) !== null && _a !== void 0 ? _a : '').toUpperCase();
99
172
  const type = action === 'ENTER' ? 'enter' : action === 'EXIT' ? 'exit' : 'dwell';
100
173
  this.emit(this.fromLocation(type, event === null || event === void 0 ? void 0 : event.location));
101
174
  }));
102
- // Heartbeat is the OS-tolerated stand-in for the BRD's 30-minute ping: it
103
- // fires periodically even under Doze, and each firing samples a position.
104
- this.subscriptions.push(this.bg.onHeartbeat(async () => {
105
- try {
106
- const location = await this.bg.getCurrentPosition({
107
- samples: 1,
108
- persist: false,
109
- timeout: 30,
110
- desiredAccuracy: 40,
111
- });
112
- this.emit(this.fromLocation('ping', location));
113
- }
114
- catch {
115
- this.emit({ type: 'heartbeat', recordedAt: new Date() });
116
- }
175
+ // The heartbeat is the OS-tolerated stand-in for the BRD's 30-minute ping.
176
+ // While the app is killed on Android the headless task does this instead
177
+ // (`registerProxzeKycHeadlessTask`).
178
+ heartbeatAudience.add(this);
179
+ if (!heartbeatSubscription) {
180
+ const bg = this.bg;
181
+ heartbeatSubscription = bg.onHeartbeat(async () => {
182
+ let event;
183
+ try {
184
+ const location = await (0, exports.sampleForNight)(bg);
185
+ if (!location)
186
+ return;
187
+ event = BackgroundGeolocationAdapter.toEvent('ping', location);
188
+ }
189
+ catch {
190
+ event = { type: 'heartbeat', recordedAt: new Date() };
191
+ }
192
+ heartbeatAudience.forEach((adapter) => adapter.emit(event));
193
+ });
194
+ }
195
+ this.subscriptions.push(this.bg.onHttp((response) => {
196
+ var _a;
197
+ lastHttp = { status: Number((_a = response === null || response === void 0 ? void 0 : response.status) !== null && _a !== void 0 ? _a : 0), at: new Date().toISOString() };
117
198
  }));
118
- await this.bg.start();
119
- // Geofence transitions keep arriving even in geofence-only mode, and
120
- // starting monitoring without full tracking keeps battery drain polite.
199
+ // Geofences only: transitions plus the heartbeat, no movement tracking.
200
+ await this.bg.startGeofences();
121
201
  this.started = true;
122
202
  }
203
+ /**
204
+ * Stop the plugin entirely. Unconditional: the plugin is process-wide, and
205
+ * a verification that ended while the app was closed is stopped by an
206
+ * adapter instance that never called `start()` itself.
207
+ */
123
208
  async stop() {
124
- for (const sub of this.subscriptions) {
125
- try {
126
- sub.remove();
127
- }
128
- catch {
129
- /* noop */
130
- }
131
- }
132
- this.subscriptions = [];
133
- if (this.started) {
209
+ this.unsubscribeAll();
210
+ heartbeatSubscription === null || heartbeatSubscription === void 0 ? void 0 : heartbeatSubscription.remove();
211
+ heartbeatSubscription = null;
212
+ heartbeatAudience.clear();
213
+ try {
214
+ await this.ready();
134
215
  await this.bg.stop();
135
- this.started = false;
136
216
  }
217
+ catch {
218
+ /* already stopped, or the plugin never became ready */
219
+ }
220
+ this.started = false;
137
221
  }
222
+ /**
223
+ * A one-shot fix for the foreground scheduler. With native delivery the
224
+ * library stores it and syncs it itself; without, it is returned for the
225
+ * JavaScript queue and not stored.
226
+ */
138
227
  async getCurrentPosition() {
228
+ await this.ready();
139
229
  const location = await this.bg.getCurrentPosition({
140
- samples: 1,
141
- persist: false,
142
- timeout: 30,
143
- desiredAccuracy: 40,
230
+ ...SAMPLE_OPTIONS,
231
+ persist: Boolean(this.delivery),
144
232
  });
145
233
  return this.fromLocation('ping', location);
146
234
  }
@@ -150,41 +238,128 @@ class BackgroundGeolocationAdapter {
150
238
  this.listeners = this.listeners.filter((l) => l !== listener);
151
239
  };
152
240
  }
241
+ async configureNativeDelivery(target) {
242
+ this.delivery = target;
243
+ await this.ready();
244
+ await this.bg.setConfig(this.config());
245
+ // Anything captured before the URL was known goes now.
246
+ await this.bg.sync().catch(() => undefined);
247
+ }
248
+ async clearNativeDelivery() {
249
+ this.delivery = undefined;
250
+ await this.ready();
251
+ await this.bg.setConfig({ url: '', autoSync: false, headers: {}, params: {} });
252
+ await this.bg.destroyLocations().catch(() => undefined);
253
+ }
254
+ async nativeDeliveryStatus() {
255
+ var _a, _b;
256
+ let pending = null;
257
+ try {
258
+ await this.ready();
259
+ pending = await this.bg.getCount();
260
+ }
261
+ catch {
262
+ /* plugin unavailable */
263
+ }
264
+ return {
265
+ pending,
266
+ lastStatus: (_a = lastHttp === null || lastHttp === void 0 ? void 0 : lastHttp.status) !== null && _a !== void 0 ? _a : null,
267
+ lastAt: (_b = lastHttp === null || lastHttp === void 0 ? void 0 : lastHttp.at) !== null && _b !== void 0 ? _b : null,
268
+ };
269
+ }
270
+ // ---------------------------------------------------------------------------
271
+ /**
272
+ * The library config. `ready()` is called with `reset: false` so a relaunch
273
+ * never wipes the URL and token a previous launch set (Android keeps
274
+ * syncing after a reboot with no JavaScript, from the persisted config);
275
+ * `setConfig` then applies this launch's values on top.
276
+ */
277
+ config() {
278
+ var _a, _b, _c;
279
+ const delivery = this.delivery
280
+ ? {
281
+ url: this.delivery.url,
282
+ headers: this.delivery.headers,
283
+ params: this.delivery.params,
284
+ method: 'POST',
285
+ autoSync: true,
286
+ autoSyncThreshold: 0,
287
+ batchSync: true,
288
+ maxBatchSize: NATIVE_MAX_BATCH,
289
+ maxDaysToPersist: NATIVE_MAX_DAYS_TO_PERSIST,
290
+ }
291
+ : {};
292
+ return {
293
+ desiredAccuracy: (_a = this.bg.DESIRED_ACCURACY_HIGH) !== null && _a !== void 0 ? _a : -1,
294
+ distanceFilter: 50,
295
+ stopOnTerminate: false, // tracking must survive an app kill
296
+ startOnBoot: true, // and a phone restart mid-verification
297
+ enableHeadless: true, // Android: heartbeats reach JS after a kill
298
+ heartbeatInterval: 30 * 60, // seconds — the 30-minute cadence
299
+ preventSuspend: (_b = this.options.iosPreventSuspend) !== null && _b !== void 0 ? _b : true,
300
+ geofenceInitialTriggerEntry: true, // already home at registration = ENTER
301
+ locationAuthorizationRequest: 'Always',
302
+ backgroundPermissionRationale: (_c = this.options.backgroundPermissionRationale) !== null && _c !== void 0 ? _c : DEFAULT_RATIONALE,
303
+ debug: Boolean(this.options.debug),
304
+ logLevel: this.options.debug ? this.bg.LOG_LEVEL_VERBOSE : this.bg.LOG_LEVEL_OFF,
305
+ ...delivery,
306
+ };
307
+ }
153
308
  ready() {
309
+ if (!readyOnce) {
310
+ readyOnce = Promise.resolve(this.bg.ready({ ...this.config(), reset: false }))
311
+ .then(() => this.bg.setConfig(this.config()))
312
+ .then(() => undefined)
313
+ .catch((err) => {
314
+ readyOnce = null; // let a later call retry
315
+ throw err;
316
+ });
317
+ }
318
+ return readyOnce;
319
+ }
320
+ async currentGeofence() {
154
321
  var _a;
155
- if (this.readyPromise !== null)
156
- return this.readyPromise;
157
- {
158
- this.readyPromise = this.bg
159
- .ready({
160
- desiredAccuracy: (_a = this.bg.DESIRED_ACCURACY_HIGH) !== null && _a !== void 0 ? _a : -1,
161
- distanceFilter: 50,
162
- stopOnTerminate: false, // tracking must survive an app kill
163
- startOnBoot: true, // and a phone restart mid-verification
164
- heartbeatInterval: 30 * 60, // seconds — the 30-minute cadence
165
- preventSuspend: false,
166
- debug: this.debug,
167
- logLevel: this.debug ? this.bg.LOG_LEVEL_VERBOSE : this.bg.LOG_LEVEL_OFF,
168
- })
169
- .then(() => undefined);
170
- }
171
- return this.readyPromise;
322
+ try {
323
+ const fences = await this.bg.getGeofences();
324
+ return (_a = fences === null || fences === void 0 ? void 0 : fences.find((f) => (f === null || f === void 0 ? void 0 : f.identifier) === constants_1.SDK_GEOFENCE_IDENTIFIER)) !== null && _a !== void 0 ? _a : null;
325
+ }
326
+ catch {
327
+ return null;
328
+ }
329
+ }
330
+ unsubscribeAll() {
331
+ heartbeatAudience.delete(this);
332
+ for (const sub of this.subscriptions) {
333
+ try {
334
+ sub.remove();
335
+ }
336
+ catch {
337
+ /* noop */
338
+ }
339
+ }
340
+ this.subscriptions = [];
172
341
  }
173
342
  fromLocation(type, location) {
174
- var _a, _b, _c, _d, _e;
343
+ return BackgroundGeolocationAdapter.toEvent(type, location);
344
+ }
345
+ /** The library's location record as an adapter event. */
346
+ static toEvent(type, location) {
347
+ var _a, _b, _c, _d;
348
+ const battery = location === null || location === void 0 ? void 0 : location.battery;
349
+ const level = typeof (battery === null || battery === void 0 ? void 0 : battery.level) === 'number' && battery.level >= 0 ? battery.level : undefined;
350
+ const charging = (_a = battery === null || battery === void 0 ? void 0 : battery.is_charging) !== null && _a !== void 0 ? _a : battery === null || battery === void 0 ? void 0 : battery.isCharging;
175
351
  return {
176
352
  type,
177
- lat: (_a = location === null || location === void 0 ? void 0 : location.coords) === null || _a === void 0 ? void 0 : _a.latitude,
178
- lng: (_b = location === null || location === void 0 ? void 0 : location.coords) === null || _b === void 0 ? void 0 : _b.longitude,
179
- accuracyM: (_c = location === null || location === void 0 ? void 0 : location.coords) === null || _c === void 0 ? void 0 : _c.accuracy,
353
+ lat: (_b = location === null || location === void 0 ? void 0 : location.coords) === null || _b === void 0 ? void 0 : _b.latitude,
354
+ lng: (_c = location === null || location === void 0 ? void 0 : location.coords) === null || _c === void 0 ? void 0 : _c.longitude,
355
+ accuracyM: (_d = location === null || location === void 0 ? void 0 : location.coords) === null || _d === void 0 ? void 0 : _d.accuracy,
180
356
  recordedAt: (location === null || location === void 0 ? void 0 : location.timestamp) ? new Date(location.timestamp) : new Date(),
181
357
  isMocked: Boolean(location === null || location === void 0 ? void 0 : location.mock),
182
- batteryLevel: typeof ((_d = location === null || location === void 0 ? void 0 : location.battery) === null || _d === void 0 ? void 0 : _d.level) === 'number'
183
- ? Math.round(Math.abs(location.battery.level) * 100)
184
- : undefined,
185
- isCharging: (_e = location === null || location === void 0 ? void 0 : location.battery) === null || _e === void 0 ? void 0 : _e.isCharging,
358
+ batteryLevel: level === undefined ? undefined : Math.round(level * 100),
359
+ isCharging: typeof charging === 'boolean' ? charging : undefined,
186
360
  };
187
361
  }
362
+ /** Deliver to this instance's listeners. Not private: the heartbeat fans out to every instance. */
188
363
  emit(event) {
189
364
  for (const listener of this.listeners) {
190
365
  try {
@@ -197,3 +372,11 @@ class BackgroundGeolocationAdapter {
197
372
  }
198
373
  }
199
374
  exports.BackgroundGeolocationAdapter = BackgroundGeolocationAdapter;
375
+ /** Test hook: forget the per-process ready state. */
376
+ const __resetBackgroundGeolocationForTests = () => {
377
+ readyOnce = null;
378
+ lastHttp = null;
379
+ heartbeatSubscription = null;
380
+ heartbeatAudience.clear();
381
+ };
382
+ exports.__resetBackgroundGeolocationForTests = __resetBackgroundGeolocationForTests;
@@ -26,6 +26,12 @@ export declare const isWithinNightWindow: (instant: Date, offsetMinutes?: number
26
26
  * one in-fence sample here to close the night.
27
27
  */
28
28
  export declare const isInMorningCheckSlot: (instant: Date, offsetMinutes?: number) => boolean;
29
+ /**
30
+ * True when a position sample can count toward a night: inside the window
31
+ * (pings) or in the morning-check slot after it. Outside these hours the SDK
32
+ * takes no fixes, so the customer's daytime movements are never collected.
33
+ */
34
+ export declare const isSamplingTime: (instant?: Date, offsetMinutes?: number) => boolean;
29
35
  /**
30
36
  * Milliseconds until the next moment the SDK wants a location sample:
31
37
  * the next 30-minute ping mark inside tonight's window, the morning check
@@ -6,7 +6,7 @@
6
6
  * is correct and avoids shipping a timezone database to the handset.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.msUntilNextSample = exports.isInMorningCheckSlot = exports.isWithinNightWindow = exports.nightWindowFor = exports.buildWindow = exports.PING_INTERVAL_MINUTES = exports.MORNING_CHECK_GRACE_MINUTES = exports.NIGHT_END_HOUR = exports.NIGHT_START_HOUR = exports.WAT_OFFSET_MINUTES = void 0;
9
+ exports.msUntilNextSample = exports.isSamplingTime = exports.isInMorningCheckSlot = exports.isWithinNightWindow = exports.nightWindowFor = exports.buildWindow = exports.PING_INTERVAL_MINUTES = exports.MORNING_CHECK_GRACE_MINUTES = exports.NIGHT_END_HOUR = exports.NIGHT_START_HOUR = exports.WAT_OFFSET_MINUTES = void 0;
10
10
  exports.WAT_OFFSET_MINUTES = 60;
11
11
  exports.NIGHT_START_HOUR = 0; // 12:00 AM local
12
12
  exports.NIGHT_END_HOUR = 5; // 05:00 AM local
@@ -48,6 +48,14 @@ const isInMorningCheckSlot = (instant, offsetMinutes = exports.WAT_OFFSET_MINUTE
48
48
  return hour >= exports.NIGHT_END_HOUR && hour < graceEndHour;
49
49
  };
50
50
  exports.isInMorningCheckSlot = isInMorningCheckSlot;
51
+ /**
52
+ * True when a position sample can count toward a night: inside the window
53
+ * (pings) or in the morning-check slot after it. Outside these hours the SDK
54
+ * takes no fixes, so the customer's daytime movements are never collected.
55
+ */
56
+ const isSamplingTime = (instant = new Date(), offsetMinutes = exports.WAT_OFFSET_MINUTES) => (0, exports.isWithinNightWindow)(instant, offsetMinutes) ||
57
+ (0, exports.isInMorningCheckSlot)(instant, offsetMinutes);
58
+ exports.isSamplingTime = isSamplingTime;
51
59
  /**
52
60
  * Milliseconds until the next moment the SDK wants a location sample:
53
61
  * the next 30-minute ping mark inside tonight's window, the morning check
package/dist/queue.js CHANGED
@@ -71,6 +71,13 @@ class OfflineEventQueue {
71
71
  catch (err) {
72
72
  if (err instanceof client_1.ProxzeKycError && err.isSessionClosed)
73
73
  throw err;
74
+ if (err instanceof client_1.ProxzeKycError && !err.isTransient) {
75
+ // Refused outright (400, 403, 413…): the same batch would be
76
+ // refused forever and block every event queued behind it.
77
+ this.events = this.events.slice(batch.length);
78
+ await this.persist();
79
+ continue;
80
+ }
74
81
  break; // transient — keep the queue, try again later
75
82
  }
76
83
  // Acknowledged either way; rejected events are refused permanently
@@ -0,0 +1,25 @@
1
+ import { StorageAdapter } from './storage';
2
+ import { LocationAdapter } from './location/adapter';
3
+ /**
4
+ * Re-arm tracking when the app launches, before any screen mounts.
5
+ *
6
+ * The location library must be made ready on every launch, including the
7
+ * ones iOS performs in the background when the phone crosses the fence.
8
+ * If nothing does that, iOS delivers the transition to an app that ignores
9
+ * it. Screens mount too late (or never, in a background launch), so call this
10
+ * from the root of the app:
11
+ *
12
+ * ```js
13
+ * // index.js, or the root component's first effect
14
+ * import { restoreProxzeKycTracking } from '@proxze/kyc-react-native';
15
+ * restoreProxzeKycTracking();
16
+ * ```
17
+ *
18
+ * Resolves true when a verification was being tracked and delivery and the
19
+ * heartbeat sampler were re-armed, false when there was nothing to restore. It never prompts for
20
+ * permission and never starts a verification that wasn't already running.
21
+ */
22
+ export declare const restoreProxzeKycTracking: (options?: {
23
+ storage?: StorageAdapter;
24
+ adapter?: LocationAdapter;
25
+ }) => Promise<boolean>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.restoreProxzeKycTracking = void 0;
4
+ const storage_1 = require("./storage");
5
+ const tracking_1 = require("./tracking");
6
+ /**
7
+ * Re-arm tracking when the app launches, before any screen mounts.
8
+ *
9
+ * The location library must be made ready on every launch, including the
10
+ * ones iOS performs in the background when the phone crosses the fence.
11
+ * If nothing does that, iOS delivers the transition to an app that ignores
12
+ * it. Screens mount too late (or never, in a background launch), so call this
13
+ * from the root of the app:
14
+ *
15
+ * ```js
16
+ * // index.js, or the root component's first effect
17
+ * import { restoreProxzeKycTracking } from '@proxze/kyc-react-native';
18
+ * restoreProxzeKycTracking();
19
+ * ```
20
+ *
21
+ * Resolves true when a verification was being tracked and delivery and the
22
+ * heartbeat sampler were re-armed, false when there was nothing to restore. It never prompts for
23
+ * permission and never starts a verification that wasn't already running.
24
+ */
25
+ const restoreProxzeKycTracking = async (options = {}) => {
26
+ var _a;
27
+ const record = await (0, tracking_1.readTrackingRecord)((_a = options.storage) !== null && _a !== void 0 ? _a : (0, storage_1.defaultStorage)());
28
+ if (!record)
29
+ return false;
30
+ let adapter = options.adapter;
31
+ if (!adapter) {
32
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
33
+ const { BackgroundGeolocationAdapter } = require('./location/backgroundGeolocationAdapter');
34
+ adapter = new BackgroundGeolocationAdapter();
35
+ }
36
+ if (!adapter.configureNativeDelivery)
37
+ return false;
38
+ await adapter.configureNativeDelivery((0, tracking_1.nativeDeliveryTarget)(record));
39
+ // Re-subscribes the heartbeat sampler. On iOS there is no headless task: a
40
+ // background relaunch only samples if something in JavaScript listens.
41
+ await adapter.start();
42
+ return true;
43
+ };
44
+ exports.restoreProxzeKycTracking = restoreProxzeKycTracking;