react-native-asleep 1.0.18 → 1.1.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.
- package/README.md +69 -304
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +36 -17
- package/build/Asleep.types.d.ts +42 -0
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +5 -2
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +201 -51
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +9 -4
- package/build/index.d.ts.map +1 -1
- package/build/index.js +10 -9
- package/build/index.js.map +1 -1
- package/ios/AsleepModule.swift +60 -4
- package/package.json +1 -1
- package/src/Asleep.types.ts +51 -1
- package/src/AsleepStore.ts +214 -52
- package/src/index.ts +19 -7
package/src/AsleepStore.ts
CHANGED
|
@@ -5,11 +5,14 @@ import { Platform, PermissionsAndroid } from "react-native";
|
|
|
5
5
|
import {
|
|
6
6
|
AsleepConfig,
|
|
7
7
|
AsleepSetupConfig,
|
|
8
|
+
AsleepErrorCategory,
|
|
9
|
+
AsleepErrorInfo,
|
|
8
10
|
AsleepEventType,
|
|
9
11
|
AsleepReport,
|
|
10
12
|
AsleepSession,
|
|
11
13
|
AsleepAverageReport,
|
|
12
14
|
AsleepAnalysisResult,
|
|
15
|
+
AsleepAnalysisAck,
|
|
13
16
|
TrackingConfig,
|
|
14
17
|
} from "./Asleep.types";
|
|
15
18
|
import AsleepModule from "./AsleepModule";
|
|
@@ -35,11 +38,56 @@ const TERMINAL_TRACKING_ERROR_CODES = new Set<string>([
|
|
|
35
38
|
"INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
|
|
36
39
|
]);
|
|
37
40
|
|
|
41
|
+
// iOS SDK 3.2.0 stops the recorder without closing the native session when
|
|
42
|
+
// audio engine initialization fails. The session must be stopped and restarted.
|
|
43
|
+
const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED"]);
|
|
44
|
+
|
|
45
|
+
// iOS SDK 3.2.0 reports this when the audio engine cannot restart in the
|
|
46
|
+
// background. The consumer must call resumeTracking() after returning foreground.
|
|
47
|
+
const RECOVERY_REQUIRED_ERROR_CODES = new Set<string>(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
|
|
48
|
+
|
|
49
|
+
// Numeric-code twin of TERMINAL_TRACKING_ERROR_CODES, matched against the
|
|
50
|
+
// `sdkCode` payload field. Android SDK 3.2.x AsleepCore.onErrorCodeReceived
|
|
51
|
+
// tears the session down and dual-fires onFail + onFinish for exactly these
|
|
52
|
+
// codes (the native module suppresses the duplicate onFinish), so JS must
|
|
53
|
+
// clear tracking state here or isTracking stays stuck true.
|
|
54
|
+
// Must stay in sync with the Kotlin TERMINAL_TRACKING_ERROR_CODES companion
|
|
55
|
+
// set in android/src/main/java/ai/asleep/reactnative/AsleepModule.kt.
|
|
56
|
+
const TERMINAL_TRACKING_SDK_CODES = new Set<number>([
|
|
57
|
+
11003, // ERR_AUDIO
|
|
58
|
+
22000,
|
|
59
|
+
22401,
|
|
60
|
+
22409,
|
|
61
|
+
22422,
|
|
62
|
+
22500, // ERR_CREATE_*
|
|
63
|
+
23499, // ERR_UPLOAD_TRACKING_TERMINATED
|
|
64
|
+
24000,
|
|
65
|
+
24400,
|
|
66
|
+
24401,
|
|
67
|
+
24403,
|
|
68
|
+
24404,
|
|
69
|
+
24500, // ERR_CLOSE_*
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
// Upload failures the native session survives: absent from the AsleepCore
|
|
73
|
+
// terminal set above, so the Android SDK 3.2.x keeps the session open and later
|
|
74
|
+
// uploads continue (UploadDataTask retries 5xx internally before reporting).
|
|
75
|
+
// Deliberately small — only codes verifiable in upstream sources.
|
|
76
|
+
const TRANSIENT_TRACKING_SDK_CODES = new Set<number>([
|
|
77
|
+
23000, // ERR_UPLOAD_FAILED
|
|
78
|
+
23500, // ERR_UPLOAD_SERVER_ERROR
|
|
79
|
+
]);
|
|
80
|
+
|
|
38
81
|
export interface AsleepState {
|
|
39
82
|
didClose: boolean;
|
|
40
83
|
isTracking: boolean;
|
|
41
84
|
isTrackingPaused: boolean;
|
|
85
|
+
isRecoveryRequired: boolean;
|
|
42
86
|
error: string | null;
|
|
87
|
+
// Structured view of the last onTrackingFailed event. Kept in lockstep with
|
|
88
|
+
// `error`: every write or clear of `error` pairs an errorInfo write — a
|
|
89
|
+
// stale category surviving a later unrelated error would misclassify it.
|
|
90
|
+
errorInfo: AsleepErrorInfo | null;
|
|
43
91
|
userId: string | null;
|
|
44
92
|
sessionId: string | null;
|
|
45
93
|
showDebugLog: boolean;
|
|
@@ -66,6 +114,7 @@ export interface AsleepState {
|
|
|
66
114
|
requestBatteryOptimizationExemption: () => Promise<boolean>;
|
|
67
115
|
startTracking: (config?: TrackingConfig) => Promise<void>;
|
|
68
116
|
stopTracking: () => Promise<void>;
|
|
117
|
+
resumeTracking: () => Promise<void>;
|
|
69
118
|
getReport: (sessionId: string) => Promise<AsleepReport | null>;
|
|
70
119
|
getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
|
|
71
120
|
getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport | null>;
|
|
@@ -75,7 +124,7 @@ export interface AsleepState {
|
|
|
75
124
|
setCustomNotification: (title: string, text: string) => Promise<void>;
|
|
76
125
|
enableLog: (print: boolean) => void;
|
|
77
126
|
clearError: () => void;
|
|
78
|
-
requestAnalysis: () => Promise<AsleepAnalysisResult | null>;
|
|
127
|
+
requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck | null>;
|
|
79
128
|
addEventListener: <K extends keyof AsleepEventType>(
|
|
80
129
|
eventType: K,
|
|
81
130
|
listener: (data: AsleepEventType[K]) => void,
|
|
@@ -119,7 +168,9 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
119
168
|
didClose: false,
|
|
120
169
|
isTracking: AsleepModule.isTracking ? AsleepModule.isTracking() : false,
|
|
121
170
|
isTrackingPaused: false,
|
|
171
|
+
isRecoveryRequired: false,
|
|
122
172
|
error: null,
|
|
173
|
+
errorInfo: null,
|
|
123
174
|
userId: null,
|
|
124
175
|
sessionId: null,
|
|
125
176
|
showDebugLog: false,
|
|
@@ -156,7 +207,7 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
156
207
|
}
|
|
157
208
|
|
|
158
209
|
addLog("[setup] Start");
|
|
159
|
-
set({ isSetupInProgress: true, error: null });
|
|
210
|
+
set({ isSetupInProgress: true, error: null, errorInfo: null });
|
|
160
211
|
|
|
161
212
|
await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
|
|
162
213
|
|
|
@@ -169,10 +220,11 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
169
220
|
isSetupInProgress: false,
|
|
170
221
|
isSetupComplete: true,
|
|
171
222
|
error: null,
|
|
223
|
+
errorInfo: null,
|
|
172
224
|
});
|
|
173
225
|
addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
|
|
174
226
|
} catch (error: any) {
|
|
175
|
-
set({ error: error.message, isSetupInProgress: false });
|
|
227
|
+
set({ error: error.message, errorInfo: null, isSetupInProgress: false });
|
|
176
228
|
throw error;
|
|
177
229
|
}
|
|
178
230
|
},
|
|
@@ -189,11 +241,11 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
189
241
|
config.callbackUrl,
|
|
190
242
|
);
|
|
191
243
|
|
|
192
|
-
set({ isInitialized: true, error: null });
|
|
244
|
+
set({ isInitialized: true, error: null, errorInfo: null });
|
|
193
245
|
addLog("[initAsleepConfig] Success");
|
|
194
246
|
return result;
|
|
195
247
|
} catch (error: any) {
|
|
196
|
-
set({ error: error.message });
|
|
248
|
+
set({ error: error.message, errorInfo: null });
|
|
197
249
|
throw error;
|
|
198
250
|
}
|
|
199
251
|
},
|
|
@@ -228,7 +280,7 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
228
280
|
hasActiveSession: isAlive,
|
|
229
281
|
};
|
|
230
282
|
} catch (error: any) {
|
|
231
|
-
set({ error: error.message });
|
|
283
|
+
set({ error: error.message, errorInfo: null });
|
|
232
284
|
throw error;
|
|
233
285
|
}
|
|
234
286
|
},
|
|
@@ -306,6 +358,10 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
306
358
|
* @throws Error if prerequisites are not met or tracking is already in progress
|
|
307
359
|
*/
|
|
308
360
|
startTracking: async (config?: TrackingConfig) => {
|
|
361
|
+
// Snapshot so the catch can tell a verdict published DURING this call
|
|
362
|
+
// (Android fires classified onTrackingFailed before rejecting the same
|
|
363
|
+
// promise) apart from a stale one left by an earlier failure.
|
|
364
|
+
const errorInfoBefore = get().errorInfo;
|
|
309
365
|
try {
|
|
310
366
|
const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
|
|
311
367
|
|
|
@@ -366,8 +422,10 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
366
422
|
didClose: false,
|
|
367
423
|
isTracking: true,
|
|
368
424
|
isAnalyzing: false,
|
|
425
|
+
isRecoveryRequired: false,
|
|
369
426
|
trackingStartTime: new Date(),
|
|
370
427
|
error: null,
|
|
428
|
+
errorInfo: null,
|
|
371
429
|
});
|
|
372
430
|
await AsleepModule.startTracking(config);
|
|
373
431
|
|
|
@@ -379,8 +437,14 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
379
437
|
|
|
380
438
|
addLog("[startTracking] Success");
|
|
381
439
|
} catch (error: any) {
|
|
440
|
+
// Preserve only a verdict that arrived during this call — the raw
|
|
441
|
+
// rejection message carries strictly less information than the
|
|
442
|
+
// numeric-code verdict. Reference inequality against the snapshot
|
|
443
|
+
// excludes stale verdicts, so guard failures still write the new error.
|
|
444
|
+
const nowInfo = get().errorInfo;
|
|
445
|
+
const classified = nowInfo !== null && nowInfo !== errorInfoBefore;
|
|
382
446
|
set({
|
|
383
|
-
error: error.message,
|
|
447
|
+
...(classified ? {} : { error: error.message, errorInfo: null }),
|
|
384
448
|
isTracking: false,
|
|
385
449
|
isAnalyzing: false,
|
|
386
450
|
trackingStartTime: null,
|
|
@@ -390,6 +454,8 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
390
454
|
},
|
|
391
455
|
|
|
392
456
|
stopTracking: async () => {
|
|
457
|
+
// Same dual-signal race as startTracking; see the snapshot rationale there.
|
|
458
|
+
const errorInfoBefore = get().errorInfo;
|
|
393
459
|
try {
|
|
394
460
|
const { addLog } = get();
|
|
395
461
|
addLog("[stopTracking] Start");
|
|
@@ -400,17 +466,31 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
400
466
|
...(result ? { sessionId: result } : {}),
|
|
401
467
|
isTracking: false,
|
|
402
468
|
isAnalyzing: false,
|
|
469
|
+
isRecoveryRequired: false,
|
|
403
470
|
trackingStartTime: null,
|
|
404
471
|
error: null,
|
|
472
|
+
errorInfo: null,
|
|
405
473
|
});
|
|
406
474
|
|
|
407
475
|
addLog(`[stopTracking] Success - result: ${result}`);
|
|
408
476
|
} catch (error: any) {
|
|
409
|
-
|
|
477
|
+
const nowInfo = get().errorInfo;
|
|
478
|
+
if (nowInfo === null || nowInfo === errorInfoBefore) set({ error: error.message, errorInfo: null });
|
|
410
479
|
throw error;
|
|
411
480
|
}
|
|
412
481
|
},
|
|
413
482
|
|
|
483
|
+
resumeTracking: async () => {
|
|
484
|
+
if (Platform.OS !== "ios") {
|
|
485
|
+
throw Object.assign(new Error("resumeTracking is only supported on iOS."), {
|
|
486
|
+
name: "AsleepPlatformError",
|
|
487
|
+
code: "UNSUPPORTED_PLATFORM",
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
await AsleepModule.resumeTracking();
|
|
492
|
+
},
|
|
493
|
+
|
|
414
494
|
getReport: async (sessionId: string) => {
|
|
415
495
|
// Snapshot the error before the await so we only clear it on success
|
|
416
496
|
// if no concurrent failure (e.g. onTrackingFailed firing during the
|
|
@@ -427,7 +507,7 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
427
507
|
// Guard so a successful query after a clean run does not spam an empty
|
|
428
508
|
// notification, and so we never clobber an unrelated tracking error
|
|
429
509
|
// that arrived during the await.
|
|
430
|
-
if (get().error !== null && get().error === errorBefore) set({ error: null });
|
|
510
|
+
if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
|
|
431
511
|
|
|
432
512
|
// Ensure the report has the expected AsleepReport structure
|
|
433
513
|
// Handle cases where native modules might return data in different formats
|
|
@@ -460,7 +540,7 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
460
540
|
// Metro log still shows the failure when they're debugging without
|
|
461
541
|
// observing `useAsleep().error` directly.
|
|
462
542
|
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReport failed:", error);
|
|
463
|
-
set({ error: error.message });
|
|
543
|
+
set({ error: error.message, errorInfo: null });
|
|
464
544
|
return null;
|
|
465
545
|
}
|
|
466
546
|
},
|
|
@@ -488,11 +568,11 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
488
568
|
});
|
|
489
569
|
|
|
490
570
|
addLog("[getReportList] Success");
|
|
491
|
-
if (get().error !== null && get().error === errorBefore) set({ error: null });
|
|
571
|
+
if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
|
|
492
572
|
return convertedList;
|
|
493
573
|
} catch (error: any) {
|
|
494
574
|
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReportList failed:", error);
|
|
495
|
-
set({ error: error.message });
|
|
575
|
+
set({ error: error.message, errorInfo: null });
|
|
496
576
|
return [];
|
|
497
577
|
}
|
|
498
578
|
},
|
|
@@ -506,9 +586,9 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
506
586
|
await AsleepModule.deleteSession(sessionId);
|
|
507
587
|
|
|
508
588
|
addLog("[deleteSession] Success");
|
|
509
|
-
if (get().error !== null && get().error === errorBefore) set({ error: null });
|
|
589
|
+
if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
|
|
510
590
|
} catch (error: any) {
|
|
511
|
-
set({ error: error.message });
|
|
591
|
+
set({ error: error.message, errorInfo: null });
|
|
512
592
|
throw error;
|
|
513
593
|
}
|
|
514
594
|
},
|
|
@@ -523,11 +603,11 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
523
603
|
const convertedReport = convertKeysToCamelCase(averageReport);
|
|
524
604
|
|
|
525
605
|
addLog("[getAverageReport] Success");
|
|
526
|
-
if (get().error !== null && get().error === errorBefore) set({ error: null });
|
|
606
|
+
if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
|
|
527
607
|
return convertedReport;
|
|
528
608
|
} catch (error: any) {
|
|
529
609
|
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getAverageReport failed:", error);
|
|
530
|
-
set({ error: error.message });
|
|
610
|
+
set({ error: error.message, errorInfo: null });
|
|
531
611
|
return null;
|
|
532
612
|
}
|
|
533
613
|
},
|
|
@@ -578,44 +658,39 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
578
658
|
return AsleepModule.requestRequiredPermissions();
|
|
579
659
|
},
|
|
580
660
|
|
|
581
|
-
setCustomNotification: async (
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
}
|
|
661
|
+
setCustomNotification: async (_title: string, _text: string) => {
|
|
662
|
+
// Native method removed; notification config now flows through startTracking options.
|
|
663
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
664
|
+
console.warn(
|
|
665
|
+
"[Asleep] setCustomNotification is deprecated and a no-op; pass `{ android: { notification: { title, text, icon } } }` to startTracking() instead",
|
|
666
|
+
);
|
|
588
667
|
},
|
|
589
668
|
|
|
590
669
|
enableLog: (print: boolean) => {
|
|
670
|
+
if (Platform.OS === "ios") AsleepModule.enableLog(print);
|
|
591
671
|
set({ showDebugLog: print });
|
|
592
672
|
},
|
|
593
673
|
|
|
594
674
|
requestAnalysis: async () => {
|
|
595
675
|
try {
|
|
596
|
-
const { addLog } = get();
|
|
676
|
+
const { addLog, showDebugLog } = get();
|
|
597
677
|
addLog("[requestAnalysis] Start");
|
|
598
678
|
|
|
599
|
-
set({ isAnalyzing: true, error: null });
|
|
679
|
+
set({ isAnalyzing: true, error: null, errorInfo: null });
|
|
600
680
|
|
|
601
681
|
const result = await AsleepModule.requestAnalysis();
|
|
602
682
|
const convertedResult = convertKeysToCamelCase(result);
|
|
603
683
|
|
|
604
|
-
//
|
|
605
|
-
// Android
|
|
606
|
-
// iOS
|
|
607
|
-
if (Platform.OS === "android" && convertedResult.sleepStages) {
|
|
608
|
-
// Android returns the actual session data
|
|
609
|
-
set({ analysisResult: convertedResult, isAnalyzing: false });
|
|
610
|
-
}
|
|
611
|
-
// For iOS, isAnalyzing will be set to false when onAnalysisResult event fires
|
|
684
|
+
// analysisResult and isAnalyzing are owned by the onAnalysisResult event handler on both
|
|
685
|
+
// platforms. Android resolves the promise with the full session AND fires the event;
|
|
686
|
+
// iOS resolves with an ack only. Writing state here would double-update on Android.
|
|
612
687
|
|
|
613
|
-
addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
|
|
688
|
+
if (showDebugLog) addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
|
|
614
689
|
|
|
615
690
|
return convertedResult;
|
|
616
691
|
} catch (error: any) {
|
|
617
692
|
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] requestAnalysis failed:", error);
|
|
618
|
-
set({ error: error.message, isAnalyzing: false });
|
|
693
|
+
set({ error: error.message, errorInfo: null, isAnalyzing: false });
|
|
619
694
|
return null;
|
|
620
695
|
}
|
|
621
696
|
},
|
|
@@ -632,8 +707,10 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
632
707
|
},
|
|
633
708
|
|
|
634
709
|
// internal actions
|
|
635
|
-
setError
|
|
636
|
-
|
|
710
|
+
// setError takes a raw string, so any structured classification is stale;
|
|
711
|
+
// reset errorInfo rather than let a previous event's category linger.
|
|
712
|
+
setError: (error) => set({ error, errorInfo: null }),
|
|
713
|
+
clearError: () => set({ error: null, errorInfo: null }),
|
|
637
714
|
setUserId: (userId) => set({ userId }),
|
|
638
715
|
setSessionId: (sessionId) => set({ sessionId }),
|
|
639
716
|
setIsTracking: (isTracking) => set({ isTracking }),
|
|
@@ -700,7 +777,9 @@ export const initializeAsleepListeners = (): (() => void) => {
|
|
|
700
777
|
// Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
|
|
701
778
|
onUserJoinFailed: (error: any) => {
|
|
702
779
|
const errorString = JSON.stringify(error);
|
|
703
|
-
|
|
780
|
+
// Not a tracking-runtime failure; errorInfo stays reserved for
|
|
781
|
+
// onTrackingFailed classification.
|
|
782
|
+
useAsleepStore.setState({ error: errorString, errorInfo: null });
|
|
704
783
|
addLog(`[onUserJoinFailed] error: ${errorString}`);
|
|
705
784
|
},
|
|
706
785
|
// Connected: iOS userDidDelete, Android NOT IMPLEMENTED
|
|
@@ -724,6 +803,10 @@ export const initializeAsleepListeners = (): (() => void) => {
|
|
|
724
803
|
// requestAnalysis() flips isAnalyzing internally; no separate setter
|
|
725
804
|
// needed before invoking it (avoids a duplicate subscriber notification).
|
|
726
805
|
const state = useAsleepStore.getState();
|
|
806
|
+
// A completed upload is the only positive proof that recording actually came
|
|
807
|
+
// back — didResume fires before the engine restart is even attempted, so it
|
|
808
|
+
// cannot be trusted to clear this.
|
|
809
|
+
if (state.isRecoveryRequired) useAsleepStore.setState({ isRecoveryRequired: false });
|
|
727
810
|
const triggerAnalysis = () =>
|
|
728
811
|
state.requestAnalysis().catch((error) => {
|
|
729
812
|
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
@@ -744,23 +827,89 @@ export const initializeAsleepListeners = (): (() => void) => {
|
|
|
744
827
|
sessionId: data.sessionId,
|
|
745
828
|
isTracking: false,
|
|
746
829
|
isAnalyzing: false,
|
|
830
|
+
isRecoveryRequired: false,
|
|
747
831
|
didClose: true,
|
|
748
832
|
trackingStartTime: null,
|
|
749
833
|
});
|
|
750
834
|
addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
|
|
751
835
|
},
|
|
752
836
|
// Connected: iOS didFail, Android onFail (AsleepTrackingListener)
|
|
753
|
-
//
|
|
754
|
-
//
|
|
755
|
-
//
|
|
837
|
+
// Four state buckets, each writing tracking state in the same setState as the
|
|
838
|
+
// error so subscribers see one event: terminal (native session already gone),
|
|
839
|
+
// recording-dead (recorder torn down but session still open — clearing
|
|
840
|
+
// isTracking is what unblocks a restart), recovery-required (resumeTracking()
|
|
841
|
+
// in foreground can revive it), and everything else (error only).
|
|
842
|
+
// The two dead-session buckets must also clear isRecoveryRequired: iOS retries
|
|
843
|
+
// cannotActivateInBackground and then gives up with interruptionRecoveryFailed,
|
|
844
|
+
// and no upload will ever arrive to clear the flag on that path.
|
|
845
|
+
// The bucket verdict is also published as errorInfo.category (with the
|
|
846
|
+
// else-bucket split into "transient" vs "unknown") so consumers can gate
|
|
847
|
+
// log severity on data instead of re-deriving code lists themselves.
|
|
756
848
|
onTrackingFailed: (error: any) => {
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
849
|
+
// The explicit iOS string buckets must win before the numeric terminal
|
|
850
|
+
// fallback: the numeric set encodes Android teardown semantics, and iOS
|
|
851
|
+
// reuses 11003 (.audioInitializationFailed -> .audio) for a failure whose
|
|
852
|
+
// session is still open. The numeric fallback still matters on iOS for
|
|
853
|
+
// start/stop failures that arrive as UNKNOWN_ERROR + 22xxx/24xxx and must
|
|
854
|
+
// clear the optimistically-set isTracking.
|
|
855
|
+
const recordingDead = !!(error && RECORDING_DEAD_ERROR_CODES.has(error.code));
|
|
856
|
+
const recoveryRequired = !!(error && RECOVERY_REQUIRED_ERROR_CODES.has(error.code));
|
|
857
|
+
const terminal = !!(
|
|
858
|
+
error &&
|
|
859
|
+
!recordingDead &&
|
|
860
|
+
!recoveryRequired &&
|
|
861
|
+
(TERMINAL_TRACKING_ERROR_CODES.has(error.code) || TERMINAL_TRACKING_SDK_CODES.has(error.sdkCode))
|
|
763
862
|
);
|
|
863
|
+
const transient = !!(error && TRANSIENT_TRACKING_SDK_CODES.has(error.sdkCode));
|
|
864
|
+
|
|
865
|
+
let category: AsleepErrorCategory;
|
|
866
|
+
if (recordingDead) category = "recordingDead";
|
|
867
|
+
else if (recoveryRequired) category = "recoveryRequired";
|
|
868
|
+
else if (terminal) category = "terminal";
|
|
869
|
+
else if (transient) category = "transient";
|
|
870
|
+
else category = "unknown";
|
|
871
|
+
|
|
872
|
+
// Category rides along in the stringified error too, so consumers still
|
|
873
|
+
// parsing the legacy string see the same verdict as errorInfo readers.
|
|
874
|
+
const errorString = JSON.stringify(error ? { ...error, category } : error);
|
|
875
|
+
const errorInfo: AsleepErrorInfo | null = error
|
|
876
|
+
? {
|
|
877
|
+
code: typeof error.code === "string" ? error.code : "UNKNOWN_ERROR",
|
|
878
|
+
category,
|
|
879
|
+
...(typeof error.sdkCode === "number" ? { sdkCode: error.sdkCode } : {}),
|
|
880
|
+
...(typeof error.message === "string" ? { message: error.message } : {}),
|
|
881
|
+
...(typeof error.caseName === "string" ? { caseName: error.caseName } : {}),
|
|
882
|
+
}
|
|
883
|
+
: null;
|
|
884
|
+
|
|
885
|
+
let nextState: Partial<AsleepState>;
|
|
886
|
+
if (terminal) {
|
|
887
|
+
nextState = {
|
|
888
|
+
error: errorString,
|
|
889
|
+
errorInfo,
|
|
890
|
+
isTracking: false,
|
|
891
|
+
isAnalyzing: false,
|
|
892
|
+
isRecoveryRequired: false,
|
|
893
|
+
didClose: true,
|
|
894
|
+
trackingStartTime: null,
|
|
895
|
+
};
|
|
896
|
+
} else if (recordingDead) {
|
|
897
|
+
nextState = {
|
|
898
|
+
error: errorString,
|
|
899
|
+
errorInfo,
|
|
900
|
+
isTracking: false,
|
|
901
|
+
isAnalyzing: false,
|
|
902
|
+
isRecoveryRequired: false,
|
|
903
|
+
didClose: false,
|
|
904
|
+
trackingStartTime: null,
|
|
905
|
+
};
|
|
906
|
+
} else if (recoveryRequired) {
|
|
907
|
+
nextState = { error: errorString, errorInfo, isTracking: true, isRecoveryRequired: true };
|
|
908
|
+
} else {
|
|
909
|
+
nextState = { error: errorString, errorInfo };
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
useAsleepStore.setState(nextState);
|
|
764
913
|
addLog(`[onTrackingError] error: ${errorString}`);
|
|
765
914
|
},
|
|
766
915
|
// Connected: iOS didInterrupt, Android NOT IMPLEMENTED
|
|
@@ -773,16 +922,20 @@ export const initializeAsleepListeners = (): (() => void) => {
|
|
|
773
922
|
// retry) reach this handler without a preceding didInterrupt, and the stale error
|
|
774
923
|
// should still be cleared. Only the paused-state mutation is gated, to dedup the
|
|
775
924
|
// iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
|
|
925
|
+
// isRecoveryRequired, not isTrackingPaused, is authoritative when recording is
|
|
926
|
+
// dead because didResume fires before the engine restart is attempted.
|
|
776
927
|
onTrackingResumed: () => {
|
|
777
928
|
const wasPaused = useAsleepStore.getState().isTrackingPaused;
|
|
778
|
-
useAsleepStore.setState(
|
|
929
|
+
useAsleepStore.setState(
|
|
930
|
+
wasPaused ? { error: null, errorInfo: null, isTrackingPaused: false } : { error: null, errorInfo: null },
|
|
931
|
+
);
|
|
779
932
|
addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
|
|
780
933
|
},
|
|
781
934
|
// Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
|
|
782
935
|
onMicPermissionDenied: () => {
|
|
783
936
|
addLog(`[onMicPermissionDenied]`);
|
|
784
937
|
},
|
|
785
|
-
// Connected: iOS
|
|
938
|
+
// Connected: iOS AsleepLogger callbacks, Android sendEvent called directly
|
|
786
939
|
onDebugLog: (data: any) => {
|
|
787
940
|
addLog(`[onDebugLog] message: ${data.message}`);
|
|
788
941
|
},
|
|
@@ -794,7 +947,12 @@ export const initializeAsleepListeners = (): (() => void) => {
|
|
|
794
947
|
// Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
|
|
795
948
|
onSetupDidFail: (data: any) => {
|
|
796
949
|
const errorString = JSON.stringify(data);
|
|
797
|
-
useAsleepStore.setState({
|
|
950
|
+
useAsleepStore.setState({
|
|
951
|
+
error: errorString,
|
|
952
|
+
errorInfo: null,
|
|
953
|
+
isSetupInProgress: false,
|
|
954
|
+
isSetupComplete: false,
|
|
955
|
+
});
|
|
798
956
|
addLog(`[onSetupDidFail] error: ${errorString}`);
|
|
799
957
|
},
|
|
800
958
|
// Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
|
|
@@ -803,9 +961,13 @@ export const initializeAsleepListeners = (): (() => void) => {
|
|
|
803
961
|
addLog(`[onSetupInProgress] progress: ${data.progress}%`);
|
|
804
962
|
},
|
|
805
963
|
// Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
|
|
964
|
+
// Android serializes snake_case; normalize so both platforms match AsleepAnalysisResult.
|
|
806
965
|
onAnalysisResult: (data: any) => {
|
|
807
|
-
|
|
808
|
-
|
|
966
|
+
const normalized = convertKeysToCamelCase(data);
|
|
967
|
+
useAsleepStore.setState({ analysisResult: normalized, isAnalyzing: false });
|
|
968
|
+
if (useAsleepStore.getState().showDebugLog) {
|
|
969
|
+
addLog(`[onAnalysisResult] ${JSON.stringify(normalized)}`);
|
|
970
|
+
}
|
|
809
971
|
},
|
|
810
972
|
};
|
|
811
973
|
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from "expo-modules-core";
|
|
2
2
|
import { useEffect } from "react";
|
|
3
|
-
import { Alert
|
|
3
|
+
import { Alert } from "react-native";
|
|
4
4
|
import {
|
|
5
5
|
AsleepConfig,
|
|
6
6
|
AsleepSetupConfig,
|
|
@@ -108,12 +108,11 @@ class Asleep {
|
|
|
108
108
|
return AsleepModule.requestRequiredPermissions();
|
|
109
109
|
};
|
|
110
110
|
|
|
111
|
-
setCustomNotification = async (
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
111
|
+
setCustomNotification = async (_title: string, _text: string): Promise<void> => {
|
|
112
|
+
// Native method removed; notification config now flows through startTracking options.
|
|
113
|
+
console.warn(
|
|
114
|
+
"[Asleep] setCustomNotification is deprecated and a no-op; pass `{ android: { notification: { title, text, icon } } }` to startTracking() instead",
|
|
115
|
+
);
|
|
117
116
|
};
|
|
118
117
|
|
|
119
118
|
private convertKeysToCamelCase = (obj: any): any => {
|
|
@@ -152,7 +151,9 @@ export const useAsleep = () => {
|
|
|
152
151
|
const {
|
|
153
152
|
didClose,
|
|
154
153
|
isTracking,
|
|
154
|
+
isRecoveryRequired,
|
|
155
155
|
error,
|
|
156
|
+
errorInfo,
|
|
156
157
|
userId,
|
|
157
158
|
sessionId,
|
|
158
159
|
log,
|
|
@@ -163,6 +164,7 @@ export const useAsleep = () => {
|
|
|
163
164
|
requestBatteryOptimizationExemption,
|
|
164
165
|
startTracking,
|
|
165
166
|
stopTracking,
|
|
167
|
+
resumeTracking,
|
|
166
168
|
getReport,
|
|
167
169
|
getReportList,
|
|
168
170
|
getAverageReport,
|
|
@@ -193,7 +195,9 @@ export const useAsleep = () => {
|
|
|
193
195
|
return {
|
|
194
196
|
didClose,
|
|
195
197
|
isTracking,
|
|
198
|
+
isRecoveryRequired,
|
|
196
199
|
error,
|
|
200
|
+
errorInfo,
|
|
197
201
|
userId,
|
|
198
202
|
sessionId,
|
|
199
203
|
log,
|
|
@@ -206,6 +210,7 @@ export const useAsleep = () => {
|
|
|
206
210
|
requestBatteryOptimizationExemption,
|
|
207
211
|
startTracking,
|
|
208
212
|
stopTracking,
|
|
213
|
+
resumeTracking,
|
|
209
214
|
getReport,
|
|
210
215
|
getReportList,
|
|
211
216
|
getAverageReport,
|
|
@@ -244,6 +249,8 @@ export const AsleepSDK = {
|
|
|
244
249
|
|
|
245
250
|
stopTracking: () => useAsleepStore.getState().stopTracking(),
|
|
246
251
|
|
|
252
|
+
resumeTracking: () => useAsleepStore.getState().resumeTracking(),
|
|
253
|
+
|
|
247
254
|
getReport: (sessionId: string) => useAsleepStore.getState().getReport(sessionId),
|
|
248
255
|
|
|
249
256
|
getReportList: (fromDate: string, toDate: string) => useAsleepStore.getState().getReportList(fromDate, toDate),
|
|
@@ -260,6 +267,8 @@ export const AsleepSDK = {
|
|
|
260
267
|
|
|
261
268
|
isTracking: () => useAsleepStore.getState().isTracking,
|
|
262
269
|
|
|
270
|
+
isRecoveryRequired: () => useAsleepStore.getState().isRecoveryRequired,
|
|
271
|
+
|
|
263
272
|
isAnalyzing: () => useAsleepStore.getState().isAnalyzing,
|
|
264
273
|
|
|
265
274
|
isSetupInProgress: () => useAsleepStore.getState().isSetupInProgress,
|
|
@@ -291,6 +300,8 @@ export default asleep;
|
|
|
291
300
|
export type {
|
|
292
301
|
AsleepConfig,
|
|
293
302
|
AsleepSetupConfig,
|
|
303
|
+
AsleepErrorCategory,
|
|
304
|
+
AsleepErrorInfo,
|
|
294
305
|
AsleepEventType,
|
|
295
306
|
AsleepReport,
|
|
296
307
|
AsleepSession,
|
|
@@ -299,5 +310,6 @@ export type {
|
|
|
299
310
|
AsleepNeverSleptSession,
|
|
300
311
|
AsleepStat,
|
|
301
312
|
AsleepAnalysisResult,
|
|
313
|
+
AsleepAnalysisAck,
|
|
302
314
|
TrackingConfig,
|
|
303
315
|
} from "./Asleep.types";
|