react-native-asleep 1.1.0 → 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 +142 -25
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +20 -10
- package/build/Asleep.types.d.ts +20 -16
- 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 +44 -43
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +507 -670
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +11 -113
- package/build/index.d.ts.map +1 -1
- package/build/index.js +18 -184
- 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 +4 -0
- package/package.json +3 -5
- package/src/Asleep.types.ts +36 -16
- package/src/AsleepStore.ts +723 -892
- package/src/index.ts +36 -292
- package/src/store/createStore.ts +84 -0
package/src/AsleepStore.ts
CHANGED
|
@@ -1,112 +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
|
-
AsleepSetupConfig,
|
|
8
8
|
AsleepErrorCategory,
|
|
9
|
-
AsleepErrorInfo,
|
|
10
9
|
AsleepEventType,
|
|
11
10
|
AsleepReport,
|
|
12
11
|
AsleepSession,
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
AsleepAnalysisAck,
|
|
12
|
+
AsleepSetupConfig,
|
|
13
|
+
SetupStatus,
|
|
16
14
|
TrackingConfig,
|
|
15
|
+
TrackingStatus,
|
|
17
16
|
} from "./Asleep.types";
|
|
17
|
+
import { AsleepError } from "./Asleep.types";
|
|
18
18
|
import AsleepModule from "./AsleepModule";
|
|
19
|
+
import { createStore } from "./store/createStore";
|
|
19
20
|
|
|
20
21
|
const emitter = new EventEmitter(AsleepModule);
|
|
21
22
|
|
|
22
|
-
//
|
|
23
|
-
|
|
24
|
-
// function. Metro's inline plugin substitutes the bare `__DEV__` identifier
|
|
25
|
-
// for the literal at build time, then constant-folds `typeof <literal>` and
|
|
26
|
-
// the `&&` so the entire branch is dead-code-eliminated in production
|
|
27
|
-
// bundles. Wrapping the check in a function (e.g. `if (isDev())`) defeats
|
|
28
|
-
// that DCE because Metro does not constant-fold through call expressions.
|
|
29
|
-
// The `typeof` guard also keeps the module importable from plain Node,
|
|
30
|
-
// custom bundlers, or unconfigured jest setups without a ReferenceError.
|
|
31
|
-
|
|
32
|
-
// Error codes emitted on onTrackingFailed for which the native SDK has already
|
|
33
|
-
// terminated the session and will not deliver onTrackingClosed. JS must clear
|
|
34
|
-
// tracking state itself when one of these arrives. See AGENTS.md "Native Behavior
|
|
35
|
-
// Compensations" for the upstream behavior these guard against.
|
|
36
|
-
const TERMINAL_TRACKING_ERROR_CODES = new Set<string>([
|
|
37
|
-
"UPLOAD_TRACKING_TERMINATED", // iOS 403/429 closeSessionSilently; Android errorCode 23499
|
|
38
|
-
"INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
|
|
39
|
-
]);
|
|
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"]);
|
|
40
25
|
|
|
41
|
-
// iOS
|
|
42
|
-
// audio engine initialization fails. The session must be stopped and restarted.
|
|
26
|
+
// iOS 3.2.0 stops recording but leaves the native session open.
|
|
43
27
|
const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED"]);
|
|
44
28
|
|
|
45
|
-
// iOS
|
|
46
|
-
// background. The consumer must call resumeTracking() after returning foreground.
|
|
29
|
+
// iOS 3.2.0 needs an explicit foreground resume after this failure.
|
|
47
30
|
const RECOVERY_REQUIRED_ERROR_CODES = new Set<string>(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
|
|
48
31
|
|
|
49
|
-
//
|
|
50
|
-
//
|
|
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.
|
|
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.
|
|
56
34
|
const TERMINAL_TRACKING_SDK_CODES = new Set<number>([
|
|
57
|
-
11003,
|
|
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_*
|
|
35
|
+
11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500,
|
|
70
36
|
]);
|
|
71
37
|
|
|
72
|
-
//
|
|
73
|
-
|
|
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
|
-
]);
|
|
38
|
+
// The native session survives these exhausted upload attempts.
|
|
39
|
+
const TRANSIENT_TRACKING_SDK_CODES = new Set<number>([23000, 23500]);
|
|
80
40
|
|
|
81
|
-
export interface
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
isTrackingPaused: boolean;
|
|
85
|
-
isRecoveryRequired: boolean;
|
|
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;
|
|
91
|
-
userId: string | null;
|
|
41
|
+
export interface InternalAsleepState {
|
|
42
|
+
setupStatus: SetupStatus;
|
|
43
|
+
trackingStatus: TrackingStatus;
|
|
92
44
|
sessionId: string | null;
|
|
93
|
-
|
|
94
|
-
|
|
45
|
+
userId: string | null;
|
|
46
|
+
error: AsleepError | null;
|
|
95
47
|
analysisResult: AsleepAnalysisResult | null;
|
|
96
|
-
isODAEnabled: boolean;
|
|
97
48
|
isAnalyzing: boolean;
|
|
49
|
+
didClose: boolean;
|
|
50
|
+
isODAEnabled: boolean;
|
|
98
51
|
trackingStartTime: Date | null;
|
|
99
52
|
isInitialized: boolean;
|
|
100
|
-
isSetupInProgress: boolean;
|
|
101
|
-
isSetupComplete: boolean;
|
|
102
|
-
|
|
103
|
-
// Service status tracking
|
|
104
53
|
hasCheckedStatus: boolean;
|
|
105
|
-
|
|
106
|
-
// Battery optimization tracking
|
|
107
54
|
hasCheckedBatteryOptimization: boolean;
|
|
55
|
+
showDebugLog: boolean;
|
|
56
|
+
log: string;
|
|
57
|
+
}
|
|
108
58
|
|
|
109
|
-
|
|
59
|
+
export interface AsleepActions {
|
|
110
60
|
setup: (config: AsleepSetupConfig) => Promise<void>;
|
|
111
61
|
initAsleepConfig: (config: AsleepConfig) => Promise<void>;
|
|
112
62
|
checkAndRestoreTracking: () => Promise<{ hasActiveSession: boolean }>;
|
|
@@ -115,205 +65,268 @@ export interface AsleepState {
|
|
|
115
65
|
startTracking: (config?: TrackingConfig) => Promise<void>;
|
|
116
66
|
stopTracking: () => Promise<void>;
|
|
117
67
|
resumeTracking: () => Promise<void>;
|
|
118
|
-
getReport: (sessionId: string) => Promise<AsleepReport
|
|
68
|
+
getReport: (sessionId: string) => Promise<AsleepReport>;
|
|
119
69
|
getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
|
|
120
|
-
getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport
|
|
70
|
+
getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport>;
|
|
121
71
|
deleteSession: (sessionId: string) => Promise<void>;
|
|
122
|
-
|
|
72
|
+
requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck>;
|
|
73
|
+
hasRequiredPermissions: () => Promise<boolean>;
|
|
123
74
|
requestRequiredPermissions: () => Promise<boolean>;
|
|
124
75
|
setCustomNotification: (title: string, text: string) => Promise<void>;
|
|
125
76
|
enableLog: (print: boolean) => void;
|
|
126
77
|
clearError: () => void;
|
|
127
|
-
requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck | null>;
|
|
128
78
|
addEventListener: <K extends keyof AsleepEventType>(
|
|
129
79
|
eventType: K,
|
|
130
80
|
listener: (data: AsleepEventType[K]) => void,
|
|
131
81
|
) => () => void;
|
|
132
|
-
getTrackingDurationMinutes: () => number;
|
|
133
|
-
|
|
134
|
-
// internal actions
|
|
135
|
-
setError: (error: string | null) => void;
|
|
136
|
-
setUserId: (userId: string | null) => void;
|
|
137
|
-
setSessionId: (sessionId: string | null) => void;
|
|
138
|
-
setIsTracking: (isTracking: boolean) => void;
|
|
139
|
-
setIsTrackingPaused: (isTrackingPaused: boolean) => void;
|
|
140
|
-
setDidClose: (didClose: boolean) => void;
|
|
141
|
-
setAnalysisResult: (result: AsleepAnalysisResult | null) => void;
|
|
142
|
-
setIsAnalyzing: (isAnalyzing: boolean) => void;
|
|
143
|
-
setTrackingStartTime: (time: Date | null) => void;
|
|
144
|
-
setIsInitialized: (initialized: boolean) => void;
|
|
145
|
-
setIsSetupInProgress: (inProgress: boolean) => void;
|
|
146
|
-
setIsSetupComplete: (complete: boolean) => void;
|
|
147
|
-
setHasCheckedStatus: (checked: boolean) => void;
|
|
148
|
-
setHasCheckedBatteryOptimization: (checked: boolean) => void;
|
|
149
|
-
addLog: (log: string) => void;
|
|
150
82
|
}
|
|
151
83
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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;
|
|
160
131
|
}, {} as any);
|
|
161
132
|
}
|
|
162
|
-
return
|
|
133
|
+
return value;
|
|
163
134
|
};
|
|
164
135
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
isTrackingPaused: false,
|
|
171
|
-
isRecoveryRequired: false,
|
|
172
|
-
error: null,
|
|
173
|
-
errorInfo: null,
|
|
174
|
-
userId: null,
|
|
175
|
-
sessionId: null,
|
|
176
|
-
showDebugLog: false,
|
|
177
|
-
log: "",
|
|
178
|
-
analysisResult: null,
|
|
179
|
-
isODAEnabled: false,
|
|
180
|
-
isAnalyzing: false,
|
|
181
|
-
trackingStartTime: null,
|
|
182
|
-
isInitialized: false,
|
|
183
|
-
isSetupInProgress: false,
|
|
184
|
-
isSetupComplete: false,
|
|
185
|
-
|
|
186
|
-
// Service status state
|
|
187
|
-
hasCheckedStatus: false,
|
|
188
|
-
|
|
189
|
-
// Battery optimization state
|
|
190
|
-
hasCheckedBatteryOptimization: false,
|
|
191
|
-
|
|
192
|
-
// actions
|
|
193
|
-
setup: async (config: AsleepSetupConfig) => {
|
|
194
|
-
try {
|
|
195
|
-
const { addLog, isSetupInProgress, isTracking } = get();
|
|
196
|
-
|
|
197
|
-
// Prevent duplicate execution if setup is already in progress
|
|
198
|
-
if (isSetupInProgress) {
|
|
199
|
-
addLog("[setup] Setup is already in progress. Please try again later.");
|
|
200
|
-
throw new Error("Setup is already in progress.");
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// Block setup execution if tracking is in progress
|
|
204
|
-
if (isTracking) {
|
|
205
|
-
addLog("[setup] Cannot execute setup while tracking is in progress.");
|
|
206
|
-
throw new Error("Cannot execute setup while tracking is in progress.");
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
addLog("[setup] Start");
|
|
210
|
-
set({ isSetupInProgress: true, error: null, errorInfo: null });
|
|
211
|
-
|
|
212
|
-
await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
|
|
213
|
-
|
|
214
|
-
// Store ODA enabled state. Clearing `error` on success keeps the
|
|
215
|
-
// reactive `useAsleep().error` field aligned with the actual SDK status
|
|
216
|
-
// (no stale failure messages after a successful retry).
|
|
217
|
-
set({
|
|
218
|
-
isODAEnabled: config.enableODA || false,
|
|
219
|
-
isInitialized: true,
|
|
220
|
-
isSetupInProgress: false,
|
|
221
|
-
isSetupComplete: true,
|
|
222
|
-
error: null,
|
|
223
|
-
errorInfo: null,
|
|
224
|
-
});
|
|
225
|
-
addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
|
|
226
|
-
} catch (error: any) {
|
|
227
|
-
set({ error: error.message, errorInfo: null, isSetupInProgress: false });
|
|
228
|
-
throw error;
|
|
229
|
-
}
|
|
230
|
-
},
|
|
231
|
-
|
|
232
|
-
initAsleepConfig: async (config: AsleepConfig) => {
|
|
233
|
-
try {
|
|
234
|
-
const { addLog } = get();
|
|
235
|
-
addLog("[initAsleepConfig] Start");
|
|
236
|
-
|
|
237
|
-
const result = await AsleepModule.initAsleepConfig(
|
|
238
|
-
config.apiKey,
|
|
239
|
-
config.userId,
|
|
240
|
-
config.baseUrl,
|
|
241
|
-
config.callbackUrl,
|
|
242
|
-
);
|
|
136
|
+
type ErrorOptions = {
|
|
137
|
+
category?: AsleepErrorCategory;
|
|
138
|
+
sdkCode?: number;
|
|
139
|
+
caseName?: string;
|
|
140
|
+
};
|
|
243
141
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
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
|
+
};
|
|
307
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
|
+
};
|
|
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 {
|
|
308
324
|
if (Platform.OS === "ios") {
|
|
309
|
-
|
|
325
|
+
clearErrorIfUnchanged(errorBefore);
|
|
310
326
|
return { exempted: true, platform: "ios" };
|
|
311
327
|
}
|
|
312
|
-
|
|
313
|
-
// Android: Check current status
|
|
314
328
|
const exempted = await AsleepModule.isBatteryOptimizationExempted();
|
|
315
|
-
|
|
316
|
-
|
|
329
|
+
clearErrorIfUnchanged(errorBefore);
|
|
317
330
|
return {
|
|
318
331
|
exempted,
|
|
319
332
|
platform: "android",
|
|
@@ -321,676 +334,494 @@ export const useAsleepStore = create<AsleepState>()(
|
|
|
321
334
|
? "Battery optimization disabled - ready for tracking"
|
|
322
335
|
: "Battery optimization must be disabled for reliable tracking",
|
|
323
336
|
};
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
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
|
+
);
|
|
341
388
|
}
|
|
342
389
|
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* Starts sleep tracking session.
|
|
352
|
-
*
|
|
353
|
-
* Prerequisites:
|
|
354
|
-
* 1. checkAndRestoreTracking() must be called at app startup
|
|
355
|
-
* 2. checkBatteryOptimization() must be called (required on both platforms)
|
|
356
|
-
*
|
|
357
|
-
* @param config Optional tracking configuration
|
|
358
|
-
* @throws Error if prerequisites are not met or tracking is already in progress
|
|
359
|
-
*/
|
|
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;
|
|
365
|
-
try {
|
|
366
|
-
const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
|
|
367
|
-
|
|
368
|
-
// Enforce that checkAndRestoreTracking must be called first
|
|
369
|
-
if (!hasCheckedStatus) {
|
|
370
|
-
addLog("[startTracking] Must call checkAndRestoreTracking() at app startup");
|
|
371
|
-
throw new Error("Must call checkAndRestoreTracking() at app startup before starting tracking");
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
// Enforce battery optimization check on BOTH platforms for consistency
|
|
375
|
-
// This ensures iOS developers handle battery optimization for their Android users
|
|
376
|
-
if (!get().hasCheckedBatteryOptimization) {
|
|
377
|
-
addLog("[startTracking] ERROR: Must check battery optimization first");
|
|
378
|
-
throw new Error(
|
|
379
|
-
"Must call checkBatteryOptimization() before starting tracking. " +
|
|
380
|
-
"This check is required on both iOS and Android to ensure cross-platform consistency.",
|
|
381
|
-
);
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
// Block startTracking execution if setup is in progress
|
|
385
|
-
if (isSetupInProgress) {
|
|
386
|
-
addLog("[startTracking] Cannot start tracking while setup is in progress.");
|
|
387
|
-
throw new Error("Cannot start tracking while setup is in progress.");
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// Prevent duplicate execution if already tracking
|
|
391
|
-
if (get().isTracking) {
|
|
392
|
-
addLog("[startTracking] Tracking is already in progress.");
|
|
393
|
-
throw new Error("Tracking is already in progress.");
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
addLog("[startTracking] Start");
|
|
397
|
-
|
|
398
|
-
const permission = await requestRequiredPermissions();
|
|
399
|
-
if (!permission) {
|
|
400
|
-
// SDK shouldn't show UI directly - throw specific error message
|
|
401
|
-
if (Platform.OS === "android" && Platform.Version >= 33) {
|
|
402
|
-
throw new Error("Microphone and notification permissions are required for sleep tracking");
|
|
403
|
-
} else {
|
|
404
|
-
throw new Error("Microphone permission is required for sleep tracking");
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
// Always verify CURRENT exemption status
|
|
409
|
-
if (Platform.OS === "android") {
|
|
410
|
-
const batteryExempted = await AsleepModule.isBatteryOptimizationExempted();
|
|
411
|
-
if (!batteryExempted) {
|
|
412
|
-
addLog("[startTracking] ERROR: Battery optimization not disabled");
|
|
413
|
-
throw new Error(
|
|
414
|
-
"Battery optimization must be disabled for reliable sleep tracking. " +
|
|
415
|
-
"Call requestBatteryOptimizationExemption() to guide user to settings.",
|
|
416
|
-
);
|
|
417
|
-
}
|
|
418
|
-
addLog("[startTracking] Battery optimization exempted - OK");
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
set({
|
|
422
|
-
didClose: false,
|
|
423
|
-
isTracking: true,
|
|
424
|
-
isAnalyzing: false,
|
|
425
|
-
isRecoveryRequired: false,
|
|
426
|
-
trackingStartTime: new Date(),
|
|
427
|
-
error: null,
|
|
428
|
-
errorInfo: null,
|
|
429
|
-
});
|
|
430
|
-
await AsleepModule.startTracking(config);
|
|
431
|
-
|
|
432
|
-
if (isODAEnabled) {
|
|
433
|
-
addLog("[startTracking] ODA enabled - real-time analysis will start automatically");
|
|
434
|
-
} else {
|
|
435
|
-
addLog("[startTracking] ODA not enabled");
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
addLog("[startTracking] Success");
|
|
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;
|
|
446
|
-
set({
|
|
447
|
-
...(classified ? {} : { error: error.message, errorInfo: null }),
|
|
448
|
-
isTracking: false,
|
|
449
|
-
isAnalyzing: false,
|
|
450
|
-
trackingStartTime: null,
|
|
451
|
-
});
|
|
452
|
-
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
|
+
);
|
|
453
397
|
}
|
|
454
|
-
},
|
|
455
|
-
|
|
456
|
-
stopTracking: async () => {
|
|
457
|
-
// Same dual-signal race as startTracking; see the snapshot rationale there.
|
|
458
|
-
const errorInfoBefore = get().errorInfo;
|
|
459
|
-
try {
|
|
460
|
-
const { addLog } = get();
|
|
461
|
-
addLog("[stopTracking] Start");
|
|
462
398
|
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
}
|
|
481
|
-
},
|
|
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
|
-
}
|
|
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
|
+
},
|
|
490
416
|
|
|
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 {
|
|
491
441
|
await AsleepModule.resumeTracking();
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const convertedReport = convertKeysToCamelCase(report);
|
|
505
|
-
|
|
506
|
-
addLog("[getReport] Success");
|
|
507
|
-
// Guard so a successful query after a clean run does not spam an empty
|
|
508
|
-
// notification, and so we never clobber an unrelated tracking error
|
|
509
|
-
// that arrived during the await.
|
|
510
|
-
if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
|
|
511
|
-
|
|
512
|
-
// Ensure the report has the expected AsleepReport structure
|
|
513
|
-
// Handle cases where native modules might return data in different formats
|
|
514
|
-
if (convertedReport && !convertedReport.session && convertedReport.sessionId) {
|
|
515
|
-
// If the data comes in a flat format (like AsleepSession), convert it to AsleepReport format
|
|
516
|
-
const normalizedReport: AsleepReport = {
|
|
517
|
-
timezone: convertedReport.timezone || "",
|
|
518
|
-
session: {
|
|
519
|
-
id: convertedReport.sessionId || convertedReport.id || sessionId,
|
|
520
|
-
createdTimezone: convertedReport.createdTimezone || "",
|
|
521
|
-
startTime: convertedReport.sessionStartTime || convertedReport.startTime || "",
|
|
522
|
-
endTime: convertedReport.sessionEndTime || convertedReport.endTime,
|
|
523
|
-
unexpectedEndTime: convertedReport.unexpectedEndTime,
|
|
524
|
-
state: convertedReport.state || "",
|
|
525
|
-
sleepStages: convertedReport.sleepStages,
|
|
526
|
-
breathStages: convertedReport.breathStages,
|
|
527
|
-
snoringStages: convertedReport.snoringStages,
|
|
528
|
-
},
|
|
529
|
-
missingDataRatio: convertedReport.missingDataRatio || 0,
|
|
530
|
-
peculiarities: convertedReport.peculiarities || [],
|
|
531
|
-
stat: convertedReport.stat,
|
|
532
|
-
};
|
|
533
|
-
return normalizedReport;
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
return convertedReport as AsleepReport;
|
|
537
|
-
} catch (error: any) {
|
|
538
|
-
// Silent return on failure is a public-API quirk preserved for v1.x
|
|
539
|
-
// compat (v2.0 throws). Surface a dev-only warn so the consumer's
|
|
540
|
-
// Metro log still shows the failure when they're debugging without
|
|
541
|
-
// observing `useAsleep().error` directly.
|
|
542
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReport failed:", error);
|
|
543
|
-
set({ error: error.message, errorInfo: null });
|
|
544
|
-
return null;
|
|
545
|
-
}
|
|
546
|
-
},
|
|
547
|
-
|
|
548
|
-
getReportList: async (fromDate: string, toDate: string) => {
|
|
549
|
-
const errorBefore = get().error;
|
|
550
|
-
try {
|
|
551
|
-
const { addLog } = get();
|
|
552
|
-
addLog(`[getReportList] fromDate: ${fromDate}, toDate: ${toDate}`);
|
|
553
|
-
|
|
554
|
-
const reportList = await AsleepModule.getReportList(fromDate, toDate);
|
|
555
|
-
const convertedList = reportList.map((session: any) => {
|
|
556
|
-
const converted = convertKeysToCamelCase(session);
|
|
557
|
-
// Normalize property names to match other session types
|
|
558
|
-
return {
|
|
559
|
-
id: converted.sessionId || converted.id,
|
|
560
|
-
state: converted.state,
|
|
561
|
-
startTime: converted.sessionStartTime || converted.startTime,
|
|
562
|
-
endTime: converted.sessionEndTime || converted.endTime,
|
|
563
|
-
createdTimezone: converted.createdTimezone,
|
|
564
|
-
unexpectedEndTime: converted.unexpectedEndTime,
|
|
565
|
-
lastReceivedSeqNum: converted.lastReceivedSeqNum,
|
|
566
|
-
timeInBed: converted.timeInBed,
|
|
567
|
-
};
|
|
568
|
-
});
|
|
569
|
-
|
|
570
|
-
addLog("[getReportList] Success");
|
|
571
|
-
if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
|
|
572
|
-
return convertedList;
|
|
573
|
-
} catch (error: any) {
|
|
574
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getReportList failed:", error);
|
|
575
|
-
set({ error: error.message, errorInfo: null });
|
|
576
|
-
return [];
|
|
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}".`);
|
|
577
454
|
}
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
* @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
|
|
617
|
-
*/
|
|
618
|
-
requestMicrophonePermission: async () => {
|
|
619
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
620
|
-
console.warn(
|
|
621
|
-
"[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.",
|
|
622
|
-
);
|
|
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}.`);
|
|
623
493
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
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 {
|
|
628
538
|
if (Platform.OS === "android") {
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
const results = await PermissionsAndroid.requestMultiple(permissions);
|
|
640
|
-
|
|
641
|
-
// Check if all required permissions are granted
|
|
642
|
-
const audioGranted =
|
|
643
|
-
results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
|
|
644
|
-
|
|
645
|
-
const notificationGranted =
|
|
646
|
-
Platform.Version >= 33
|
|
647
|
-
? results[PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS] === PermissionsAndroid.RESULTS.GRANTED
|
|
648
|
-
: true;
|
|
649
|
-
|
|
650
|
-
// Both must be granted for tracking to work properly
|
|
651
|
-
return audioGranted && notificationGranted;
|
|
652
|
-
} catch (err) {
|
|
653
|
-
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] Permission request error:", err);
|
|
654
|
-
return false;
|
|
655
|
-
}
|
|
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;
|
|
656
549
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
},
|
|
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
|
+
},
|
|
673
565
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
566
|
+
enableLog: (print) => {
|
|
567
|
+
if (Platform.OS === "ios") AsleepModule.enableLog(print);
|
|
568
|
+
useAsleepStore.setState({ showDebugLog: print });
|
|
569
|
+
},
|
|
678
570
|
|
|
679
|
-
|
|
571
|
+
clearError: () => useAsleepStore.setState({ error: null }),
|
|
680
572
|
|
|
681
|
-
|
|
682
|
-
|
|
573
|
+
addEventListener: (eventType, listener) => {
|
|
574
|
+
const subscription = emitter.addListener(eventType, listener);
|
|
575
|
+
return () => subscription.remove();
|
|
576
|
+
},
|
|
577
|
+
};
|
|
683
578
|
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
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
|
+
};
|
|
687
624
|
|
|
688
|
-
|
|
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
|
+
});
|
|
689
697
|
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
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
|
+
};
|
|
711
|
+
}
|
|
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
|
+
};
|
|
695
725
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
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
|
+
};
|
|
733
|
+
}
|
|
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
|
+
};
|
|
774
|
+
|
|
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
|
+
};
|
|
785
|
+
|
|
750
786
|
let refCount = 0;
|
|
751
787
|
let teardown: (() => void) | null = null;
|
|
752
788
|
|
|
753
789
|
export const initializeAsleepListeners = (): (() => void) => {
|
|
754
|
-
// Cold start when no teardown is installed. `teardown` is the single source
|
|
755
|
-
// of truth for "listeners are currently attached"; refCount is just an
|
|
756
|
-
// increment-only counter for cleanup balancing. Always incrementing
|
|
757
|
-
// (instead of assigning =1 on cold start) keeps the count correct even if
|
|
758
|
-
// a future change introduces an async seam between this check and the
|
|
759
|
-
// listener registration below.
|
|
760
790
|
if (teardown) {
|
|
761
791
|
refCount++;
|
|
762
792
|
return makeCleanup();
|
|
763
793
|
}
|
|
764
794
|
|
|
765
|
-
const
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
// Connected: iOS userDidDelete, Android NOT IMPLEMENTED
|
|
786
|
-
onUserDeleted: (data: any) => {
|
|
787
|
-
setUserId(null);
|
|
788
|
-
addLog(`[onUserDeleted] userId: ${data.userId}`);
|
|
789
|
-
},
|
|
790
|
-
// Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
|
|
791
|
-
onTrackingCreated: (data: any) => {
|
|
792
|
-
useAsleepStore.setState({
|
|
793
|
-
isTracking: true,
|
|
794
|
-
...(data?.sessionId ? { sessionId: data.sessionId } : {}),
|
|
795
|
-
});
|
|
796
|
-
addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
|
|
797
|
-
},
|
|
798
|
-
// Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
|
|
799
|
-
// Triggers automatic analysis requests in both ODA and non-ODA modes
|
|
800
|
-
onTrackingUploaded: (data: any) => {
|
|
801
|
-
addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
|
|
802
|
-
|
|
803
|
-
// requestAnalysis() flips isAnalyzing internally; no separate setter
|
|
804
|
-
// needed before invoking it (avoids a duplicate subscriber notification).
|
|
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 });
|
|
810
|
-
const triggerAnalysis = () =>
|
|
811
|
-
state.requestAnalysis().catch((error) => {
|
|
812
|
-
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
813
|
-
state.setIsAnalyzing(false);
|
|
814
|
-
});
|
|
815
|
-
|
|
816
|
-
if (state.isODAEnabled && state.isTracking) {
|
|
817
|
-
triggerAnalysis();
|
|
818
|
-
} else if (!state.isODAEnabled && state.isTracking) {
|
|
819
|
-
if (data.sequence >= 10 && data.sequence % 10 === 1) {
|
|
820
|
-
triggerAnalysis();
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
},
|
|
824
|
-
// Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
|
|
825
|
-
onTrackingClosed: (data: { sessionId: string }) => {
|
|
826
|
-
useAsleepStore.setState({
|
|
827
|
-
sessionId: data.sessionId,
|
|
828
|
-
isTracking: false,
|
|
829
|
-
isAnalyzing: false,
|
|
830
|
-
isRecoveryRequired: false,
|
|
831
|
-
didClose: true,
|
|
832
|
-
trackingStartTime: null,
|
|
833
|
-
});
|
|
834
|
-
addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
|
|
835
|
-
},
|
|
836
|
-
// Connected: iOS didFail, Android onFail (AsleepTrackingListener)
|
|
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.
|
|
848
|
-
onTrackingFailed: (error: any) => {
|
|
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))
|
|
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);
|
|
913
|
-
addLog(`[onTrackingError] error: ${errorString}`);
|
|
914
|
-
},
|
|
915
|
-
// Connected: iOS didInterrupt, Android NOT IMPLEMENTED
|
|
916
|
-
onTrackingInterrupted: () => {
|
|
917
|
-
setIsTrackingPaused(true);
|
|
918
|
-
addLog(`[onTrackingInterrupted]`);
|
|
919
|
-
},
|
|
920
|
-
// Connected: iOS didResume, Android NOT IMPLEMENTED
|
|
921
|
-
// Always clear the error: some iOS recovery paths (e.g. cannotActivateInBackground
|
|
922
|
-
// retry) reach this handler without a preceding didInterrupt, and the stale error
|
|
923
|
-
// should still be cleared. Only the paused-state mutation is gated, to dedup the
|
|
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.
|
|
927
|
-
onTrackingResumed: () => {
|
|
928
|
-
const wasPaused = useAsleepStore.getState().isTrackingPaused;
|
|
929
|
-
useAsleepStore.setState(
|
|
930
|
-
wasPaused ? { error: null, errorInfo: null, isTrackingPaused: false } : { error: null, errorInfo: null },
|
|
931
|
-
);
|
|
932
|
-
addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
|
|
933
|
-
},
|
|
934
|
-
// Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
|
|
935
|
-
onMicPermissionDenied: () => {
|
|
936
|
-
addLog(`[onMicPermissionDenied]`);
|
|
937
|
-
},
|
|
938
|
-
// Connected: iOS AsleepLogger callbacks, Android sendEvent called directly
|
|
939
|
-
onDebugLog: (data: any) => {
|
|
940
|
-
addLog(`[onDebugLog] message: ${data.message}`);
|
|
941
|
-
},
|
|
942
|
-
// Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
|
|
943
|
-
onSetupDidComplete: () => {
|
|
944
|
-
useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
|
|
945
|
-
addLog(`[onSetupDidComplete]`);
|
|
946
|
-
},
|
|
947
|
-
// Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
|
|
948
|
-
onSetupDidFail: (data: any) => {
|
|
949
|
-
const errorString = JSON.stringify(data);
|
|
950
|
-
useAsleepStore.setState({
|
|
951
|
-
error: errorString,
|
|
952
|
-
errorInfo: null,
|
|
953
|
-
isSetupInProgress: false,
|
|
954
|
-
isSetupComplete: false,
|
|
955
|
-
});
|
|
956
|
-
addLog(`[onSetupDidFail] error: ${errorString}`);
|
|
957
|
-
},
|
|
958
|
-
// Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
|
|
959
|
-
onSetupInProgress: (data: any) => {
|
|
960
|
-
setIsSetupInProgress(true);
|
|
961
|
-
addLog(`[onSetupInProgress] progress: ${data.progress}%`);
|
|
962
|
-
},
|
|
963
|
-
// Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
|
|
964
|
-
// Android serializes snake_case; normalize so both platforms match AsleepAnalysisResult.
|
|
965
|
-
onAnalysisResult: (data: any) => {
|
|
966
|
-
const normalized = convertKeysToCamelCase(data);
|
|
967
|
-
useAsleepStore.setState({ analysisResult: normalized, isAnalyzing: false });
|
|
968
|
-
if (useAsleepStore.getState().showDebugLog) {
|
|
969
|
-
addLog(`[onAnalysisResult] ${JSON.stringify(normalized)}`);
|
|
970
|
-
}
|
|
971
|
-
},
|
|
972
|
-
};
|
|
973
|
-
|
|
974
|
-
// register all event listeners
|
|
975
|
-
const subscriptions: (() => void)[] = [];
|
|
976
|
-
Object.entries(handlers).forEach(([eventType, handler]) => {
|
|
977
|
-
const subscription = emitter.addListener(eventType, handler);
|
|
978
|
-
subscriptions.push(() => subscription.remove());
|
|
979
|
-
});
|
|
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
|
+
);
|
|
980
815
|
|
|
981
816
|
refCount++;
|
|
982
817
|
teardown = () => {
|
|
983
|
-
subscriptions.forEach((
|
|
818
|
+
subscriptions.forEach((subscription) => subscription.remove());
|
|
984
819
|
teardown = null;
|
|
985
820
|
};
|
|
986
|
-
|
|
987
821
|
return makeCleanup();
|
|
988
822
|
};
|
|
989
823
|
|
|
990
824
|
const makeCleanup = (): (() => void) => {
|
|
991
|
-
// Idempotent per-caller cleanup. The `called` flag is closure-private so
|
|
992
|
-
// calling the returned function twice (e.g. Strict Mode double-effect)
|
|
993
|
-
// decrements the shared ref count only once.
|
|
994
825
|
let called = false;
|
|
995
826
|
return () => {
|
|
996
827
|
if (called) return;
|