react-native-asleep 1.0.18 → 1.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.
- package/README.md +164 -282
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +52 -23
- package/build/Asleep.types.d.ts +46 -0
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js +24 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +45 -41
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +518 -531
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +11 -108
- package/build/index.d.ts.map +1 -1
- package/build/index.js +18 -183
- package/build/index.js.map +1 -1
- package/build/store/createStore.d.ts +14 -0
- package/build/store/createStore.d.ts.map +1 -0
- package/build/store/createStore.js +63 -0
- package/build/store/createStore.js.map +1 -0
- package/ios/AsleepModule.swift +64 -4
- package/package.json +3 -5
- package/src/Asleep.types.ts +71 -1
- package/src/AsleepStore.ts +733 -740
- package/src/index.ts +37 -281
- package/src/store/createStore.ts +84 -0
package/src/AsleepStore.ts
CHANGED
|
@@ -1,64 +1,62 @@
|
|
|
1
|
-
import { create } from "zustand";
|
|
2
|
-
import { subscribeWithSelector } from "zustand/middleware";
|
|
3
1
|
import { EventEmitter } from "expo-modules-core";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
2
|
+
import { PermissionsAndroid, Platform } from "react-native";
|
|
3
|
+
import type {
|
|
4
|
+
AsleepAnalysisAck,
|
|
5
|
+
AsleepAnalysisResult,
|
|
6
|
+
AsleepAverageReport,
|
|
6
7
|
AsleepConfig,
|
|
7
|
-
|
|
8
|
+
AsleepErrorCategory,
|
|
8
9
|
AsleepEventType,
|
|
9
10
|
AsleepReport,
|
|
10
11
|
AsleepSession,
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
AsleepSetupConfig,
|
|
13
|
+
SetupStatus,
|
|
13
14
|
TrackingConfig,
|
|
15
|
+
TrackingStatus,
|
|
14
16
|
} from "./Asleep.types";
|
|
17
|
+
import { AsleepError } from "./Asleep.types";
|
|
15
18
|
import AsleepModule from "./AsleepModule";
|
|
19
|
+
import { createStore } from "./store/createStore";
|
|
16
20
|
|
|
17
21
|
const emitter = new EventEmitter(AsleepModule);
|
|
18
22
|
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
//
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
//
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
//
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
// Compensations" for the upstream behavior these guard against.
|
|
33
|
-
const TERMINAL_TRACKING_ERROR_CODES = new Set<string>([
|
|
34
|
-
"UPLOAD_TRACKING_TERMINATED", // iOS 403/429 closeSessionSilently; Android errorCode 23499
|
|
35
|
-
"INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
|
|
23
|
+
// Native sessions are already gone for these errors and no close event follows.
|
|
24
|
+
const TERMINAL_TRACKING_ERROR_CODES = new Set<string>(["UPLOAD_TRACKING_TERMINATED", "INTERRUPTION_RECOVERY_FAILED"]);
|
|
25
|
+
|
|
26
|
+
// iOS 3.2.0 stops recording but leaves the native session open.
|
|
27
|
+
const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED"]);
|
|
28
|
+
|
|
29
|
+
// iOS 3.2.0 needs an explicit foreground resume after this failure.
|
|
30
|
+
const RECOVERY_REQUIRED_ERROR_CODES = new Set<string>(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
|
|
31
|
+
|
|
32
|
+
// Android SDK 3.2.x tears the session down for exactly these codes. Keep this
|
|
33
|
+
// synchronized with AsleepModule.kt's TERMINAL_TRACKING_ERROR_CODES.
|
|
34
|
+
const TERMINAL_TRACKING_SDK_CODES = new Set<number>([
|
|
35
|
+
11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500,
|
|
36
36
|
]);
|
|
37
37
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
38
|
+
// The native session survives these exhausted upload attempts.
|
|
39
|
+
const TRANSIENT_TRACKING_SDK_CODES = new Set<number>([23000, 23500]);
|
|
40
|
+
|
|
41
|
+
export interface InternalAsleepState {
|
|
42
|
+
setupStatus: SetupStatus;
|
|
43
|
+
trackingStatus: TrackingStatus;
|
|
44
44
|
sessionId: string | null;
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
userId: string | null;
|
|
46
|
+
error: AsleepError | null;
|
|
47
47
|
analysisResult: AsleepAnalysisResult | null;
|
|
48
|
-
isODAEnabled: boolean;
|
|
49
48
|
isAnalyzing: boolean;
|
|
49
|
+
didClose: boolean;
|
|
50
|
+
isODAEnabled: boolean;
|
|
50
51
|
trackingStartTime: Date | null;
|
|
51
52
|
isInitialized: boolean;
|
|
52
|
-
isSetupInProgress: boolean;
|
|
53
|
-
isSetupComplete: boolean;
|
|
54
|
-
|
|
55
|
-
// Service status tracking
|
|
56
53
|
hasCheckedStatus: boolean;
|
|
57
|
-
|
|
58
|
-
// Battery optimization tracking
|
|
59
54
|
hasCheckedBatteryOptimization: boolean;
|
|
55
|
+
showDebugLog: boolean;
|
|
56
|
+
log: string;
|
|
57
|
+
}
|
|
60
58
|
|
|
61
|
-
|
|
59
|
+
export interface AsleepActions {
|
|
62
60
|
setup: (config: AsleepSetupConfig) => Promise<void>;
|
|
63
61
|
initAsleepConfig: (config: AsleepConfig) => Promise<void>;
|
|
64
62
|
checkAndRestoreTracking: () => Promise<{ hasActiveSession: boolean }>;
|
|
@@ -66,202 +64,269 @@ export interface AsleepState {
|
|
|
66
64
|
requestBatteryOptimizationExemption: () => Promise<boolean>;
|
|
67
65
|
startTracking: (config?: TrackingConfig) => Promise<void>;
|
|
68
66
|
stopTracking: () => Promise<void>;
|
|
69
|
-
|
|
67
|
+
resumeTracking: () => Promise<void>;
|
|
68
|
+
getReport: (sessionId: string) => Promise<AsleepReport>;
|
|
70
69
|
getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
|
|
71
|
-
getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport
|
|
70
|
+
getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport>;
|
|
72
71
|
deleteSession: (sessionId: string) => Promise<void>;
|
|
73
|
-
|
|
72
|
+
requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck>;
|
|
73
|
+
hasRequiredPermissions: () => Promise<boolean>;
|
|
74
74
|
requestRequiredPermissions: () => Promise<boolean>;
|
|
75
75
|
setCustomNotification: (title: string, text: string) => Promise<void>;
|
|
76
76
|
enableLog: (print: boolean) => void;
|
|
77
77
|
clearError: () => void;
|
|
78
|
-
requestAnalysis: () => Promise<AsleepAnalysisResult | null>;
|
|
79
78
|
addEventListener: <K extends keyof AsleepEventType>(
|
|
80
79
|
eventType: K,
|
|
81
80
|
listener: (data: AsleepEventType[K]) => void,
|
|
82
81
|
) => () => void;
|
|
83
|
-
getTrackingDurationMinutes: () => number;
|
|
84
|
-
|
|
85
|
-
// internal actions
|
|
86
|
-
setError: (error: string | null) => void;
|
|
87
|
-
setUserId: (userId: string | null) => void;
|
|
88
|
-
setSessionId: (sessionId: string | null) => void;
|
|
89
|
-
setIsTracking: (isTracking: boolean) => void;
|
|
90
|
-
setIsTrackingPaused: (isTrackingPaused: boolean) => void;
|
|
91
|
-
setDidClose: (didClose: boolean) => void;
|
|
92
|
-
setAnalysisResult: (result: AsleepAnalysisResult | null) => void;
|
|
93
|
-
setIsAnalyzing: (isAnalyzing: boolean) => void;
|
|
94
|
-
setTrackingStartTime: (time: Date | null) => void;
|
|
95
|
-
setIsInitialized: (initialized: boolean) => void;
|
|
96
|
-
setIsSetupInProgress: (inProgress: boolean) => void;
|
|
97
|
-
setIsSetupComplete: (complete: boolean) => void;
|
|
98
|
-
setHasCheckedStatus: (checked: boolean) => void;
|
|
99
|
-
setHasCheckedBatteryOptimization: (checked: boolean) => void;
|
|
100
|
-
addLog: (log: string) => void;
|
|
101
82
|
}
|
|
102
83
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
84
|
+
export interface AsleepPublicState {
|
|
85
|
+
status: TrackingStatus;
|
|
86
|
+
isTracking: boolean;
|
|
87
|
+
isTrackingPaused: boolean;
|
|
88
|
+
isRecoveryRequired: boolean;
|
|
89
|
+
isSetupInProgress: boolean;
|
|
90
|
+
isSetupComplete: boolean;
|
|
91
|
+
sessionId: string | null;
|
|
92
|
+
userId: string | null;
|
|
93
|
+
error: AsleepError | null;
|
|
94
|
+
analysisResult: AsleepAnalysisResult | null;
|
|
95
|
+
isAnalyzing: boolean;
|
|
96
|
+
didClose: boolean;
|
|
97
|
+
isODAEnabled: boolean;
|
|
98
|
+
log: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type AsleepPublicApi = AsleepPublicState & AsleepActions;
|
|
102
|
+
|
|
103
|
+
const initialTrackingStatus: TrackingStatus =
|
|
104
|
+
typeof AsleepModule.isTracking === "function" && AsleepModule.isTracking() ? "tracking" : "idle";
|
|
105
|
+
|
|
106
|
+
export const useAsleepStore = createStore<InternalAsleepState>(() => ({
|
|
107
|
+
setupStatus: "idle",
|
|
108
|
+
trackingStatus: initialTrackingStatus,
|
|
109
|
+
sessionId: null,
|
|
110
|
+
userId: null,
|
|
111
|
+
error: null,
|
|
112
|
+
analysisResult: null,
|
|
113
|
+
isAnalyzing: false,
|
|
114
|
+
didClose: false,
|
|
115
|
+
isODAEnabled: false,
|
|
116
|
+
trackingStartTime: null,
|
|
117
|
+
isInitialized: false,
|
|
118
|
+
hasCheckedStatus: false,
|
|
119
|
+
hasCheckedBatteryOptimization: false,
|
|
120
|
+
showDebugLog: false,
|
|
121
|
+
log: "",
|
|
122
|
+
}));
|
|
123
|
+
|
|
124
|
+
const convertKeysToCamelCase = (value: any): any => {
|
|
125
|
+
if (Array.isArray(value)) return value.map(convertKeysToCamelCase);
|
|
126
|
+
if (value !== null && value.constructor === Object) {
|
|
127
|
+
return Object.keys(value).reduce((result, key) => {
|
|
128
|
+
const camelKey = key.replace(/_([a-z])/g, (_match, letter: string) => letter.toUpperCase());
|
|
129
|
+
result[camelKey] = convertKeysToCamelCase(value[key]);
|
|
130
|
+
return result;
|
|
111
131
|
}, {} as any);
|
|
112
132
|
}
|
|
113
|
-
return
|
|
133
|
+
return value;
|
|
114
134
|
};
|
|
115
135
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
isTrackingPaused: false,
|
|
122
|
-
error: null,
|
|
123
|
-
userId: null,
|
|
124
|
-
sessionId: null,
|
|
125
|
-
showDebugLog: false,
|
|
126
|
-
log: "",
|
|
127
|
-
analysisResult: null,
|
|
128
|
-
isODAEnabled: false,
|
|
129
|
-
isAnalyzing: false,
|
|
130
|
-
trackingStartTime: null,
|
|
131
|
-
isInitialized: false,
|
|
132
|
-
isSetupInProgress: false,
|
|
133
|
-
isSetupComplete: false,
|
|
134
|
-
|
|
135
|
-
// Service status state
|
|
136
|
-
hasCheckedStatus: false,
|
|
137
|
-
|
|
138
|
-
// Battery optimization state
|
|
139
|
-
hasCheckedBatteryOptimization: false,
|
|
140
|
-
|
|
141
|
-
// actions
|
|
142
|
-
setup: async (config: AsleepSetupConfig) => {
|
|
143
|
-
try {
|
|
144
|
-
const { addLog, isSetupInProgress, isTracking } = get();
|
|
145
|
-
|
|
146
|
-
// Prevent duplicate execution if setup is already in progress
|
|
147
|
-
if (isSetupInProgress) {
|
|
148
|
-
addLog("[setup] Setup is already in progress. Please try again later.");
|
|
149
|
-
throw new Error("Setup is already in progress.");
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// Block setup execution if tracking is in progress
|
|
153
|
-
if (isTracking) {
|
|
154
|
-
addLog("[setup] Cannot execute setup while tracking is in progress.");
|
|
155
|
-
throw new Error("Cannot execute setup while tracking is in progress.");
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
addLog("[setup] Start");
|
|
159
|
-
set({ isSetupInProgress: true, error: null });
|
|
160
|
-
|
|
161
|
-
await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
|
|
162
|
-
|
|
163
|
-
// Store ODA enabled state. Clearing `error` on success keeps the
|
|
164
|
-
// reactive `useAsleep().error` field aligned with the actual SDK status
|
|
165
|
-
// (no stale failure messages after a successful retry).
|
|
166
|
-
set({
|
|
167
|
-
isODAEnabled: config.enableODA || false,
|
|
168
|
-
isInitialized: true,
|
|
169
|
-
isSetupInProgress: false,
|
|
170
|
-
isSetupComplete: true,
|
|
171
|
-
error: null,
|
|
172
|
-
});
|
|
173
|
-
addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
|
|
174
|
-
} catch (error: any) {
|
|
175
|
-
set({ error: error.message, isSetupInProgress: false });
|
|
176
|
-
throw error;
|
|
177
|
-
}
|
|
178
|
-
},
|
|
179
|
-
|
|
180
|
-
initAsleepConfig: async (config: AsleepConfig) => {
|
|
181
|
-
try {
|
|
182
|
-
const { addLog } = get();
|
|
183
|
-
addLog("[initAsleepConfig] Start");
|
|
184
|
-
|
|
185
|
-
const result = await AsleepModule.initAsleepConfig(
|
|
186
|
-
config.apiKey,
|
|
187
|
-
config.userId,
|
|
188
|
-
config.baseUrl,
|
|
189
|
-
config.callbackUrl,
|
|
190
|
-
);
|
|
136
|
+
type ErrorOptions = {
|
|
137
|
+
category?: AsleepErrorCategory;
|
|
138
|
+
sdkCode?: number;
|
|
139
|
+
caseName?: string;
|
|
140
|
+
};
|
|
191
141
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
142
|
+
export const normalizeError = (source: unknown, fallbackCode: string, options: ErrorOptions = {}): AsleepError => {
|
|
143
|
+
if (source instanceof AsleepError && Object.keys(options).length === 0) return source;
|
|
144
|
+
|
|
145
|
+
const payload =
|
|
146
|
+
source && typeof source === "object"
|
|
147
|
+
? (source as {
|
|
148
|
+
code?: unknown;
|
|
149
|
+
message?: unknown;
|
|
150
|
+
error?: unknown;
|
|
151
|
+
detail?: unknown;
|
|
152
|
+
sdkCode?: unknown;
|
|
153
|
+
caseName?: unknown;
|
|
154
|
+
})
|
|
155
|
+
: undefined;
|
|
156
|
+
const code = typeof payload?.code === "string" ? payload.code : fallbackCode;
|
|
157
|
+
const message =
|
|
158
|
+
typeof payload?.message === "string"
|
|
159
|
+
? payload.message
|
|
160
|
+
: typeof payload?.error === "string"
|
|
161
|
+
? payload.error
|
|
162
|
+
: typeof payload?.detail === "string"
|
|
163
|
+
? payload.detail
|
|
164
|
+
: source instanceof Error
|
|
165
|
+
? source.message
|
|
166
|
+
: String(source ?? "Unknown error");
|
|
167
|
+
|
|
168
|
+
return new AsleepError(code, message, {
|
|
169
|
+
cause: source instanceof AsleepError ? (source.cause ?? source) : source,
|
|
170
|
+
category: options.category ?? (source instanceof AsleepError ? source.category : undefined),
|
|
171
|
+
sdkCode:
|
|
172
|
+
options.sdkCode ??
|
|
173
|
+
(typeof payload?.sdkCode === "number"
|
|
174
|
+
? payload.sdkCode
|
|
175
|
+
: source instanceof AsleepError
|
|
176
|
+
? source.sdkCode
|
|
177
|
+
: undefined),
|
|
178
|
+
caseName:
|
|
179
|
+
options.caseName ??
|
|
180
|
+
(typeof payload?.caseName === "string"
|
|
181
|
+
? payload.caseName
|
|
182
|
+
: source instanceof AsleepError
|
|
183
|
+
? source.caseName
|
|
184
|
+
: undefined),
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const logPartial = (message: string, state = useAsleepStore.getState()): Partial<InternalAsleepState> => {
|
|
189
|
+
if (!state.showDebugLog) return {};
|
|
190
|
+
const now = new Date();
|
|
191
|
+
const time = `${now.getHours().toString().padStart(2, "0")}:${now
|
|
192
|
+
.getMinutes()
|
|
193
|
+
.toString()
|
|
194
|
+
.padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
|
|
195
|
+
const log = `[${time}]${message}`;
|
|
196
|
+
console.log(`[Asleep]${log}`);
|
|
197
|
+
return { log };
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
const addLog = (message: string) => {
|
|
201
|
+
useAsleepStore.setState(logPartial(message));
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const storeAndThrow = (error: AsleepError, partial: Partial<InternalAsleepState> = {}): never => {
|
|
205
|
+
useAsleepStore.setState({ ...partial, error });
|
|
206
|
+
throw error;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const guardedFailure = (
|
|
210
|
+
source: unknown,
|
|
211
|
+
fallbackCode: string,
|
|
212
|
+
errorBefore: AsleepError | null,
|
|
213
|
+
partial: Partial<InternalAsleepState> = {},
|
|
214
|
+
): never => {
|
|
215
|
+
const current = useAsleepStore.getState().error;
|
|
216
|
+
if (current !== null && current !== errorBefore) {
|
|
217
|
+
useAsleepStore.setState(partial);
|
|
218
|
+
throw current;
|
|
219
|
+
}
|
|
220
|
+
return storeAndThrow(normalizeError(source, fallbackCode), partial);
|
|
221
|
+
};
|
|
255
222
|
|
|
223
|
+
const clearErrorIfUnchanged = (errorBefore: AsleepError | null) => {
|
|
224
|
+
const current = useAsleepStore.getState().error;
|
|
225
|
+
if (current !== null && current === errorBefore) useAsleepStore.setState({ error: null });
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const normalizeReport = (report: any, sessionId: string): AsleepReport => {
|
|
229
|
+
const converted = convertKeysToCamelCase(report);
|
|
230
|
+
if (converted && !converted.session && converted.sessionId) {
|
|
231
|
+
return {
|
|
232
|
+
timezone: converted.timezone || "",
|
|
233
|
+
session: {
|
|
234
|
+
id: converted.sessionId || converted.id || sessionId,
|
|
235
|
+
createdTimezone: converted.createdTimezone || "",
|
|
236
|
+
startTime: converted.sessionStartTime || converted.startTime || "",
|
|
237
|
+
endTime: converted.sessionEndTime || converted.endTime,
|
|
238
|
+
unexpectedEndTime: converted.unexpectedEndTime,
|
|
239
|
+
state: converted.state || "",
|
|
240
|
+
sleepStages: converted.sleepStages,
|
|
241
|
+
breathStages: converted.breathStages,
|
|
242
|
+
snoringStages: converted.snoringStages,
|
|
243
|
+
},
|
|
244
|
+
missingDataRatio: converted.missingDataRatio || 0,
|
|
245
|
+
peculiarities: converted.peculiarities || [],
|
|
246
|
+
stat: converted.stat,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
return converted as AsleepReport;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
export const asleepActions: AsleepActions = {
|
|
253
|
+
setup: async (config) => {
|
|
254
|
+
const state = useAsleepStore.getState();
|
|
255
|
+
if (state.setupStatus === "inProgress") {
|
|
256
|
+
storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
|
|
257
|
+
}
|
|
258
|
+
if (state.trackingStatus !== "idle") {
|
|
259
|
+
storeAndThrow(new AsleepError("INVALID_STATE", "Cannot execute setup while tracking is in progress."));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const errorBefore = state.error;
|
|
263
|
+
addLog("[setup] Start");
|
|
264
|
+
useAsleepStore.setState({ setupStatus: "inProgress" });
|
|
265
|
+
try {
|
|
266
|
+
await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
|
|
267
|
+
useAsleepStore.setState({
|
|
268
|
+
setupStatus: "complete",
|
|
269
|
+
isODAEnabled: config.enableODA || false,
|
|
270
|
+
isInitialized: true,
|
|
271
|
+
});
|
|
272
|
+
clearErrorIfUnchanged(errorBefore);
|
|
273
|
+
addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
|
|
274
|
+
} catch (error) {
|
|
275
|
+
return guardedFailure(error, "SETUP_FAILED", errorBefore, { setupStatus: "idle" });
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
|
|
279
|
+
initAsleepConfig: async (config) => {
|
|
280
|
+
const state = useAsleepStore.getState();
|
|
281
|
+
if (state.setupStatus === "inProgress") {
|
|
282
|
+
return storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
|
|
283
|
+
}
|
|
284
|
+
// No tracking-state guard here: checkAndRestoreTracking() reconnects a live
|
|
285
|
+
// session before the app configures the SDK, so this must remain callable
|
|
286
|
+
// while trackingStatus is "tracking" (v1 behavior the restore flow relies on).
|
|
287
|
+
const errorBefore = state.error;
|
|
288
|
+
addLog("[initAsleepConfig] Start");
|
|
289
|
+
useAsleepStore.setState({ setupStatus: "inProgress" });
|
|
290
|
+
try {
|
|
291
|
+
await AsleepModule.initAsleepConfig(config.apiKey, config.userId, config.baseUrl, config.callbackUrl);
|
|
292
|
+
useAsleepStore.setState({ setupStatus: "complete", isInitialized: true });
|
|
293
|
+
clearErrorIfUnchanged(errorBefore);
|
|
294
|
+
addLog("[initAsleepConfig] Success");
|
|
295
|
+
} catch (error) {
|
|
296
|
+
return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, { setupStatus: "idle" });
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
checkAndRestoreTracking: async () => {
|
|
301
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
302
|
+
addLog("[checkAndRestoreTracking] Start");
|
|
303
|
+
try {
|
|
304
|
+
const isAlive = await AsleepModule.isSleepTrackingAlive();
|
|
305
|
+
let trackingStatus = useAsleepStore.getState().trackingStatus;
|
|
306
|
+
if (isAlive && Platform.OS === "android") {
|
|
307
|
+
const isConnected = await AsleepModule.connectSleepTracking();
|
|
308
|
+
if (isConnected) trackingStatus = "tracking";
|
|
309
|
+
}
|
|
310
|
+
useAsleepStore.setState({ hasCheckedStatus: true, trackingStatus });
|
|
311
|
+
clearErrorIfUnchanged(errorBefore);
|
|
312
|
+
addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
|
|
313
|
+
return { hasActiveSession: isAlive };
|
|
314
|
+
} catch (error) {
|
|
315
|
+
return guardedFailure(error, "CHECK_AND_RESTORE_FAILED", errorBefore);
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
|
|
319
|
+
checkBatteryOptimization: async () => {
|
|
320
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
321
|
+
addLog("[checkBatteryOptimization] Checking battery optimization status...");
|
|
322
|
+
useAsleepStore.setState({ hasCheckedBatteryOptimization: true });
|
|
323
|
+
try {
|
|
256
324
|
if (Platform.OS === "ios") {
|
|
257
|
-
|
|
325
|
+
clearErrorIfUnchanged(errorBefore);
|
|
258
326
|
return { exempted: true, platform: "ios" };
|
|
259
327
|
}
|
|
260
|
-
|
|
261
|
-
// Android: Check current status
|
|
262
328
|
const exempted = await AsleepModule.isBatteryOptimizationExempted();
|
|
263
|
-
|
|
264
|
-
|
|
329
|
+
clearErrorIfUnchanged(errorBefore);
|
|
265
330
|
return {
|
|
266
331
|
exempted,
|
|
267
332
|
platform: "android",
|
|
@@ -269,566 +334,494 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
269
334
|
? "Battery optimization disabled - ready for tracking"
|
|
270
335
|
: "Battery optimization must be disabled for reliable tracking",
|
|
271
336
|
};
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
337
|
+
} catch (error) {
|
|
338
|
+
return guardedFailure(error, "CHECK_BATTERY_OPTIMIZATION_FAILED", errorBefore);
|
|
339
|
+
}
|
|
340
|
+
},
|
|
341
|
+
|
|
342
|
+
requestBatteryOptimizationExemption: async () => {
|
|
343
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
344
|
+
if (Platform.OS === "ios") {
|
|
345
|
+
clearErrorIfUnchanged(errorBefore);
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
const result = await AsleepModule.requestBatteryOptimizationExemption();
|
|
350
|
+
clearErrorIfUnchanged(errorBefore);
|
|
351
|
+
return result;
|
|
352
|
+
} catch (error) {
|
|
353
|
+
return guardedFailure(error, "REQUEST_BATTERY_EXEMPTION_FAILED", errorBefore);
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
|
|
357
|
+
startTracking: async (config) => {
|
|
358
|
+
const state = useAsleepStore.getState();
|
|
359
|
+
if (!state.hasCheckedStatus) {
|
|
360
|
+
storeAndThrow(
|
|
361
|
+
new AsleepError(
|
|
362
|
+
"MISSING_PREREQUISITE",
|
|
363
|
+
"Must call checkAndRestoreTracking() at app startup before starting tracking.",
|
|
364
|
+
),
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
if (!state.hasCheckedBatteryOptimization) {
|
|
368
|
+
storeAndThrow(
|
|
369
|
+
new AsleepError("MISSING_PREREQUISITE", "Must call checkBatteryOptimization() before starting tracking."),
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
if (state.setupStatus === "inProgress") {
|
|
373
|
+
storeAndThrow(new AsleepError("INVALID_STATE", "Cannot start tracking while setup is in progress."));
|
|
374
|
+
}
|
|
375
|
+
if (state.trackingStatus !== "idle") {
|
|
376
|
+
storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Tracking is already in progress."));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const errorBefore = state.error;
|
|
380
|
+
try {
|
|
381
|
+
if (!(await asleepActions.hasRequiredPermissions())) {
|
|
382
|
+
storeAndThrow(
|
|
383
|
+
new AsleepError(
|
|
384
|
+
"PERMISSION_DENIED",
|
|
385
|
+
"Microphone permission is required. Call requestRequiredPermissions() before startTracking().",
|
|
386
|
+
),
|
|
387
|
+
);
|
|
289
388
|
}
|
|
290
389
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* Starts sleep tracking session.
|
|
300
|
-
*
|
|
301
|
-
* Prerequisites:
|
|
302
|
-
* 1. checkAndRestoreTracking() must be called at app startup
|
|
303
|
-
* 2. checkBatteryOptimization() must be called (required on both platforms)
|
|
304
|
-
*
|
|
305
|
-
* @param config Optional tracking configuration
|
|
306
|
-
* @throws Error if prerequisites are not met or tracking is already in progress
|
|
307
|
-
*/
|
|
308
|
-
startTracking: async (config?: TrackingConfig) => {
|
|
309
|
-
try {
|
|
310
|
-
const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
|
|
311
|
-
|
|
312
|
-
// Enforce that checkAndRestoreTracking must be called first
|
|
313
|
-
if (!hasCheckedStatus) {
|
|
314
|
-
addLog("[startTracking] Must call checkAndRestoreTracking() at app startup");
|
|
315
|
-
throw new Error("Must call checkAndRestoreTracking() at app startup before starting tracking");
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// Enforce battery optimization check on BOTH platforms for consistency
|
|
319
|
-
// This ensures iOS developers handle battery optimization for their Android users
|
|
320
|
-
if (!get().hasCheckedBatteryOptimization) {
|
|
321
|
-
addLog("[startTracking] ERROR: Must check battery optimization first");
|
|
322
|
-
throw new Error(
|
|
323
|
-
"Must call checkBatteryOptimization() before starting tracking. " +
|
|
324
|
-
"This check is required on both iOS and Android to ensure cross-platform consistency.",
|
|
325
|
-
);
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
// Block startTracking execution if setup is in progress
|
|
329
|
-
if (isSetupInProgress) {
|
|
330
|
-
addLog("[startTracking] Cannot start tracking while setup is in progress.");
|
|
331
|
-
throw new Error("Cannot start tracking while setup is in progress.");
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// Prevent duplicate execution if already tracking
|
|
335
|
-
if (get().isTracking) {
|
|
336
|
-
addLog("[startTracking] Tracking is already in progress.");
|
|
337
|
-
throw new Error("Tracking is already in progress.");
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
addLog("[startTracking] Start");
|
|
341
|
-
|
|
342
|
-
const permission = await requestRequiredPermissions();
|
|
343
|
-
if (!permission) {
|
|
344
|
-
// SDK shouldn't show UI directly - throw specific error message
|
|
345
|
-
if (Platform.OS === "android" && Platform.Version >= 33) {
|
|
346
|
-
throw new Error("Microphone and notification permissions are required for sleep tracking");
|
|
347
|
-
} else {
|
|
348
|
-
throw new Error("Microphone permission is required for sleep tracking");
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// Always verify CURRENT exemption status
|
|
353
|
-
if (Platform.OS === "android") {
|
|
354
|
-
const batteryExempted = await AsleepModule.isBatteryOptimizationExempted();
|
|
355
|
-
if (!batteryExempted) {
|
|
356
|
-
addLog("[startTracking] ERROR: Battery optimization not disabled");
|
|
357
|
-
throw new Error(
|
|
358
|
-
"Battery optimization must be disabled for reliable sleep tracking. " +
|
|
359
|
-
"Call requestBatteryOptimizationExemption() to guide user to settings.",
|
|
360
|
-
);
|
|
361
|
-
}
|
|
362
|
-
addLog("[startTracking] Battery optimization exempted - OK");
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
set({
|
|
366
|
-
didClose: false,
|
|
367
|
-
isTracking: true,
|
|
368
|
-
isAnalyzing: false,
|
|
369
|
-
trackingStartTime: new Date(),
|
|
370
|
-
error: null,
|
|
371
|
-
});
|
|
372
|
-
await AsleepModule.startTracking(config);
|
|
373
|
-
|
|
374
|
-
if (isODAEnabled) {
|
|
375
|
-
addLog("[startTracking] ODA enabled - real-time analysis will start automatically");
|
|
376
|
-
} else {
|
|
377
|
-
addLog("[startTracking] ODA not enabled");
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
addLog("[startTracking] Success");
|
|
381
|
-
} catch (error: any) {
|
|
382
|
-
set({
|
|
383
|
-
error: error.message,
|
|
384
|
-
isTracking: false,
|
|
385
|
-
isAnalyzing: false,
|
|
386
|
-
trackingStartTime: null,
|
|
387
|
-
});
|
|
388
|
-
throw error;
|
|
390
|
+
if (Platform.OS === "android" && !(await AsleepModule.isBatteryOptimizationExempted())) {
|
|
391
|
+
storeAndThrow(
|
|
392
|
+
new AsleepError(
|
|
393
|
+
"BATTERY_NOT_EXEMPTED",
|
|
394
|
+
"Battery optimization must be disabled before startTracking(). Call requestBatteryOptimizationExemption().",
|
|
395
|
+
),
|
|
396
|
+
);
|
|
389
397
|
}
|
|
390
|
-
},
|
|
391
|
-
|
|
392
|
-
stopTracking: async () => {
|
|
393
|
-
try {
|
|
394
|
-
const { addLog } = get();
|
|
395
|
-
addLog("[stopTracking] Start");
|
|
396
398
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
399
|
+
useAsleepStore.setState({
|
|
400
|
+
didClose: false,
|
|
401
|
+
trackingStatus: "tracking",
|
|
402
|
+
isAnalyzing: false,
|
|
403
|
+
trackingStartTime: new Date(),
|
|
404
|
+
});
|
|
405
|
+
await AsleepModule.startTracking(config);
|
|
406
|
+
clearErrorIfUnchanged(errorBefore);
|
|
407
|
+
addLog("[startTracking] Success");
|
|
408
|
+
} catch (error) {
|
|
409
|
+
return guardedFailure(error, "START_TRACKING_FAILED", errorBefore, {
|
|
410
|
+
trackingStatus: "idle",
|
|
411
|
+
isAnalyzing: false,
|
|
412
|
+
trackingStartTime: null,
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
},
|
|
406
416
|
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
417
|
+
stopTracking: async () => {
|
|
418
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
419
|
+
try {
|
|
420
|
+
const result = await AsleepModule.stopTracking();
|
|
421
|
+
useAsleepStore.setState({
|
|
422
|
+
didClose: true,
|
|
423
|
+
...(typeof result === "string" && result ? { sessionId: result } : {}),
|
|
424
|
+
trackingStatus: "idle",
|
|
425
|
+
isAnalyzing: false,
|
|
426
|
+
trackingStartTime: null,
|
|
427
|
+
});
|
|
428
|
+
clearErrorIfUnchanged(errorBefore);
|
|
429
|
+
addLog(`[stopTracking] Success - result: ${result}`);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
return guardedFailure(error, "STOP_TRACKING_FAILED", errorBefore);
|
|
432
|
+
}
|
|
433
|
+
},
|
|
434
|
+
|
|
435
|
+
resumeTracking: async () => {
|
|
436
|
+
if (Platform.OS !== "ios") {
|
|
437
|
+
storeAndThrow(new AsleepError("UNSUPPORTED_PLATFORM", "resumeTracking is only supported on iOS."));
|
|
438
|
+
}
|
|
439
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
440
|
+
try {
|
|
441
|
+
await AsleepModule.resumeTracking();
|
|
442
|
+
clearErrorIfUnchanged(errorBefore);
|
|
443
|
+
} catch (error) {
|
|
444
|
+
return guardedFailure(error, "RESUME_TRACKING_FAILED", errorBefore);
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
|
|
448
|
+
getReport: async (sessionId) => {
|
|
449
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
450
|
+
try {
|
|
451
|
+
const payload = await AsleepModule.getReport(sessionId);
|
|
452
|
+
if (payload == null) {
|
|
453
|
+
throw new AsleepError("REPORT_NOT_FOUND", `No report available for session "${sessionId}".`);
|
|
411
454
|
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
peculiarities: convertedReport.peculiarities || [],
|
|
451
|
-
stat: convertedReport.stat,
|
|
452
|
-
};
|
|
453
|
-
return normalizedReport;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
return convertedReport as AsleepReport;
|
|
457
|
-
} catch (error: any) {
|
|
458
|
-
// Silent return on failure is a public-API quirk preserved for v1.x
|
|
459
|
-
// compat (v2.0 throws). Surface a dev-only warn so the consumer's
|
|
460
|
-
// Metro log still shows the failure when they're debugging without
|
|
461
|
-
// observing `useAsleep().error` directly.
|
|
462
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReport failed:", error);
|
|
463
|
-
set({ error: error.message });
|
|
464
|
-
return null;
|
|
455
|
+
const report = normalizeReport(payload, sessionId);
|
|
456
|
+
clearErrorIfUnchanged(errorBefore);
|
|
457
|
+
return report;
|
|
458
|
+
} catch (error) {
|
|
459
|
+
return guardedFailure(error, "GET_REPORT_FAILED", errorBefore);
|
|
460
|
+
}
|
|
461
|
+
},
|
|
462
|
+
|
|
463
|
+
getReportList: async (fromDate, toDate) => {
|
|
464
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
465
|
+
try {
|
|
466
|
+
const reportList = (await AsleepModule.getReportList(fromDate, toDate)) ?? [];
|
|
467
|
+
const result = reportList.map((session: any) => {
|
|
468
|
+
const converted = convertKeysToCamelCase(session);
|
|
469
|
+
return {
|
|
470
|
+
id: converted.sessionId || converted.id,
|
|
471
|
+
state: converted.state,
|
|
472
|
+
startTime: converted.sessionStartTime || converted.startTime,
|
|
473
|
+
endTime: converted.sessionEndTime || converted.endTime,
|
|
474
|
+
createdTimezone: converted.createdTimezone,
|
|
475
|
+
unexpectedEndTime: converted.unexpectedEndTime,
|
|
476
|
+
lastReceivedSeqNum: converted.lastReceivedSeqNum,
|
|
477
|
+
timeInBed: converted.timeInBed,
|
|
478
|
+
};
|
|
479
|
+
});
|
|
480
|
+
clearErrorIfUnchanged(errorBefore);
|
|
481
|
+
return result;
|
|
482
|
+
} catch (error) {
|
|
483
|
+
return guardedFailure(error, "GET_REPORT_LIST_FAILED", errorBefore);
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
|
|
487
|
+
getAverageReport: async (fromDate, toDate) => {
|
|
488
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
489
|
+
try {
|
|
490
|
+
const payload = await AsleepModule.getAverageReport(fromDate, toDate);
|
|
491
|
+
if (payload == null) {
|
|
492
|
+
throw new AsleepError("REPORT_NOT_FOUND", `No average report available for ${fromDate} to ${toDate}.`);
|
|
465
493
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
494
|
+
const result = convertKeysToCamelCase(payload);
|
|
495
|
+
clearErrorIfUnchanged(errorBefore);
|
|
496
|
+
return result;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
return guardedFailure(error, "GET_AVERAGE_REPORT_FAILED", errorBefore);
|
|
499
|
+
}
|
|
500
|
+
},
|
|
501
|
+
|
|
502
|
+
deleteSession: async (sessionId) => {
|
|
503
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
504
|
+
try {
|
|
505
|
+
await AsleepModule.deleteSession(sessionId);
|
|
506
|
+
clearErrorIfUnchanged(errorBefore);
|
|
507
|
+
} catch (error) {
|
|
508
|
+
return guardedFailure(error, "DELETE_SESSION_FAILED", errorBefore);
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
|
|
512
|
+
requestAnalysis: async () => {
|
|
513
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
514
|
+
useAsleepStore.setState({ isAnalyzing: true });
|
|
515
|
+
try {
|
|
516
|
+
const result = convertKeysToCamelCase(await AsleepModule.requestAnalysis());
|
|
517
|
+
clearErrorIfUnchanged(errorBefore);
|
|
518
|
+
return result;
|
|
519
|
+
} catch (error) {
|
|
520
|
+
return guardedFailure(error, "REQUEST_ANALYSIS_FAILED", errorBefore, { isAnalyzing: false });
|
|
521
|
+
}
|
|
522
|
+
},
|
|
523
|
+
|
|
524
|
+
hasRequiredPermissions: async () => {
|
|
525
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
526
|
+
try {
|
|
527
|
+
const result = await AsleepModule.hasRequiredPermissions();
|
|
528
|
+
clearErrorIfUnchanged(errorBefore);
|
|
529
|
+
return result;
|
|
530
|
+
} catch (error) {
|
|
531
|
+
return guardedFailure(error, "CHECK_PERMISSION_FAILED", errorBefore);
|
|
532
|
+
}
|
|
533
|
+
},
|
|
534
|
+
|
|
535
|
+
requestRequiredPermissions: async () => {
|
|
536
|
+
const errorBefore = useAsleepStore.getState().error;
|
|
537
|
+
try {
|
|
538
|
+
if (Platform.OS === "android") {
|
|
539
|
+
const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
|
|
540
|
+
if (Platform.Version >= 33) permissions.push(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
|
|
541
|
+
const results = await PermissionsAndroid.requestMultiple(permissions);
|
|
542
|
+
// POST_NOTIFICATIONS is requested for foreground-service notification
|
|
543
|
+
// visibility but is not needed for tracking to run, so the returned
|
|
544
|
+
// boolean mirrors hasRequiredPermissions(): microphone-side grants only.
|
|
545
|
+
const audioGranted =
|
|
546
|
+
results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
|
|
547
|
+
clearErrorIfUnchanged(errorBefore);
|
|
548
|
+
return audioGranted;
|
|
497
549
|
}
|
|
498
|
-
|
|
550
|
+
const result = await AsleepModule.requestRequiredPermissions();
|
|
551
|
+
clearErrorIfUnchanged(errorBefore);
|
|
552
|
+
return result;
|
|
553
|
+
} catch (error) {
|
|
554
|
+
return guardedFailure(error, "REQUEST_PERMISSION_FAILED", errorBefore);
|
|
555
|
+
}
|
|
556
|
+
},
|
|
557
|
+
|
|
558
|
+
setCustomNotification: async (_title, _text) => {
|
|
559
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
560
|
+
console.warn(
|
|
561
|
+
"[Asleep] setCustomNotification is deprecated and a no-op; pass notification options to startTracking() instead.",
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
|
|
566
|
+
enableLog: (print) => {
|
|
567
|
+
if (Platform.OS === "ios") AsleepModule.enableLog(print);
|
|
568
|
+
useAsleepStore.setState({ showDebugLog: print });
|
|
569
|
+
},
|
|
499
570
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
571
|
+
clearError: () => useAsleepStore.setState({ error: null }),
|
|
572
|
+
|
|
573
|
+
addEventListener: (eventType, listener) => {
|
|
574
|
+
const subscription = emitter.addListener(eventType, listener);
|
|
575
|
+
return () => subscription.remove();
|
|
576
|
+
},
|
|
577
|
+
};
|
|
505
578
|
|
|
506
|
-
|
|
579
|
+
let lastInternal: InternalAsleepState | null = null;
|
|
580
|
+
let lastPublic: AsleepPublicApi | null = null;
|
|
581
|
+
|
|
582
|
+
export const toPublicState = (internal: InternalAsleepState): AsleepPublicApi => {
|
|
583
|
+
if (internal === lastInternal && lastPublic) return lastPublic;
|
|
584
|
+
// Recovery-required is still a live native session on main; preserve that
|
|
585
|
+
// contract while representing the recovery fact with one enum value.
|
|
586
|
+
const isTracking = internal.trackingStatus !== "idle";
|
|
587
|
+
const next: AsleepPublicApi = {
|
|
588
|
+
status: internal.trackingStatus,
|
|
589
|
+
isTracking,
|
|
590
|
+
isTrackingPaused: internal.trackingStatus === "paused",
|
|
591
|
+
isRecoveryRequired: internal.trackingStatus === "recoveryRequired",
|
|
592
|
+
isSetupInProgress: internal.setupStatus === "inProgress",
|
|
593
|
+
isSetupComplete: internal.setupStatus === "complete",
|
|
594
|
+
sessionId: internal.sessionId,
|
|
595
|
+
userId: internal.userId,
|
|
596
|
+
error: internal.error,
|
|
597
|
+
analysisResult: internal.analysisResult,
|
|
598
|
+
isAnalyzing: internal.isAnalyzing,
|
|
599
|
+
didClose: internal.didClose,
|
|
600
|
+
isODAEnabled: internal.isODAEnabled,
|
|
601
|
+
log: internal.log,
|
|
602
|
+
...asleepActions,
|
|
603
|
+
};
|
|
604
|
+
lastInternal = internal;
|
|
605
|
+
if (
|
|
606
|
+
lastPublic &&
|
|
607
|
+
lastPublic.status === next.status &&
|
|
608
|
+
lastPublic.sessionId === next.sessionId &&
|
|
609
|
+
lastPublic.userId === next.userId &&
|
|
610
|
+
lastPublic.error === next.error &&
|
|
611
|
+
lastPublic.analysisResult === next.analysisResult &&
|
|
612
|
+
lastPublic.isAnalyzing === next.isAnalyzing &&
|
|
613
|
+
lastPublic.didClose === next.didClose &&
|
|
614
|
+
lastPublic.isODAEnabled === next.isODAEnabled &&
|
|
615
|
+
lastPublic.log === next.log &&
|
|
616
|
+
lastPublic.isSetupInProgress === next.isSetupInProgress &&
|
|
617
|
+
lastPublic.isSetupComplete === next.isSetupComplete
|
|
618
|
+
) {
|
|
619
|
+
return lastPublic;
|
|
620
|
+
}
|
|
621
|
+
lastPublic = next;
|
|
622
|
+
return lastPublic;
|
|
623
|
+
};
|
|
507
624
|
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
625
|
+
type EventName = keyof AsleepEventType;
|
|
626
|
+
|
|
627
|
+
const transitionForEvent = (
|
|
628
|
+
eventType: EventName,
|
|
629
|
+
payload: any,
|
|
630
|
+
state: InternalAsleepState,
|
|
631
|
+
): { partial: Partial<InternalAsleepState>; log: string; requestAnalysis?: boolean } => {
|
|
632
|
+
switch (eventType) {
|
|
633
|
+
case "onUserJoined":
|
|
634
|
+
return { partial: { userId: payload.userId }, log: `[onUserJoined] userId: ${payload.userId}` };
|
|
635
|
+
case "onUserJoinFailed":
|
|
636
|
+
return {
|
|
637
|
+
partial: { error: normalizeError(payload, "USER_JOIN_FAILED") },
|
|
638
|
+
log: `[onUserJoinFailed] error: ${payload?.message ?? payload?.detail ?? payload?.error ?? "Unknown error"}`,
|
|
639
|
+
};
|
|
640
|
+
case "onUserDeleted":
|
|
641
|
+
return { partial: { userId: null }, log: `[onUserDeleted] userId: ${payload.userId}` };
|
|
642
|
+
case "onTrackingCreated":
|
|
643
|
+
return {
|
|
644
|
+
partial: { trackingStatus: "tracking", ...(payload?.sessionId ? { sessionId: payload.sessionId } : {}) },
|
|
645
|
+
log: `[onTrackingCreated]${payload?.sessionId ? ` sessionId: ${payload.sessionId}` : ""}`,
|
|
646
|
+
};
|
|
647
|
+
case "onTrackingUploaded": {
|
|
648
|
+
const shouldAnalyze =
|
|
649
|
+
state.trackingStatus !== "idle" &&
|
|
650
|
+
(state.isODAEnabled || (payload.sequence >= 10 && payload.sequence % 10 === 1));
|
|
651
|
+
return {
|
|
652
|
+
partial: {
|
|
653
|
+
// iOS 3.2.0 emits didResume before its engine restart is proven.
|
|
654
|
+
// Only a completed upload clears recovery; see AGENTS.md
|
|
655
|
+
// "Native Behavior Compensations".
|
|
656
|
+
...(state.trackingStatus === "recoveryRequired" ? { trackingStatus: "tracking" as const } : {}),
|
|
657
|
+
...(shouldAnalyze ? { isAnalyzing: true } : {}),
|
|
658
|
+
},
|
|
659
|
+
log: `[onTrackingUploaded] sequence: ${payload.sequence}`,
|
|
660
|
+
requestAnalysis: shouldAnalyze,
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
case "onTrackingClosed":
|
|
664
|
+
return {
|
|
665
|
+
partial: {
|
|
666
|
+
sessionId: payload.sessionId,
|
|
667
|
+
trackingStatus: "idle",
|
|
668
|
+
isAnalyzing: false,
|
|
669
|
+
didClose: true,
|
|
670
|
+
trackingStartTime: null,
|
|
671
|
+
},
|
|
672
|
+
log: `[onTrackingClosed] sessionId: ${payload.sessionId}`,
|
|
673
|
+
};
|
|
674
|
+
case "onTrackingFailed": {
|
|
675
|
+
const recordingDead = !!payload && RECORDING_DEAD_ERROR_CODES.has(payload.code);
|
|
676
|
+
const recoveryRequired = !!payload && RECOVERY_REQUIRED_ERROR_CODES.has(payload.code);
|
|
677
|
+
const terminal =
|
|
678
|
+
!!payload &&
|
|
679
|
+
!recordingDead &&
|
|
680
|
+
!recoveryRequired &&
|
|
681
|
+
(TERMINAL_TRACKING_ERROR_CODES.has(payload.code) || TERMINAL_TRACKING_SDK_CODES.has(payload.sdkCode));
|
|
682
|
+
const transient = !!payload && TRANSIENT_TRACKING_SDK_CODES.has(payload.sdkCode);
|
|
683
|
+
const category: AsleepErrorCategory = recordingDead
|
|
684
|
+
? "recordingDead"
|
|
685
|
+
: recoveryRequired
|
|
686
|
+
? "recoveryRequired"
|
|
687
|
+
: terminal
|
|
688
|
+
? "terminal"
|
|
689
|
+
: transient
|
|
690
|
+
? "transient"
|
|
691
|
+
: "unknown";
|
|
692
|
+
const error = normalizeError(payload, "TRACKING_FAILED", {
|
|
693
|
+
category,
|
|
694
|
+
sdkCode: typeof payload?.sdkCode === "number" ? payload.sdkCode : undefined,
|
|
695
|
+
caseName: typeof payload?.caseName === "string" ? payload.caseName : undefined,
|
|
696
|
+
});
|
|
697
|
+
|
|
698
|
+
if (terminal) {
|
|
699
|
+
return {
|
|
700
|
+
partial: {
|
|
701
|
+
// iOS 3.2.1 closeSessionSilently does not emit didClose, so this
|
|
702
|
+
// branch must clear the projected session state itself.
|
|
703
|
+
error,
|
|
704
|
+
trackingStatus: "idle",
|
|
705
|
+
isAnalyzing: false,
|
|
706
|
+
didClose: true,
|
|
707
|
+
trackingStartTime: null,
|
|
708
|
+
},
|
|
709
|
+
log: `[onTrackingError] error: ${error.message}`,
|
|
710
|
+
};
|
|
513
711
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
return convertedReport;
|
|
528
|
-
} catch (error: any) {
|
|
529
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getAverageReport failed:", error);
|
|
530
|
-
set({ error: error.message });
|
|
531
|
-
return null;
|
|
712
|
+
if (recordingDead) {
|
|
713
|
+
return {
|
|
714
|
+
partial: {
|
|
715
|
+
// iOS 3.2.0 audioInitializationFailed stops its recorder but
|
|
716
|
+
// intentionally keeps the native session open (didClose=false).
|
|
717
|
+
error,
|
|
718
|
+
trackingStatus: "idle",
|
|
719
|
+
isAnalyzing: false,
|
|
720
|
+
didClose: false,
|
|
721
|
+
trackingStartTime: null,
|
|
722
|
+
},
|
|
723
|
+
log: `[onTrackingError] error: ${error.message}`,
|
|
724
|
+
};
|
|
532
725
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
console.warn(
|
|
541
|
-
"[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.",
|
|
542
|
-
);
|
|
726
|
+
if (recoveryRequired) {
|
|
727
|
+
return {
|
|
728
|
+
// iOS 3.2.0 cannotActivateInBackground keeps the session alive and
|
|
729
|
+
// requires an explicit foreground resume.
|
|
730
|
+
partial: { error, trackingStatus: "recoveryRequired" },
|
|
731
|
+
log: `[onTrackingError] error: ${error.message}`,
|
|
732
|
+
};
|
|
543
733
|
}
|
|
544
|
-
return
|
|
545
|
-
}
|
|
734
|
+
return { partial: { error }, log: `[onTrackingError] error: ${error.message}` };
|
|
735
|
+
}
|
|
736
|
+
case "onTrackingInterrupted":
|
|
737
|
+
return { partial: { trackingStatus: "paused" }, log: "[onTrackingInterrupted]" };
|
|
738
|
+
case "onTrackingResumed":
|
|
739
|
+
return {
|
|
740
|
+
partial: {
|
|
741
|
+
error: null,
|
|
742
|
+
// iOS 3.2.1 can emit didResume twice. Always clear the error, but
|
|
743
|
+
// mutate the paused state only for the first event.
|
|
744
|
+
...(state.trackingStatus === "paused" ? { trackingStatus: "tracking" as const } : {}),
|
|
745
|
+
},
|
|
746
|
+
log:
|
|
747
|
+
state.trackingStatus === "paused"
|
|
748
|
+
? "[onTrackingResumed]"
|
|
749
|
+
: "[onTrackingResumed] (no prior pause; error cleared)",
|
|
750
|
+
};
|
|
751
|
+
case "onMicPermissionDenied":
|
|
752
|
+
return { partial: {}, log: "[onMicPermissionDenied]" };
|
|
753
|
+
case "onDebugLog":
|
|
754
|
+
return { partial: {}, log: `[onDebugLog] message: ${payload.message}` };
|
|
755
|
+
case "onSetupDidComplete":
|
|
756
|
+
return { partial: { setupStatus: "complete" }, log: "[onSetupDidComplete]" };
|
|
757
|
+
case "onSetupDidFail":
|
|
758
|
+
return {
|
|
759
|
+
partial: { error: normalizeError(payload, "SETUP_FAILED"), setupStatus: "idle" },
|
|
760
|
+
log: `[onSetupDidFail] error: ${payload?.message ?? payload?.error ?? "Unknown error"}`,
|
|
761
|
+
};
|
|
762
|
+
case "onSetupInProgress":
|
|
763
|
+
return { partial: { setupStatus: "inProgress" }, log: `[onSetupInProgress] progress: ${payload.progress}%` };
|
|
764
|
+
case "onAnalysisResult": {
|
|
765
|
+
// Android SDK 3.2.x emits snake_case while iOS emits camelCase.
|
|
766
|
+
const analysisResult = convertKeysToCamelCase(payload);
|
|
767
|
+
return {
|
|
768
|
+
partial: { analysisResult, isAnalyzing: false },
|
|
769
|
+
log: `[onAnalysisResult] ${JSON.stringify(analysisResult)}`,
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
};
|
|
546
774
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
// Request all permissions together for better UX (single dialog)
|
|
559
|
-
const results = await PermissionsAndroid.requestMultiple(permissions);
|
|
560
|
-
|
|
561
|
-
// Check if all required permissions are granted
|
|
562
|
-
const audioGranted =
|
|
563
|
-
results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
|
|
564
|
-
|
|
565
|
-
const notificationGranted =
|
|
566
|
-
Platform.Version >= 33
|
|
567
|
-
? results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] === PermissionsAndroid.RESULTS.GRANTED
|
|
568
|
-
: true;
|
|
569
|
-
|
|
570
|
-
// Both must be granted for tracking to work properly
|
|
571
|
-
return audioGranted && notificationGranted;
|
|
572
|
-
} catch (err) {
|
|
573
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] Permission request error:", err);
|
|
574
|
-
return false;
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
// iOS uses native implementation
|
|
578
|
-
return AsleepModule.requestRequiredPermissions();
|
|
579
|
-
},
|
|
775
|
+
const applyEvent = (eventType: EventName, payload: unknown) => {
|
|
776
|
+
const state = useAsleepStore.getState();
|
|
777
|
+
const transition = transitionForEvent(eventType, payload, state);
|
|
778
|
+
useAsleepStore.setState({ ...transition.partial, ...logPartial(transition.log, state) });
|
|
779
|
+
if (transition.requestAnalysis) {
|
|
780
|
+
void asleepActions.requestAnalysis().catch((error) => {
|
|
781
|
+
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
};
|
|
580
785
|
|
|
581
|
-
setCustomNotification: async (title: string, text: string) => {
|
|
582
|
-
if (Platform.OS === "android") {
|
|
583
|
-
await AsleepModule.setCustomNotification(title, text);
|
|
584
|
-
} else {
|
|
585
|
-
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
586
|
-
console.warn("[Asleep] setCustomNotification is not supported on this platform");
|
|
587
|
-
}
|
|
588
|
-
},
|
|
589
|
-
|
|
590
|
-
enableLog: (print: boolean) => {
|
|
591
|
-
set({ showDebugLog: print });
|
|
592
|
-
},
|
|
593
|
-
|
|
594
|
-
requestAnalysis: async () => {
|
|
595
|
-
try {
|
|
596
|
-
const { addLog } = get();
|
|
597
|
-
addLog("[requestAnalysis] Start");
|
|
598
|
-
|
|
599
|
-
set({ isAnalyzing: true, error: null });
|
|
600
|
-
|
|
601
|
-
const result = await AsleepModule.requestAnalysis();
|
|
602
|
-
const convertedResult = convertKeysToCamelCase(result);
|
|
603
|
-
|
|
604
|
-
// Platform differences:
|
|
605
|
-
// Android: Returns the actual analysis result immediately and also sends onAnalysisResult event
|
|
606
|
-
// iOS: Returns acknowledgment data only, actual result comes through onAnalysisResult event
|
|
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
|
|
612
|
-
|
|
613
|
-
addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
|
|
614
|
-
|
|
615
|
-
return convertedResult;
|
|
616
|
-
} catch (error: any) {
|
|
617
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] requestAnalysis failed:", error);
|
|
618
|
-
set({ error: error.message, isAnalyzing: false });
|
|
619
|
-
return null;
|
|
620
|
-
}
|
|
621
|
-
},
|
|
622
|
-
|
|
623
|
-
addEventListener: <K extends keyof AsleepEventType>(eventType: K, listener: (data: AsleepEventType[K]) => void) => {
|
|
624
|
-
const subscription = emitter.addListener(eventType, listener);
|
|
625
|
-
return () => subscription.remove();
|
|
626
|
-
},
|
|
627
|
-
|
|
628
|
-
getTrackingDurationMinutes: () => {
|
|
629
|
-
const { trackingStartTime } = get();
|
|
630
|
-
if (!trackingStartTime) return 0;
|
|
631
|
-
return Math.floor((Date.now() - trackingStartTime.getTime()) / (1000 * 60));
|
|
632
|
-
},
|
|
633
|
-
|
|
634
|
-
// internal actions
|
|
635
|
-
setError: (error) => set({ error }),
|
|
636
|
-
clearError: () => set({ error: null }),
|
|
637
|
-
setUserId: (userId) => set({ userId }),
|
|
638
|
-
setSessionId: (sessionId) => set({ sessionId }),
|
|
639
|
-
setIsTracking: (isTracking) => set({ isTracking }),
|
|
640
|
-
setIsTrackingPaused: (isTrackingPaused) => set({ isTrackingPaused }),
|
|
641
|
-
setDidClose: (didClose) => set({ didClose }),
|
|
642
|
-
setAnalysisResult: (result) => set({ analysisResult: result }),
|
|
643
|
-
setIsAnalyzing: (isAnalyzing) => set({ isAnalyzing }),
|
|
644
|
-
setTrackingStartTime: (time) => set({ trackingStartTime: time }),
|
|
645
|
-
setIsInitialized: (initialized) => set({ isInitialized: initialized }),
|
|
646
|
-
setIsSetupInProgress: (inProgress) => set({ isSetupInProgress: inProgress }),
|
|
647
|
-
setIsSetupComplete: (complete) => set({ isSetupComplete: complete }),
|
|
648
|
-
setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
|
|
649
|
-
setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
|
|
650
|
-
|
|
651
|
-
addLog: (log: string) => {
|
|
652
|
-
// Zero-cost when the consumer has not opted into debug logging. Without
|
|
653
|
-
// this guard, every native event handler would cause a spurious
|
|
654
|
-
// subscriber notification on top of any actual data update.
|
|
655
|
-
const { showDebugLog } = get();
|
|
656
|
-
if (!showDebugLog) return;
|
|
657
|
-
const now = new Date();
|
|
658
|
-
const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
|
|
659
|
-
.getMinutes()
|
|
660
|
-
.toString()
|
|
661
|
-
.padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
|
|
662
|
-
const formattedLog = `[${dateString}]${log}`;
|
|
663
|
-
console.log(`[Asleep]${formattedLog}`);
|
|
664
|
-
set({ log: formattedLog });
|
|
665
|
-
},
|
|
666
|
-
})),
|
|
667
|
-
);
|
|
668
|
-
|
|
669
|
-
// Ref-counted registration. Each caller (useAsleep effect, background context,
|
|
670
|
-
// etc.) increments on entry and decrements via the returned cleanup. Native
|
|
671
|
-
// listeners only attach on 0→1 and detach on the final 1→0, so concurrent
|
|
672
|
-
// consumers cannot tear each other's subscriptions down.
|
|
673
786
|
let refCount = 0;
|
|
674
787
|
let teardown: (() => void) | null = null;
|
|
675
788
|
|
|
676
789
|
export const initializeAsleepListeners = (): (() => void) => {
|
|
677
|
-
// Cold start when no teardown is installed. `teardown` is the single source
|
|
678
|
-
// of truth for "listeners are currently attached"; refCount is just an
|
|
679
|
-
// increment-only counter for cleanup balancing. Always incrementing
|
|
680
|
-
// (instead of assigning =1 on cold start) keeps the count correct even if
|
|
681
|
-
// a future change introduces an async seam between this check and the
|
|
682
|
-
// listener registration below.
|
|
683
790
|
if (teardown) {
|
|
684
791
|
refCount++;
|
|
685
792
|
return makeCleanup();
|
|
686
793
|
}
|
|
687
794
|
|
|
688
|
-
const
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
setUserId(null);
|
|
709
|
-
addLog(`[onUserDeleted] userId: ${data.userId}`);
|
|
710
|
-
},
|
|
711
|
-
// Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
|
|
712
|
-
onTrackingCreated: (data: any) => {
|
|
713
|
-
useAsleepStore.setState({
|
|
714
|
-
isTracking: true,
|
|
715
|
-
...(data?.sessionId ? { sessionId: data.sessionId } : {}),
|
|
716
|
-
});
|
|
717
|
-
addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
|
|
718
|
-
},
|
|
719
|
-
// Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
|
|
720
|
-
// Triggers automatic analysis requests in both ODA and non-ODA modes
|
|
721
|
-
onTrackingUploaded: (data: any) => {
|
|
722
|
-
addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
|
|
723
|
-
|
|
724
|
-
// requestAnalysis() flips isAnalyzing internally; no separate setter
|
|
725
|
-
// needed before invoking it (avoids a duplicate subscriber notification).
|
|
726
|
-
const state = useAsleepStore.getState();
|
|
727
|
-
const triggerAnalysis = () =>
|
|
728
|
-
state.requestAnalysis().catch((error) => {
|
|
729
|
-
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
730
|
-
state.setIsAnalyzing(false);
|
|
731
|
-
});
|
|
732
|
-
|
|
733
|
-
if (state.isODAEnabled && state.isTracking) {
|
|
734
|
-
triggerAnalysis();
|
|
735
|
-
} else if (!state.isODAEnabled && state.isTracking) {
|
|
736
|
-
if (data.sequence >= 10 && data.sequence % 10 === 1) {
|
|
737
|
-
triggerAnalysis();
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
},
|
|
741
|
-
// Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
|
|
742
|
-
onTrackingClosed: (data: { sessionId: string }) => {
|
|
743
|
-
useAsleepStore.setState({
|
|
744
|
-
sessionId: data.sessionId,
|
|
745
|
-
isTracking: false,
|
|
746
|
-
isAnalyzing: false,
|
|
747
|
-
didClose: true,
|
|
748
|
-
trackingStartTime: null,
|
|
749
|
-
});
|
|
750
|
-
addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
|
|
751
|
-
},
|
|
752
|
-
// Connected: iOS didFail, Android onFail (AsleepTrackingListener)
|
|
753
|
-
// Terminal codes (UPLOAD_TRACKING_TERMINATED / INTERRUPTION_RECOVERY_FAILED)
|
|
754
|
-
// mean the native SDK already tore the session down — clear tracking state
|
|
755
|
-
// in the same setState as the error write so subscribers see one event.
|
|
756
|
-
onTrackingFailed: (error: any) => {
|
|
757
|
-
const errorString = JSON.stringify(error);
|
|
758
|
-
const terminal = !!(error && TERMINAL_TRACKING_ERROR_CODES.has(error.code));
|
|
759
|
-
useAsleepStore.setState(
|
|
760
|
-
terminal
|
|
761
|
-
? { error: errorString, isTracking: false, isAnalyzing: false, didClose: true, trackingStartTime: null }
|
|
762
|
-
: { error: errorString },
|
|
763
|
-
);
|
|
764
|
-
addLog(`[onTrackingError] error: ${errorString}`);
|
|
765
|
-
},
|
|
766
|
-
// Connected: iOS didInterrupt, Android NOT IMPLEMENTED
|
|
767
|
-
onTrackingInterrupted: () => {
|
|
768
|
-
setIsTrackingPaused(true);
|
|
769
|
-
addLog(`[onTrackingInterrupted]`);
|
|
770
|
-
},
|
|
771
|
-
// Connected: iOS didResume, Android NOT IMPLEMENTED
|
|
772
|
-
// Always clear the error: some iOS recovery paths (e.g. cannotActivateInBackground
|
|
773
|
-
// retry) reach this handler without a preceding didInterrupt, and the stale error
|
|
774
|
-
// should still be cleared. Only the paused-state mutation is gated, to dedup the
|
|
775
|
-
// iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
|
|
776
|
-
onTrackingResumed: () => {
|
|
777
|
-
const wasPaused = useAsleepStore.getState().isTrackingPaused;
|
|
778
|
-
useAsleepStore.setState(wasPaused ? { error: null, isTrackingPaused: false } : { error: null });
|
|
779
|
-
addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
|
|
780
|
-
},
|
|
781
|
-
// Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
|
|
782
|
-
onMicPermissionDenied: () => {
|
|
783
|
-
addLog(`[onMicPermissionDenied]`);
|
|
784
|
-
},
|
|
785
|
-
// Connected: iOS didPrint (AsleepDebugLoggerDelegate), Android sendEvent called directly
|
|
786
|
-
onDebugLog: (data: any) => {
|
|
787
|
-
addLog(`[onDebugLog] message: ${data.message}`);
|
|
788
|
-
},
|
|
789
|
-
// Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
|
|
790
|
-
onSetupDidComplete: () => {
|
|
791
|
-
useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
|
|
792
|
-
addLog(`[onSetupDidComplete]`);
|
|
793
|
-
},
|
|
794
|
-
// Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
|
|
795
|
-
onSetupDidFail: (data: any) => {
|
|
796
|
-
const errorString = JSON.stringify(data);
|
|
797
|
-
useAsleepStore.setState({ error: errorString, isSetupInProgress: false, isSetupComplete: false });
|
|
798
|
-
addLog(`[onSetupDidFail] error: ${errorString}`);
|
|
799
|
-
},
|
|
800
|
-
// Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
|
|
801
|
-
onSetupInProgress: (data: any) => {
|
|
802
|
-
setIsSetupInProgress(true);
|
|
803
|
-
addLog(`[onSetupInProgress] progress: ${data.progress}%`);
|
|
804
|
-
},
|
|
805
|
-
// Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
|
|
806
|
-
onAnalysisResult: (data: any) => {
|
|
807
|
-
useAsleepStore.setState({ analysisResult: data, isAnalyzing: false });
|
|
808
|
-
addLog(`[onAnalysisResult] ${JSON.stringify(data)}`);
|
|
809
|
-
},
|
|
810
|
-
};
|
|
811
|
-
|
|
812
|
-
// register all event listeners
|
|
813
|
-
const subscriptions: (() => void)[] = [];
|
|
814
|
-
Object.entries(handlers).forEach(([eventType, handler]) => {
|
|
815
|
-
const subscription = emitter.addListener(eventType, handler);
|
|
816
|
-
subscriptions.push(() => subscription.remove());
|
|
817
|
-
});
|
|
795
|
+
const eventTypes: EventName[] = [
|
|
796
|
+
"onUserJoined",
|
|
797
|
+
"onUserJoinFailed",
|
|
798
|
+
"onUserDeleted",
|
|
799
|
+
"onTrackingCreated",
|
|
800
|
+
"onTrackingUploaded",
|
|
801
|
+
"onTrackingClosed",
|
|
802
|
+
"onTrackingFailed",
|
|
803
|
+
"onTrackingInterrupted",
|
|
804
|
+
"onTrackingResumed",
|
|
805
|
+
"onMicPermissionDenied",
|
|
806
|
+
"onDebugLog",
|
|
807
|
+
"onSetupDidComplete",
|
|
808
|
+
"onSetupDidFail",
|
|
809
|
+
"onSetupInProgress",
|
|
810
|
+
"onAnalysisResult",
|
|
811
|
+
];
|
|
812
|
+
const subscriptions = eventTypes.map((eventType) =>
|
|
813
|
+
emitter.addListener(eventType, (payload: unknown) => applyEvent(eventType, payload)),
|
|
814
|
+
);
|
|
818
815
|
|
|
819
816
|
refCount++;
|
|
820
817
|
teardown = () => {
|
|
821
|
-
subscriptions.forEach((
|
|
818
|
+
subscriptions.forEach((subscription) => subscription.remove());
|
|
822
819
|
teardown = null;
|
|
823
820
|
};
|
|
824
|
-
|
|
825
821
|
return makeCleanup();
|
|
826
822
|
};
|
|
827
823
|
|
|
828
824
|
const makeCleanup = (): (() => void) => {
|
|
829
|
-
// Idempotent per-caller cleanup. The `called` flag is closure-private so
|
|
830
|
-
// calling the returned function twice (e.g. Strict Mode double-effect)
|
|
831
|
-
// decrements the shared ref count only once.
|
|
832
825
|
let called = false;
|
|
833
826
|
return () => {
|
|
834
827
|
if (called) return;
|