react-native-asleep 1.0.15 → 1.0.18
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/README.md +65 -14
- package/android/build.gradle +1 -1
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +52 -64
- package/build/Asleep.types.d.ts +1 -1
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +1 -1
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +159 -86
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -1
- package/build/index.js.map +1 -1
- package/ios/AsleepModule.swift +4 -0
- package/package.json +30 -16
- package/src/Asleep.types.ts +4 -8
- package/src/AsleepStore.ts +175 -154
- package/src/index.ts +15 -41
- package/.eslintrc.js +0 -5
- package/.releaserc.js +0 -58
- package/AGENTS.md +0 -107
- package/docs/PUBLISHING.md +0 -36
- package/tsconfig.json +0 -9
- /package/{License.md → LICENSE.md} +0 -0
package/build/AsleepStore.js
CHANGED
|
@@ -4,6 +4,23 @@ import { EventEmitter } from "expo-modules-core";
|
|
|
4
4
|
import { Platform, PermissionsAndroid } from "react-native";
|
|
5
5
|
import AsleepModule from "./AsleepModule";
|
|
6
6
|
const emitter = new EventEmitter(AsleepModule);
|
|
7
|
+
// All dev-only warnings below are gated with an inline
|
|
8
|
+
// `typeof __DEV__ !== "undefined" && __DEV__` check rather than a helper
|
|
9
|
+
// function. Metro's inline plugin substitutes the bare `__DEV__` identifier
|
|
10
|
+
// for the literal at build time, then constant-folds `typeof <literal>` and
|
|
11
|
+
// the `&&` so the entire branch is dead-code-eliminated in production
|
|
12
|
+
// bundles. Wrapping the check in a function (e.g. `if (isDev())`) defeats
|
|
13
|
+
// that DCE because Metro does not constant-fold through call expressions.
|
|
14
|
+
// The `typeof` guard also keeps the module importable from plain Node,
|
|
15
|
+
// custom bundlers, or unconfigured jest setups without a ReferenceError.
|
|
16
|
+
// Error codes emitted on onTrackingFailed for which the native SDK has already
|
|
17
|
+
// terminated the session and will not deliver onTrackingClosed. JS must clear
|
|
18
|
+
// tracking state itself when one of these arrives. See AGENTS.md "Native Behavior
|
|
19
|
+
// Compensations" for the upstream behavior these guard against.
|
|
20
|
+
const TERMINAL_TRACKING_ERROR_CODES = new Set([
|
|
21
|
+
"UPLOAD_TRACKING_TERMINATED", // iOS 403/429 closeSessionSilently; Android errorCode 23499
|
|
22
|
+
"INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
|
|
23
|
+
]);
|
|
7
24
|
const convertKeysToCamelCase = (obj) => {
|
|
8
25
|
if (Array.isArray(obj)) {
|
|
9
26
|
return obj.map(convertKeysToCamelCase);
|
|
@@ -55,17 +72,19 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
55
72
|
addLog("[setup] Start");
|
|
56
73
|
set({ isSetupInProgress: true, error: null });
|
|
57
74
|
await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
|
|
58
|
-
// Store ODA enabled state
|
|
75
|
+
// Store ODA enabled state. Clearing `error` on success keeps the
|
|
76
|
+
// reactive `useAsleep().error` field aligned with the actual SDK status
|
|
77
|
+
// (no stale failure messages after a successful retry).
|
|
59
78
|
set({
|
|
60
79
|
isODAEnabled: config.enableODA || false,
|
|
61
80
|
isInitialized: true,
|
|
62
81
|
isSetupInProgress: false,
|
|
63
82
|
isSetupComplete: true,
|
|
83
|
+
error: null,
|
|
64
84
|
});
|
|
65
85
|
addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
|
|
66
86
|
}
|
|
67
87
|
catch (error) {
|
|
68
|
-
console.error("setup error:", error);
|
|
69
88
|
set({ error: error.message, isSetupInProgress: false });
|
|
70
89
|
throw error;
|
|
71
90
|
}
|
|
@@ -75,12 +94,11 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
75
94
|
const { addLog } = get();
|
|
76
95
|
addLog("[initAsleepConfig] Start");
|
|
77
96
|
const result = await AsleepModule.initAsleepConfig(config.apiKey, config.userId, config.baseUrl, config.callbackUrl);
|
|
78
|
-
set({ isInitialized: true });
|
|
97
|
+
set({ isInitialized: true, error: null });
|
|
79
98
|
addLog("[initAsleepConfig] Success");
|
|
80
99
|
return result;
|
|
81
100
|
}
|
|
82
101
|
catch (error) {
|
|
83
|
-
console.error("initAsleepConfig error:", error);
|
|
84
102
|
set({ error: error.message });
|
|
85
103
|
throw error;
|
|
86
104
|
}
|
|
@@ -92,7 +110,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
92
110
|
// Check if sleep tracking service is alive
|
|
93
111
|
const isAlive = await AsleepModule.isSleepTrackingAlive();
|
|
94
112
|
set({
|
|
95
|
-
hasCheckedStatus: true
|
|
113
|
+
hasCheckedStatus: true,
|
|
96
114
|
});
|
|
97
115
|
// If service is alive on Android, restore connection to it
|
|
98
116
|
if (isAlive && Platform.OS === "android") {
|
|
@@ -108,11 +126,10 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
108
126
|
}
|
|
109
127
|
addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
|
|
110
128
|
return {
|
|
111
|
-
hasActiveSession: isAlive
|
|
129
|
+
hasActiveSession: isAlive,
|
|
112
130
|
};
|
|
113
131
|
}
|
|
114
132
|
catch (error) {
|
|
115
|
-
console.error("checkAndRestoreTracking error:", error);
|
|
116
133
|
set({ error: error.message });
|
|
117
134
|
throw error;
|
|
118
135
|
}
|
|
@@ -134,19 +151,19 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
134
151
|
addLog("[checkBatteryOptimization] Checking battery optimization status...");
|
|
135
152
|
// Mark that check was performed (required for startTracking)
|
|
136
153
|
set({ hasCheckedBatteryOptimization: true });
|
|
137
|
-
if (Platform.OS ===
|
|
154
|
+
if (Platform.OS === "ios") {
|
|
138
155
|
addLog("[checkBatteryOptimization] iOS - not applicable");
|
|
139
|
-
return { exempted: true, platform:
|
|
156
|
+
return { exempted: true, platform: "ios" };
|
|
140
157
|
}
|
|
141
158
|
// Android: Check current status
|
|
142
159
|
const exempted = await AsleepModule.isBatteryOptimizationExempted();
|
|
143
160
|
addLog(`[checkBatteryOptimization] Exempted: ${exempted}`);
|
|
144
161
|
return {
|
|
145
162
|
exempted,
|
|
146
|
-
platform:
|
|
147
|
-
message: exempted
|
|
148
|
-
"Battery optimization disabled - ready for tracking"
|
|
149
|
-
"Battery optimization must be disabled for reliable tracking"
|
|
163
|
+
platform: "android",
|
|
164
|
+
message: exempted
|
|
165
|
+
? "Battery optimization disabled - ready for tracking"
|
|
166
|
+
: "Battery optimization must be disabled for reliable tracking",
|
|
150
167
|
};
|
|
151
168
|
},
|
|
152
169
|
/**
|
|
@@ -160,7 +177,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
160
177
|
*/
|
|
161
178
|
requestBatteryOptimizationExemption: async () => {
|
|
162
179
|
const { addLog } = get();
|
|
163
|
-
if (Platform.OS ===
|
|
180
|
+
if (Platform.OS === "ios") {
|
|
164
181
|
addLog("[requestBatteryOptimizationExemption] iOS - not applicable");
|
|
165
182
|
return true; // Not applicable on iOS
|
|
166
183
|
}
|
|
@@ -181,7 +198,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
181
198
|
*/
|
|
182
199
|
startTracking: async (config) => {
|
|
183
200
|
try {
|
|
184
|
-
const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus
|
|
201
|
+
const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
|
|
185
202
|
// Enforce that checkAndRestoreTracking must be called first
|
|
186
203
|
if (!hasCheckedStatus) {
|
|
187
204
|
addLog("[startTracking] Must call checkAndRestoreTracking() at app startup");
|
|
@@ -208,7 +225,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
208
225
|
const permission = await requestRequiredPermissions();
|
|
209
226
|
if (!permission) {
|
|
210
227
|
// SDK shouldn't show UI directly - throw specific error message
|
|
211
|
-
if (Platform.OS ===
|
|
228
|
+
if (Platform.OS === "android" && Platform.Version >= 33) {
|
|
212
229
|
throw new Error("Microphone and notification permissions are required for sleep tracking");
|
|
213
230
|
}
|
|
214
231
|
else {
|
|
@@ -216,7 +233,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
216
233
|
}
|
|
217
234
|
}
|
|
218
235
|
// Always verify CURRENT exemption status
|
|
219
|
-
if (Platform.OS ===
|
|
236
|
+
if (Platform.OS === "android") {
|
|
220
237
|
const batteryExempted = await AsleepModule.isBatteryOptimizationExempted();
|
|
221
238
|
if (!batteryExempted) {
|
|
222
239
|
addLog("[startTracking] ERROR: Battery optimization not disabled");
|
|
@@ -230,6 +247,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
230
247
|
isTracking: true,
|
|
231
248
|
isAnalyzing: false,
|
|
232
249
|
trackingStartTime: new Date(),
|
|
250
|
+
error: null,
|
|
233
251
|
});
|
|
234
252
|
await AsleepModule.startTracking(config);
|
|
235
253
|
if (isODAEnabled) {
|
|
@@ -241,7 +259,6 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
241
259
|
addLog("[startTracking] Success");
|
|
242
260
|
}
|
|
243
261
|
catch (error) {
|
|
244
|
-
console.error("startTracking error:", error);
|
|
245
262
|
set({
|
|
246
263
|
error: error.message,
|
|
247
264
|
isTracking: false,
|
|
@@ -262,22 +279,31 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
262
279
|
isTracking: false,
|
|
263
280
|
isAnalyzing: false,
|
|
264
281
|
trackingStartTime: null,
|
|
282
|
+
error: null,
|
|
265
283
|
});
|
|
266
284
|
addLog(`[stopTracking] Success - result: ${result}`);
|
|
267
285
|
}
|
|
268
286
|
catch (error) {
|
|
269
|
-
console.error("stopTracking error:", error);
|
|
270
287
|
set({ error: error.message });
|
|
271
288
|
throw error;
|
|
272
289
|
}
|
|
273
290
|
},
|
|
274
291
|
getReport: async (sessionId) => {
|
|
292
|
+
// Snapshot the error before the await so we only clear it on success
|
|
293
|
+
// if no concurrent failure (e.g. onTrackingFailed firing during the
|
|
294
|
+
// network round-trip) wrote a different error in the meantime.
|
|
295
|
+
const errorBefore = get().error;
|
|
275
296
|
try {
|
|
276
297
|
const { addLog } = get();
|
|
277
298
|
addLog(`[getReport] sessionId: ${sessionId}`);
|
|
278
299
|
const report = await AsleepModule.getReport(sessionId);
|
|
279
300
|
const convertedReport = convertKeysToCamelCase(report);
|
|
280
301
|
addLog("[getReport] Success");
|
|
302
|
+
// Guard so a successful query after a clean run does not spam an empty
|
|
303
|
+
// notification, and so we never clobber an unrelated tracking error
|
|
304
|
+
// that arrived during the await.
|
|
305
|
+
if (get().error !== null && get().error === errorBefore)
|
|
306
|
+
set({ error: null });
|
|
281
307
|
// Ensure the report has the expected AsleepReport structure
|
|
282
308
|
// Handle cases where native modules might return data in different formats
|
|
283
309
|
if (convertedReport && !convertedReport.session && convertedReport.sessionId) {
|
|
@@ -304,12 +330,18 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
304
330
|
return convertedReport;
|
|
305
331
|
}
|
|
306
332
|
catch (error) {
|
|
307
|
-
|
|
333
|
+
// Silent return on failure is a public-API quirk preserved for v1.x
|
|
334
|
+
// compat (v2.0 throws). Surface a dev-only warn so the consumer's
|
|
335
|
+
// Metro log still shows the failure when they're debugging without
|
|
336
|
+
// observing `useAsleep().error` directly.
|
|
337
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
338
|
+
console.warn("[Asleep] getReport failed:", error);
|
|
308
339
|
set({ error: error.message });
|
|
309
340
|
return null;
|
|
310
341
|
}
|
|
311
342
|
},
|
|
312
343
|
getReportList: async (fromDate, toDate) => {
|
|
344
|
+
const errorBefore = get().error;
|
|
313
345
|
try {
|
|
314
346
|
const { addLog } = get();
|
|
315
347
|
addLog(`[getReportList] fromDate: ${fromDate}, toDate: ${toDate}`);
|
|
@@ -329,38 +361,47 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
329
361
|
};
|
|
330
362
|
});
|
|
331
363
|
addLog("[getReportList] Success");
|
|
364
|
+
if (get().error !== null && get().error === errorBefore)
|
|
365
|
+
set({ error: null });
|
|
332
366
|
return convertedList;
|
|
333
367
|
}
|
|
334
368
|
catch (error) {
|
|
335
|
-
|
|
369
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
370
|
+
console.warn("[Asleep] getReportList failed:", error);
|
|
336
371
|
set({ error: error.message });
|
|
337
372
|
return [];
|
|
338
373
|
}
|
|
339
374
|
},
|
|
340
375
|
deleteSession: async (sessionId) => {
|
|
376
|
+
const errorBefore = get().error;
|
|
341
377
|
try {
|
|
342
378
|
const { addLog } = get();
|
|
343
379
|
addLog(`[deleteSession] sessionId: ${sessionId}`);
|
|
344
380
|
await AsleepModule.deleteSession(sessionId);
|
|
345
381
|
addLog("[deleteSession] Success");
|
|
382
|
+
if (get().error !== null && get().error === errorBefore)
|
|
383
|
+
set({ error: null });
|
|
346
384
|
}
|
|
347
385
|
catch (error) {
|
|
348
|
-
console.error("deleteSession error:", error);
|
|
349
386
|
set({ error: error.message });
|
|
350
387
|
throw error;
|
|
351
388
|
}
|
|
352
389
|
},
|
|
353
390
|
getAverageReport: async (fromDate, toDate) => {
|
|
391
|
+
const errorBefore = get().error;
|
|
354
392
|
try {
|
|
355
393
|
const { addLog } = get();
|
|
356
394
|
addLog(`[getAverageReport] fromDate: ${fromDate}, toDate: ${toDate}`);
|
|
357
395
|
const averageReport = await AsleepModule.getAverageReport(fromDate, toDate);
|
|
358
396
|
const convertedReport = convertKeysToCamelCase(averageReport);
|
|
359
397
|
addLog("[getAverageReport] Success");
|
|
398
|
+
if (get().error !== null && get().error === errorBefore)
|
|
399
|
+
set({ error: null });
|
|
360
400
|
return convertedReport;
|
|
361
401
|
}
|
|
362
402
|
catch (error) {
|
|
363
|
-
|
|
403
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
404
|
+
console.warn("[Asleep] getAverageReport failed:", error);
|
|
364
405
|
set({ error: error.message });
|
|
365
406
|
return null;
|
|
366
407
|
}
|
|
@@ -369,11 +410,13 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
369
410
|
* @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
|
|
370
411
|
*/
|
|
371
412
|
requestMicrophonePermission: async () => {
|
|
372
|
-
|
|
413
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
414
|
+
console.warn("[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.");
|
|
415
|
+
}
|
|
373
416
|
return get().requestRequiredPermissions();
|
|
374
417
|
},
|
|
375
418
|
requestRequiredPermissions: async () => {
|
|
376
|
-
if (Platform.OS ===
|
|
419
|
+
if (Platform.OS === "android") {
|
|
377
420
|
try {
|
|
378
421
|
// Prepare permissions array with RECORD_AUDIO
|
|
379
422
|
const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
|
|
@@ -384,16 +427,16 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
384
427
|
// Request all permissions together for better UX (single dialog)
|
|
385
428
|
const results = await PermissionsAndroid.requestMultiple(permissions);
|
|
386
429
|
// Check if all required permissions are granted
|
|
387
|
-
const audioGranted = results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] ===
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
PermissionsAndroid.RESULTS.GRANTED : true;
|
|
430
|
+
const audioGranted = results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
|
|
431
|
+
const notificationGranted = Platform.Version >= 33
|
|
432
|
+
? results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] === PermissionsAndroid.RESULTS.GRANTED
|
|
433
|
+
: true;
|
|
392
434
|
// Both must be granted for tracking to work properly
|
|
393
435
|
return audioGranted && notificationGranted;
|
|
394
436
|
}
|
|
395
437
|
catch (err) {
|
|
396
|
-
|
|
438
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
439
|
+
console.warn("[Asleep] Permission request error:", err);
|
|
397
440
|
return false;
|
|
398
441
|
}
|
|
399
442
|
}
|
|
@@ -405,7 +448,8 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
405
448
|
await AsleepModule.setCustomNotification(title, text);
|
|
406
449
|
}
|
|
407
450
|
else {
|
|
408
|
-
|
|
451
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
452
|
+
console.warn("[Asleep] setCustomNotification is not supported on this platform");
|
|
409
453
|
}
|
|
410
454
|
},
|
|
411
455
|
enableLog: (print) => {
|
|
@@ -415,7 +459,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
415
459
|
try {
|
|
416
460
|
const { addLog } = get();
|
|
417
461
|
addLog("[requestAnalysis] Start");
|
|
418
|
-
set({ isAnalyzing: true });
|
|
462
|
+
set({ isAnalyzing: true, error: null });
|
|
419
463
|
const result = await AsleepModule.requestAnalysis();
|
|
420
464
|
const convertedResult = convertKeysToCamelCase(result);
|
|
421
465
|
// Platform differences:
|
|
@@ -430,7 +474,8 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
430
474
|
return convertedResult;
|
|
431
475
|
}
|
|
432
476
|
catch (error) {
|
|
433
|
-
|
|
477
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
478
|
+
console.warn("[Asleep] requestAnalysis failed:", error);
|
|
434
479
|
set({ error: error.message, isAnalyzing: false });
|
|
435
480
|
return null;
|
|
436
481
|
}
|
|
@@ -462,31 +507,44 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
462
507
|
setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
|
|
463
508
|
setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
|
|
464
509
|
addLog: (log) => {
|
|
510
|
+
// Zero-cost when the consumer has not opted into debug logging. Without
|
|
511
|
+
// this guard, every native event handler would cause a spurious
|
|
512
|
+
// subscriber notification on top of any actual data update.
|
|
465
513
|
const { showDebugLog } = get();
|
|
514
|
+
if (!showDebugLog)
|
|
515
|
+
return;
|
|
466
516
|
const now = new Date();
|
|
467
517
|
const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
|
|
468
518
|
.getMinutes()
|
|
469
519
|
.toString()
|
|
470
520
|
.padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
|
|
471
521
|
const formattedLog = `[${dateString}]${log}`;
|
|
472
|
-
|
|
473
|
-
console.log(`[Asleep]${formattedLog}`);
|
|
474
|
-
}
|
|
522
|
+
console.log(`[Asleep]${formattedLog}`);
|
|
475
523
|
set({ log: formattedLog });
|
|
476
524
|
},
|
|
477
525
|
})));
|
|
478
|
-
//
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
//
|
|
526
|
+
// Ref-counted registration. Each caller (useAsleep effect, background context,
|
|
527
|
+
// etc.) increments on entry and decrements via the returned cleanup. Native
|
|
528
|
+
// listeners only attach on 0→1 and detach on the final 1→0, so concurrent
|
|
529
|
+
// consumers cannot tear each other's subscriptions down.
|
|
530
|
+
let refCount = 0;
|
|
531
|
+
let teardown = null;
|
|
482
532
|
export const initializeAsleepListeners = () => {
|
|
483
|
-
//
|
|
484
|
-
|
|
485
|
-
|
|
533
|
+
// Cold start when no teardown is installed. `teardown` is the single source
|
|
534
|
+
// of truth for "listeners are currently attached"; refCount is just an
|
|
535
|
+
// increment-only counter for cleanup balancing. Always incrementing
|
|
536
|
+
// (instead of assigning =1 on cold start) keeps the count correct even if
|
|
537
|
+
// a future change introduces an async seam between this check and the
|
|
538
|
+
// listener registration below.
|
|
539
|
+
if (teardown) {
|
|
540
|
+
refCount++;
|
|
541
|
+
return makeCleanup();
|
|
486
542
|
}
|
|
487
543
|
const store = useAsleepStore.getState();
|
|
488
|
-
const { addLog, setUserId,
|
|
489
|
-
// event handlers
|
|
544
|
+
const { addLog, setUserId, setIsTrackingPaused, setIsSetupInProgress } = store;
|
|
545
|
+
// event handlers — each native SDK event corresponds to one logical state
|
|
546
|
+
// transaction. Use a single useAsleepStore.setState per handler so consumers
|
|
547
|
+
// subscribed via useAsleep re-render once per event, not once per field.
|
|
490
548
|
const handlers = {
|
|
491
549
|
// Connected: iOS userDidJoin, Android onSuccess (AsleepConfigListener)
|
|
492
550
|
onUserJoined: (data) => {
|
|
@@ -496,7 +554,7 @@ export const initializeAsleepListeners = () => {
|
|
|
496
554
|
// Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
|
|
497
555
|
onUserJoinFailed: (error) => {
|
|
498
556
|
const errorString = JSON.stringify(error);
|
|
499
|
-
|
|
557
|
+
useAsleepStore.setState({ error: errorString });
|
|
500
558
|
addLog(`[onUserJoinFailed] error: ${errorString}`);
|
|
501
559
|
},
|
|
502
560
|
// Connected: iOS userDidDelete, Android NOT IMPLEMENTED
|
|
@@ -506,48 +564,53 @@ export const initializeAsleepListeners = () => {
|
|
|
506
564
|
},
|
|
507
565
|
// Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
|
|
508
566
|
onTrackingCreated: (data) => {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
}
|
|
567
|
+
useAsleepStore.setState({
|
|
568
|
+
isTracking: true,
|
|
569
|
+
...(data?.sessionId ? { sessionId: data.sessionId } : {}),
|
|
570
|
+
});
|
|
513
571
|
addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
|
|
514
572
|
},
|
|
515
573
|
// Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
|
|
516
574
|
// Triggers automatic analysis requests in both ODA and non-ODA modes
|
|
517
575
|
onTrackingUploaded: (data) => {
|
|
518
576
|
addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
|
|
577
|
+
// requestAnalysis() flips isAnalyzing internally; no separate setter
|
|
578
|
+
// needed before invoking it (avoids a duplicate subscriber notification).
|
|
519
579
|
const state = useAsleepStore.getState();
|
|
580
|
+
const triggerAnalysis = () => state.requestAnalysis().catch((error) => {
|
|
581
|
+
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
582
|
+
state.setIsAnalyzing(false);
|
|
583
|
+
});
|
|
520
584
|
if (state.isODAEnabled && state.isTracking) {
|
|
521
|
-
|
|
522
|
-
state.requestAnalysis().catch((error) => {
|
|
523
|
-
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
524
|
-
state.setIsAnalyzing(false);
|
|
525
|
-
});
|
|
585
|
+
triggerAnalysis();
|
|
526
586
|
}
|
|
527
587
|
else if (!state.isODAEnabled && state.isTracking) {
|
|
528
588
|
if (data.sequence >= 10 && data.sequence % 10 === 1) {
|
|
529
|
-
|
|
530
|
-
state.requestAnalysis().catch((error) => {
|
|
531
|
-
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
532
|
-
state.setIsAnalyzing(false);
|
|
533
|
-
});
|
|
589
|
+
triggerAnalysis();
|
|
534
590
|
}
|
|
535
591
|
}
|
|
536
592
|
},
|
|
537
593
|
// Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
|
|
538
594
|
onTrackingClosed: (data) => {
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
595
|
+
useAsleepStore.setState({
|
|
596
|
+
sessionId: data.sessionId,
|
|
597
|
+
isTracking: false,
|
|
598
|
+
isAnalyzing: false,
|
|
599
|
+
didClose: true,
|
|
600
|
+
trackingStartTime: null,
|
|
601
|
+
});
|
|
544
602
|
addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
|
|
545
603
|
},
|
|
546
604
|
// Connected: iOS didFail, Android onFail (AsleepTrackingListener)
|
|
547
|
-
//
|
|
605
|
+
// Terminal codes (UPLOAD_TRACKING_TERMINATED / INTERRUPTION_RECOVERY_FAILED)
|
|
606
|
+
// mean the native SDK already tore the session down — clear tracking state
|
|
607
|
+
// in the same setState as the error write so subscribers see one event.
|
|
548
608
|
onTrackingFailed: (error) => {
|
|
549
609
|
const errorString = JSON.stringify(error);
|
|
550
|
-
|
|
610
|
+
const terminal = !!(error && TERMINAL_TRACKING_ERROR_CODES.has(error.code));
|
|
611
|
+
useAsleepStore.setState(terminal
|
|
612
|
+
? { error: errorString, isTracking: false, isAnalyzing: false, didClose: true, trackingStartTime: null }
|
|
613
|
+
: { error: errorString });
|
|
551
614
|
addLog(`[onTrackingError] error: ${errorString}`);
|
|
552
615
|
},
|
|
553
616
|
// Connected: iOS didInterrupt, Android NOT IMPLEMENTED
|
|
@@ -556,10 +619,14 @@ export const initializeAsleepListeners = () => {
|
|
|
556
619
|
addLog(`[onTrackingInterrupted]`);
|
|
557
620
|
},
|
|
558
621
|
// Connected: iOS didResume, Android NOT IMPLEMENTED
|
|
622
|
+
// Always clear the error: some iOS recovery paths (e.g. cannotActivateInBackground
|
|
623
|
+
// retry) reach this handler without a preceding didInterrupt, and the stale error
|
|
624
|
+
// should still be cleared. Only the paused-state mutation is gated, to dedup the
|
|
625
|
+
// iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
|
|
559
626
|
onTrackingResumed: () => {
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
addLog(`[onTrackingResumed]`);
|
|
627
|
+
const wasPaused = useAsleepStore.getState().isTrackingPaused;
|
|
628
|
+
useAsleepStore.setState(wasPaused ? { error: null, isTrackingPaused: false } : { error: null });
|
|
629
|
+
addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
|
|
563
630
|
},
|
|
564
631
|
// Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
|
|
565
632
|
onMicPermissionDenied: () => {
|
|
@@ -571,16 +638,13 @@ export const initializeAsleepListeners = () => {
|
|
|
571
638
|
},
|
|
572
639
|
// Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
|
|
573
640
|
onSetupDidComplete: () => {
|
|
574
|
-
|
|
575
|
-
setIsSetupComplete(true);
|
|
641
|
+
useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
|
|
576
642
|
addLog(`[onSetupDidComplete]`);
|
|
577
643
|
},
|
|
578
644
|
// Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
|
|
579
645
|
onSetupDidFail: (data) => {
|
|
580
646
|
const errorString = JSON.stringify(data);
|
|
581
|
-
|
|
582
|
-
setIsSetupInProgress(false);
|
|
583
|
-
setIsSetupComplete(false);
|
|
647
|
+
useAsleepStore.setState({ error: errorString, isSetupInProgress: false, isSetupComplete: false });
|
|
584
648
|
addLog(`[onSetupDidFail] error: ${errorString}`);
|
|
585
649
|
},
|
|
586
650
|
// Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
|
|
@@ -590,8 +654,7 @@ export const initializeAsleepListeners = () => {
|
|
|
590
654
|
},
|
|
591
655
|
// Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
|
|
592
656
|
onAnalysisResult: (data) => {
|
|
593
|
-
|
|
594
|
-
setIsAnalyzing(false); // Analysis is complete, so set to false
|
|
657
|
+
useAsleepStore.setState({ analysisResult: data, isAnalyzing: false });
|
|
595
658
|
addLog(`[onAnalysisResult] ${JSON.stringify(data)}`);
|
|
596
659
|
},
|
|
597
660
|
};
|
|
@@ -601,15 +664,25 @@ export const initializeAsleepListeners = () => {
|
|
|
601
664
|
const subscription = emitter.addListener(eventType, handler);
|
|
602
665
|
subscriptions.push(() => subscription.remove());
|
|
603
666
|
});
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
// Create cleanup function
|
|
607
|
-
cleanupFunction = () => {
|
|
667
|
+
refCount++;
|
|
668
|
+
teardown = () => {
|
|
608
669
|
subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
609
|
-
|
|
610
|
-
|
|
670
|
+
teardown = null;
|
|
671
|
+
};
|
|
672
|
+
return makeCleanup();
|
|
673
|
+
};
|
|
674
|
+
const makeCleanup = () => {
|
|
675
|
+
// Idempotent per-caller cleanup. The `called` flag is closure-private so
|
|
676
|
+
// calling the returned function twice (e.g. Strict Mode double-effect)
|
|
677
|
+
// decrements the shared ref count only once.
|
|
678
|
+
let called = false;
|
|
679
|
+
return () => {
|
|
680
|
+
if (called)
|
|
681
|
+
return;
|
|
682
|
+
called = true;
|
|
683
|
+
refCount--;
|
|
684
|
+
if (refCount === 0 && teardown)
|
|
685
|
+
teardown();
|
|
611
686
|
};
|
|
612
|
-
// return cleanup function
|
|
613
|
-
return cleanupFunction;
|
|
614
687
|
};
|
|
615
688
|
//# sourceMappingURL=AsleepStore.js.map
|