react-native-asleep 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,112 +1,67 @@
1
- import { create } from "zustand";
2
- import { subscribeWithSelector } from "zustand/middleware";
3
1
  import { EventEmitter } from "expo-modules-core";
4
- import { Platform, PermissionsAndroid } from "react-native";
5
- import {
2
+ import { PermissionsAndroid, Platform } from "react-native";
3
+ import type {
4
+ AsleepAnalysisAck,
5
+ AsleepAnalysisResult,
6
+ AsleepAverageReport,
6
7
  AsleepConfig,
7
- AsleepSetupConfig,
8
+ AsleepCredentials,
8
9
  AsleepErrorCategory,
9
- AsleepErrorInfo,
10
10
  AsleepEventType,
11
11
  AsleepReport,
12
12
  AsleepSession,
13
- AsleepAverageReport,
14
- AsleepAnalysisResult,
15
- AsleepAnalysisAck,
13
+ AsleepSetupConfig,
14
+ SetupStatus,
16
15
  TrackingConfig,
16
+ TrackingStatus,
17
17
  } from "./Asleep.types";
18
+ import { AsleepError } from "./Asleep.types";
18
19
  import AsleepModule from "./AsleepModule";
20
+ import { createStore } from "./store/createStore";
19
21
 
20
22
  const emitter = new EventEmitter(AsleepModule);
21
23
 
22
- // All dev-only warnings below are gated with an inline
23
- // `typeof __DEV__ !== "undefined" && __DEV__` check rather than a helper
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
- ]);
24
+ // Native sessions are already gone for these errors and no close event follows.
25
+ const TERMINAL_TRACKING_ERROR_CODES = new Set<string>(["UPLOAD_TRACKING_TERMINATED"]);
40
26
 
41
- // iOS SDK 3.2.0 stops the recorder without closing the native session when
42
- // audio engine initialization fails. The session must be stopped and restarted.
43
- const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED"]);
27
+ // iOS stops recording but leaves the native session open; stopTracking() closes it.
28
+ const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED", "INTERRUPTION_RECOVERY_FAILED"]);
44
29
 
45
- // iOS SDK 3.2.0 reports this when the audio engine cannot restart in the
46
- // background. The consumer must call resumeTracking() after returning foreground.
30
+ // iOS 3.2.0 needs an explicit foreground resume after this failure.
47
31
  const RECOVERY_REQUIRED_ERROR_CODES = new Set<string>(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
48
32
 
49
- // Numeric-code twin of TERMINAL_TRACKING_ERROR_CODES, matched against the
50
- // `sdkCode` payload field. Android SDK 3.2.x AsleepCore.onErrorCodeReceived
51
- // tears the session down and dual-fires onFail + onFinish for exactly these
52
- // codes (the native module suppresses the duplicate onFinish), so JS must
53
- // clear tracking state here or isTracking stays stuck true.
54
- // Must stay in sync with the Kotlin TERMINAL_TRACKING_ERROR_CODES companion
55
- // set in android/src/main/java/ai/asleep/reactnative/AsleepModule.kt.
33
+ // The first 13 codes are the Android SDK 3.3.x session-teardown set; keep them
34
+ // synchronized with AsleepModule.kt's TERMINAL_TRACKING_ERROR_CODES. The rest are
35
+ // start failures after which no native session exists: iOS 3.3.2 create HTTP
36
+ // 400/403/429/404 (22400, 11403, 11404) and insufficient storage (11008, both
37
+ // platforms). Android reports create failures as 22000. 11010 (alreadyTracking)
38
+ // is deliberately absent because the existing session survives it.
56
39
  const TERMINAL_TRACKING_SDK_CODES = new Set<number>([
57
- 11003, // ERR_AUDIO
58
- 22000,
59
- 22401,
60
- 22409,
61
- 22422,
62
- 22500, // ERR_CREATE_*
63
- 23499, // ERR_UPLOAD_TRACKING_TERMINATED
64
- 24000,
65
- 24400,
66
- 24401,
67
- 24403,
68
- 24404,
69
- 24500, // ERR_CLOSE_*
40
+ 11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500, 11008, 11403, 11404, 22400,
70
41
  ]);
71
42
 
72
- // Upload failures the native session survives: absent from the AsleepCore
73
- // terminal set above, so the Android SDK 3.2.x keeps the session open and later
74
- // uploads continue (UploadDataTask retries 5xx internally before reporting).
75
- // Deliberately small — only codes verifiable in upstream sources.
76
- const TRANSIENT_TRACKING_SDK_CODES = new Set<number>([
77
- 23000, // ERR_UPLOAD_FAILED
78
- 23500, // ERR_UPLOAD_SERVER_ERROR
79
- ]);
43
+ // The native session survives these exhausted upload attempts.
44
+ const TRANSIENT_TRACKING_SDK_CODES = new Set<number>([23000, 23500]);
80
45
 
81
- export interface AsleepState {
82
- didClose: boolean;
83
- isTracking: boolean;
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;
46
+ export interface InternalAsleepState {
47
+ setupStatus: SetupStatus;
48
+ trackingStatus: TrackingStatus;
92
49
  sessionId: string | null;
93
- showDebugLog: boolean;
94
- log: string;
50
+ userId: string | null;
51
+ error: AsleepError | null;
95
52
  analysisResult: AsleepAnalysisResult | null;
96
- isODAEnabled: boolean;
97
53
  isAnalyzing: boolean;
54
+ didClose: boolean;
55
+ isODAEnabled: boolean;
98
56
  trackingStartTime: Date | null;
99
57
  isInitialized: boolean;
100
- isSetupInProgress: boolean;
101
- isSetupComplete: boolean;
102
-
103
- // Service status tracking
104
58
  hasCheckedStatus: boolean;
105
-
106
- // Battery optimization tracking
107
59
  hasCheckedBatteryOptimization: boolean;
60
+ showDebugLog: boolean;
61
+ log: string;
62
+ }
108
63
 
109
- // actions
64
+ export interface AsleepActions {
110
65
  setup: (config: AsleepSetupConfig) => Promise<void>;
111
66
  initAsleepConfig: (config: AsleepConfig) => Promise<void>;
112
67
  checkAndRestoreTracking: () => Promise<{ hasActiveSession: boolean }>;
@@ -115,205 +70,314 @@ export interface AsleepState {
115
70
  startTracking: (config?: TrackingConfig) => Promise<void>;
116
71
  stopTracking: () => Promise<void>;
117
72
  resumeTracking: () => Promise<void>;
118
- getReport: (sessionId: string) => Promise<AsleepReport | null>;
73
+ getReport: (sessionId: string) => Promise<AsleepReport>;
119
74
  getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
120
- getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport | null>;
75
+ getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport>;
121
76
  deleteSession: (sessionId: string) => Promise<void>;
122
- requestMicrophonePermission: () => Promise<boolean>; // deprecated
77
+ requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck>;
78
+ hasRequiredPermissions: () => Promise<boolean>;
123
79
  requestRequiredPermissions: () => Promise<boolean>;
124
80
  setCustomNotification: (title: string, text: string) => Promise<void>;
125
81
  enableLog: (print: boolean) => void;
126
82
  clearError: () => void;
127
- requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck | null>;
128
83
  addEventListener: <K extends keyof AsleepEventType>(
129
84
  eventType: K,
130
85
  listener: (data: AsleepEventType[K]) => void,
131
86
  ) => () => 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
87
  }
151
88
 
152
- const convertKeysToCamelCase = (obj: any): any => {
153
- if (Array.isArray(obj)) {
154
- return obj.map(convertKeysToCamelCase);
155
- } else if (obj !== null && obj.constructor === Object) {
156
- return Object.keys(obj).reduce((acc, key) => {
157
- const camelKey = key.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
158
- acc[camelKey] = convertKeysToCamelCase(obj[key]);
159
- return acc;
89
+ export interface AsleepPublicState {
90
+ status: TrackingStatus;
91
+ isTracking: boolean;
92
+ isTrackingPaused: boolean;
93
+ isRecoveryRequired: boolean;
94
+ isSetupInProgress: boolean;
95
+ isSetupComplete: boolean;
96
+ sessionId: string | null;
97
+ userId: string | null;
98
+ error: AsleepError | null;
99
+ analysisResult: AsleepAnalysisResult | null;
100
+ isAnalyzing: boolean;
101
+ didClose: boolean;
102
+ isODAEnabled: boolean;
103
+ log: string;
104
+ }
105
+
106
+ export type AsleepPublicApi = AsleepPublicState & AsleepActions;
107
+
108
+ const initialTrackingStatus: TrackingStatus =
109
+ typeof AsleepModule.isTracking === "function" && AsleepModule.isTracking() ? "tracking" : "idle";
110
+
111
+ export const useAsleepStore = createStore<InternalAsleepState>(() => ({
112
+ setupStatus: "idle",
113
+ trackingStatus: initialTrackingStatus,
114
+ sessionId: null,
115
+ userId: null,
116
+ error: null,
117
+ analysisResult: null,
118
+ isAnalyzing: false,
119
+ didClose: false,
120
+ isODAEnabled: false,
121
+ trackingStartTime: null,
122
+ isInitialized: false,
123
+ hasCheckedStatus: false,
124
+ hasCheckedBatteryOptimization: false,
125
+ showDebugLog: false,
126
+ log: "",
127
+ }));
128
+
129
+ const convertKeysToCamelCase = (value: any): any => {
130
+ if (Array.isArray(value)) return value.map(convertKeysToCamelCase);
131
+ if (value !== null && value.constructor === Object) {
132
+ return Object.keys(value).reduce((result, key) => {
133
+ const camelKey = key.replace(/_([a-z])/g, (_match, letter: string) => letter.toUpperCase());
134
+ result[camelKey] = convertKeysToCamelCase(value[key]);
135
+ return result;
160
136
  }, {} as any);
161
137
  }
162
- return obj;
138
+ return value;
163
139
  };
164
140
 
165
- export const useAsleepStore = create<AsleepState>()(
166
- subscribeWithSelector((set, get) => ({
167
- // initial state
168
- didClose: false,
169
- isTracking: AsleepModule.isTracking ? AsleepModule.isTracking() : false,
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
- );
141
+ type ErrorOptions = {
142
+ category?: AsleepErrorCategory;
143
+ sdkCode?: number;
144
+ caseName?: string;
145
+ };
243
146
 
244
- set({ isInitialized: true, error: null, errorInfo: null });
245
- addLog("[initAsleepConfig] Success");
246
- return result;
247
- } catch (error: any) {
248
- set({ error: error.message, errorInfo: null });
249
- throw error;
250
- }
251
- },
252
-
253
- checkAndRestoreTracking: async () => {
254
- try {
255
- const { addLog } = get();
256
- addLog("[checkAndRestoreTracking] Start");
257
-
258
- // Check if sleep tracking service is alive
259
- const isAlive = await AsleepModule.isSleepTrackingAlive();
260
-
261
- set({
262
- hasCheckedStatus: true,
263
- });
264
-
265
- // If service is alive on Android, restore connection to it
266
- if (isAlive && Platform.OS === "android") {
267
- addLog("[checkAndRestoreTracking] Service is alive, restoring connection...");
268
- const isConnected = await AsleepModule.connectSleepTracking();
269
-
270
- if (isConnected) {
271
- set({ isTracking: true });
272
- addLog("[checkAndRestoreTracking] Successfully restored connection to existing service");
273
- } else {
274
- addLog("[checkAndRestoreTracking] Failed to restore connection to existing service");
275
- }
276
- }
277
-
278
- addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
279
- return {
280
- hasActiveSession: isAlive,
281
- };
282
- } catch (error: any) {
283
- set({ error: error.message, errorInfo: null });
284
- throw error;
285
- }
286
- },
287
-
288
- /**
289
- * Checks battery optimization status on the device.
290
- * REQUIRED: Must be called before startTracking() on both iOS and Android.
291
- *
292
- * This ensures cross-platform consistency - iOS developers must handle
293
- * battery optimization to prevent their Android users from experiencing issues.
294
- *
295
- * @returns Promise with exemption status and platform information
296
- * @returns {boolean} exempted - Whether battery optimization is disabled (always true on iOS)
297
- * @returns {string} platform - Current platform ('ios' or 'android')
298
- * @returns {string} message - Optional status message
299
- */
300
- checkBatteryOptimization: async () => {
301
- const { addLog } = get();
302
-
303
- addLog("[checkBatteryOptimization] Checking battery optimization status...");
304
-
305
- // Mark that check was performed (required for startTracking)
306
- set({ hasCheckedBatteryOptimization: true });
147
+ export const normalizeError = (source: unknown, fallbackCode: string, options: ErrorOptions = {}): AsleepError => {
148
+ if (source instanceof AsleepError && Object.keys(options).length === 0) return source;
149
+
150
+ const payload =
151
+ source && typeof source === "object"
152
+ ? (source as {
153
+ code?: unknown;
154
+ message?: unknown;
155
+ error?: unknown;
156
+ detail?: unknown;
157
+ sdkCode?: unknown;
158
+ caseName?: unknown;
159
+ })
160
+ : undefined;
161
+ const code = typeof payload?.code === "string" ? payload.code : fallbackCode;
162
+ const message =
163
+ typeof payload?.message === "string"
164
+ ? payload.message
165
+ : typeof payload?.error === "string"
166
+ ? payload.error
167
+ : typeof payload?.detail === "string"
168
+ ? payload.detail
169
+ : source instanceof Error
170
+ ? source.message
171
+ : String(source ?? "Unknown error");
172
+
173
+ return new AsleepError(code, message, {
174
+ cause: source instanceof AsleepError ? (source.cause ?? source) : source,
175
+ category: options.category ?? (source instanceof AsleepError ? source.category : undefined),
176
+ sdkCode:
177
+ options.sdkCode ??
178
+ (typeof payload?.sdkCode === "number"
179
+ ? payload.sdkCode
180
+ : source instanceof AsleepError
181
+ ? source.sdkCode
182
+ : undefined),
183
+ caseName:
184
+ options.caseName ??
185
+ (typeof payload?.caseName === "string"
186
+ ? payload.caseName
187
+ : source instanceof AsleepError
188
+ ? source.caseName
189
+ : undefined),
190
+ });
191
+ };
192
+
193
+ const logPartial = (message: string, state = useAsleepStore.getState()): Partial<InternalAsleepState> => {
194
+ if (!state.showDebugLog) return {};
195
+ const now = new Date();
196
+ const time = `${now.getHours().toString().padStart(2, "0")}:${now
197
+ .getMinutes()
198
+ .toString()
199
+ .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
200
+ const log = `[${time}]${message}`;
201
+ console.log(`[Asleep]${log}`);
202
+ return { log };
203
+ };
204
+
205
+ const addLog = (message: string) => {
206
+ useAsleepStore.setState(logPartial(message));
207
+ };
208
+
209
+ const storeAndThrow = (error: AsleepError, partial: Partial<InternalAsleepState> = {}): never => {
210
+ useAsleepStore.setState({ ...partial, error });
211
+ throw error;
212
+ };
213
+
214
+ const guardedFailure = (
215
+ source: unknown,
216
+ fallbackCode: string,
217
+ errorBefore: AsleepError | null,
218
+ partial: Partial<InternalAsleepState> = {},
219
+ ): never => {
220
+ const current = useAsleepStore.getState().error;
221
+ if (current !== null && current !== errorBefore) {
222
+ useAsleepStore.setState(partial);
223
+ throw current;
224
+ }
225
+ return storeAndThrow(normalizeError(source, fallbackCode), partial);
226
+ };
227
+
228
+ const clearErrorIfUnchanged = (errorBefore: AsleepError | null) => {
229
+ const current = useAsleepStore.getState().error;
230
+ if (current !== null && current === errorBefore) useAsleepStore.setState({ error: null });
231
+ };
232
+
233
+ type NativeCredentials = { apiKey?: string; appId?: string; appSecret?: string };
234
+
235
+ // Runtime guard for JS callers and casts that bypass the AsleepCredentials union.
236
+ const resolveCredentials = (config: AsleepCredentials): NativeCredentials => {
237
+ const { apiKey, appId, appSecret } = (config ?? {}) as { apiKey?: unknown; appId?: unknown; appSecret?: unknown };
238
+ const hasApiKey = apiKey !== undefined;
239
+ const hasToken = appId !== undefined || appSecret !== undefined;
240
+ if (hasApiKey && hasToken) {
241
+ return storeAndThrow(
242
+ new AsleepError("INVALID_ARGUMENT", "Pass either apiKey or appId/appSecret credentials, not both."),
243
+ );
244
+ }
245
+ if (!hasApiKey && !hasToken) {
246
+ return storeAndThrow(
247
+ new AsleepError("INVALID_ARGUMENT", "Credentials are required: pass apiKey or appId/appSecret."),
248
+ );
249
+ }
250
+ const isNonEmpty = (value: unknown): value is string => typeof value === "string" && value.length > 0;
251
+ if (hasApiKey) {
252
+ if (!isNonEmpty(apiKey))
253
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "apiKey must be a non-empty string."));
254
+ return { apiKey };
255
+ }
256
+ if (!isNonEmpty(appId) || !isNonEmpty(appSecret)) {
257
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "appId and appSecret must both be non-empty strings."));
258
+ }
259
+ return { appId, appSecret };
260
+ };
261
+
262
+ const normalizeReport = (report: any, sessionId: string): AsleepReport => {
263
+ const converted = convertKeysToCamelCase(report);
264
+ if (converted && !converted.session && converted.sessionId) {
265
+ return {
266
+ timezone: converted.timezone || "",
267
+ session: {
268
+ id: converted.sessionId || converted.id || sessionId,
269
+ createdTimezone: converted.createdTimezone || "",
270
+ startTime: converted.sessionStartTime || converted.startTime || "",
271
+ endTime: converted.sessionEndTime || converted.endTime,
272
+ unexpectedEndTime: converted.unexpectedEndTime,
273
+ state: converted.state || "",
274
+ sleepStages: converted.sleepStages,
275
+ breathStages: converted.breathStages,
276
+ snoringStages: converted.snoringStages,
277
+ },
278
+ missingDataRatio: converted.missingDataRatio || 0,
279
+ peculiarities: converted.peculiarities || [],
280
+ stat: converted.stat,
281
+ };
282
+ }
283
+ return converted as AsleepReport;
284
+ };
307
285
 
286
+ export const asleepActions: AsleepActions = {
287
+ setup: async (config) => {
288
+ const credentials = resolveCredentials(config);
289
+ const state = useAsleepStore.getState();
290
+ if (state.setupStatus === "inProgress") {
291
+ storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
292
+ }
293
+ if (state.trackingStatus !== "idle") {
294
+ storeAndThrow(new AsleepError("INVALID_STATE", "Cannot execute setup while tracking is in progress."));
295
+ }
296
+
297
+ const errorBefore = state.error;
298
+ addLog("[setup] Start");
299
+ useAsleepStore.setState({ setupStatus: "inProgress" });
300
+ try {
301
+ await AsleepModule.setup(
302
+ credentials.apiKey,
303
+ credentials.appId,
304
+ credentials.appSecret,
305
+ config.baseUrl,
306
+ config.callbackUrl,
307
+ config.service,
308
+ config.enableODA,
309
+ );
310
+ useAsleepStore.setState({
311
+ setupStatus: "complete",
312
+ isODAEnabled: config.enableODA || false,
313
+ isInitialized: true,
314
+ });
315
+ clearErrorIfUnchanged(errorBefore);
316
+ addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
317
+ } catch (error) {
318
+ return guardedFailure(error, "SETUP_FAILED", errorBefore, { setupStatus: "idle" });
319
+ }
320
+ },
321
+
322
+ initAsleepConfig: async (config) => {
323
+ const credentials = resolveCredentials(config);
324
+ const state = useAsleepStore.getState();
325
+ if (state.setupStatus === "inProgress") {
326
+ return storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
327
+ }
328
+ // No tracking-state guard here: checkAndRestoreTracking() reconnects a live
329
+ // session before the app configures the SDK, so this must remain callable
330
+ // while trackingStatus is "tracking" (v1 behavior the restore flow relies on).
331
+ const errorBefore = state.error;
332
+ addLog("[initAsleepConfig] Start");
333
+ useAsleepStore.setState({ setupStatus: "inProgress" });
334
+ try {
335
+ await AsleepModule.initAsleepConfig(
336
+ credentials.apiKey,
337
+ credentials.appId,
338
+ credentials.appSecret,
339
+ config.userId,
340
+ config.baseUrl,
341
+ config.callbackUrl,
342
+ );
343
+ useAsleepStore.setState({ setupStatus: "complete", isInitialized: true });
344
+ clearErrorIfUnchanged(errorBefore);
345
+ addLog("[initAsleepConfig] Success");
346
+ } catch (error) {
347
+ return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, { setupStatus: "idle" });
348
+ }
349
+ },
350
+
351
+ checkAndRestoreTracking: async () => {
352
+ const errorBefore = useAsleepStore.getState().error;
353
+ addLog("[checkAndRestoreTracking] Start");
354
+ try {
355
+ const isAlive = await AsleepModule.isSleepTrackingAlive();
356
+ let trackingStatus = useAsleepStore.getState().trackingStatus;
357
+ if (isAlive && Platform.OS === "android") {
358
+ const isConnected = await AsleepModule.connectSleepTracking();
359
+ if (isConnected) trackingStatus = "tracking";
360
+ }
361
+ useAsleepStore.setState({ hasCheckedStatus: true, trackingStatus });
362
+ clearErrorIfUnchanged(errorBefore);
363
+ addLog(`[checkAndRestoreTracking] Complete - hasActiveSession: ${isAlive}`);
364
+ return { hasActiveSession: isAlive };
365
+ } catch (error) {
366
+ return guardedFailure(error, "CHECK_AND_RESTORE_FAILED", errorBefore);
367
+ }
368
+ },
369
+
370
+ checkBatteryOptimization: async () => {
371
+ const errorBefore = useAsleepStore.getState().error;
372
+ addLog("[checkBatteryOptimization] Checking battery optimization status...");
373
+ useAsleepStore.setState({ hasCheckedBatteryOptimization: true });
374
+ try {
308
375
  if (Platform.OS === "ios") {
309
- addLog("[checkBatteryOptimization] iOS - not applicable");
376
+ clearErrorIfUnchanged(errorBefore);
310
377
  return { exempted: true, platform: "ios" };
311
378
  }
312
-
313
- // Android: Check current status
314
379
  const exempted = await AsleepModule.isBatteryOptimizationExempted();
315
- addLog(`[checkBatteryOptimization] Exempted: ${exempted}`);
316
-
380
+ clearErrorIfUnchanged(errorBefore);
317
381
  return {
318
382
  exempted,
319
383
  platform: "android",
@@ -321,676 +385,496 @@ export const useAsleepStore = create<AsleepState>()(
321
385
  ? "Battery optimization disabled - ready for tracking"
322
386
  : "Battery optimization must be disabled for reliable tracking",
323
387
  };
324
- },
325
-
326
- /**
327
- * Requests battery optimization exemption from the user.
328
- * On Android: Opens system settings for battery optimization.
329
- * On iOS: No-op, returns true (not applicable).
330
- *
331
- * Use this when checkBatteryOptimization() returns exempted: false.
332
- *
333
- * @returns Promise<boolean> - true if already exempted or iOS, false if settings opened
334
- */
335
- requestBatteryOptimizationExemption: async () => {
336
- const { addLog } = get();
337
-
338
- if (Platform.OS === "ios") {
339
- addLog("[requestBatteryOptimizationExemption] iOS - not applicable");
340
- return true; // Not applicable on iOS
388
+ } catch (error) {
389
+ return guardedFailure(error, "CHECK_BATTERY_OPTIMIZATION_FAILED", errorBefore);
390
+ }
391
+ },
392
+
393
+ requestBatteryOptimizationExemption: async () => {
394
+ const errorBefore = useAsleepStore.getState().error;
395
+ if (Platform.OS === "ios") {
396
+ clearErrorIfUnchanged(errorBefore);
397
+ return true;
398
+ }
399
+ try {
400
+ const result = await AsleepModule.requestBatteryOptimizationExemption();
401
+ clearErrorIfUnchanged(errorBefore);
402
+ return result;
403
+ } catch (error) {
404
+ return guardedFailure(error, "REQUEST_BATTERY_EXEMPTION_FAILED", errorBefore);
405
+ }
406
+ },
407
+
408
+ startTracking: async (config) => {
409
+ const state = useAsleepStore.getState();
410
+ if (!state.hasCheckedStatus) {
411
+ storeAndThrow(
412
+ new AsleepError(
413
+ "MISSING_PREREQUISITE",
414
+ "Must call checkAndRestoreTracking() at app startup before starting tracking.",
415
+ ),
416
+ );
417
+ }
418
+ if (!state.hasCheckedBatteryOptimization) {
419
+ storeAndThrow(
420
+ new AsleepError("MISSING_PREREQUISITE", "Must call checkBatteryOptimization() before starting tracking."),
421
+ );
422
+ }
423
+ if (state.setupStatus === "inProgress") {
424
+ storeAndThrow(new AsleepError("INVALID_STATE", "Cannot start tracking while setup is in progress."));
425
+ }
426
+ if (state.trackingStatus !== "idle") {
427
+ storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Tracking is already in progress."));
428
+ }
429
+
430
+ const errorBefore = state.error;
431
+ try {
432
+ if (!(await asleepActions.hasRequiredPermissions())) {
433
+ storeAndThrow(
434
+ new AsleepError(
435
+ "PERMISSION_DENIED",
436
+ "Microphone permission is required. Call requestRequiredPermissions() before startTracking().",
437
+ ),
438
+ );
341
439
  }
342
440
 
343
- addLog("[requestBatteryOptimizationExemption] Opening battery settings...");
344
-
345
- // This just opens settings, doesn't wait
346
- // Returns true if already exempted, false if settings opened
347
- return await AsleepModule.requestBatteryOptimizationExemption();
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;
441
+ if (Platform.OS === "android" && !(await AsleepModule.isBatteryOptimizationExempted())) {
442
+ storeAndThrow(
443
+ new AsleepError(
444
+ "BATTERY_NOT_EXEMPTED",
445
+ "Battery optimization must be disabled before startTracking(). Call requestBatteryOptimizationExemption().",
446
+ ),
447
+ );
453
448
  }
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
449
 
463
- const result = await AsleepModule.stopTracking();
464
- set({
465
- didClose: true,
466
- ...(result ? { sessionId: result } : {}),
467
- isTracking: false,
468
- isAnalyzing: false,
469
- isRecoveryRequired: false,
470
- trackingStartTime: null,
471
- error: null,
472
- errorInfo: null,
473
- });
474
-
475
- addLog(`[stopTracking] Success - result: ${result}`);
476
- } catch (error: any) {
477
- const nowInfo = get().errorInfo;
478
- if (nowInfo === null || nowInfo === errorInfoBefore) set({ error: error.message, errorInfo: null });
479
- throw error;
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
- }
450
+ useAsleepStore.setState({
451
+ didClose: false,
452
+ trackingStatus: "tracking",
453
+ isAnalyzing: false,
454
+ trackingStartTime: new Date(),
455
+ });
456
+ await AsleepModule.startTracking(config);
457
+ clearErrorIfUnchanged(errorBefore);
458
+ addLog("[startTracking] Success");
459
+ } catch (error) {
460
+ return guardedFailure(error, "START_TRACKING_FAILED", errorBefore, {
461
+ trackingStatus: "idle",
462
+ isAnalyzing: false,
463
+ trackingStartTime: null,
464
+ });
465
+ }
466
+ },
490
467
 
468
+ stopTracking: async () => {
469
+ const errorBefore = useAsleepStore.getState().error;
470
+ try {
471
+ const result = await AsleepModule.stopTracking();
472
+ useAsleepStore.setState({
473
+ didClose: true,
474
+ ...(typeof result === "string" && result ? { sessionId: result } : {}),
475
+ trackingStatus: "idle",
476
+ isAnalyzing: false,
477
+ trackingStartTime: null,
478
+ });
479
+ clearErrorIfUnchanged(errorBefore);
480
+ addLog(`[stopTracking] Success - result: ${result}`);
481
+ } catch (error) {
482
+ return guardedFailure(error, "STOP_TRACKING_FAILED", errorBefore);
483
+ }
484
+ },
485
+
486
+ resumeTracking: async () => {
487
+ if (Platform.OS !== "ios") {
488
+ storeAndThrow(new AsleepError("UNSUPPORTED_PLATFORM", "resumeTracking is only supported on iOS."));
489
+ }
490
+ const errorBefore = useAsleepStore.getState().error;
491
+ try {
491
492
  await AsleepModule.resumeTracking();
492
- },
493
-
494
- getReport: async (sessionId: string) => {
495
- // Snapshot the error before the await so we only clear it on success
496
- // if no concurrent failure (e.g. onTrackingFailed firing during the
497
- // network round-trip) wrote a different error in the meantime.
498
- const errorBefore = get().error;
499
- try {
500
- const { addLog } = get();
501
- addLog(`[getReport] sessionId: ${sessionId}`);
502
-
503
- const report = await AsleepModule.getReport(sessionId);
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;
493
+ clearErrorIfUnchanged(errorBefore);
494
+ } catch (error) {
495
+ return guardedFailure(error, "RESUME_TRACKING_FAILED", errorBefore);
496
+ }
497
+ },
498
+
499
+ getReport: async (sessionId) => {
500
+ const errorBefore = useAsleepStore.getState().error;
501
+ try {
502
+ const payload = await AsleepModule.getReport(sessionId);
503
+ if (payload == null) {
504
+ throw new AsleepError("REPORT_NOT_FOUND", `No report available for session "${sessionId}".`);
545
505
  }
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 [];
577
- }
578
- },
579
-
580
- deleteSession: async (sessionId: string) => {
581
- const errorBefore = get().error;
582
- try {
583
- const { addLog } = get();
584
- addLog(`[deleteSession] sessionId: ${sessionId}`);
585
-
586
- await AsleepModule.deleteSession(sessionId);
587
-
588
- addLog("[deleteSession] Success");
589
- if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
590
- } catch (error: any) {
591
- set({ error: error.message, errorInfo: null });
592
- throw error;
593
- }
594
- },
595
-
596
- getAverageReport: async (fromDate: string, toDate: string) => {
597
- const errorBefore = get().error;
598
- try {
599
- const { addLog } = get();
600
- addLog(`[getAverageReport] fromDate: ${fromDate}, toDate: ${toDate}`);
601
-
602
- const averageReport = await AsleepModule.getAverageReport(fromDate, toDate);
603
- const convertedReport = convertKeysToCamelCase(averageReport);
604
-
605
- addLog("[getAverageReport] Success");
606
- if (get().error !== null && get().error === errorBefore) set({ error: null, errorInfo: null });
607
- return convertedReport;
608
- } catch (error: any) {
609
- if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] getAverageReport failed:", error);
610
- set({ error: error.message, errorInfo: null });
611
- return null;
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
- );
506
+ const report = normalizeReport(payload, sessionId);
507
+ clearErrorIfUnchanged(errorBefore);
508
+ return report;
509
+ } catch (error) {
510
+ return guardedFailure(error, "GET_REPORT_FAILED", errorBefore);
511
+ }
512
+ },
513
+
514
+ getReportList: async (fromDate, toDate) => {
515
+ const errorBefore = useAsleepStore.getState().error;
516
+ try {
517
+ const reportList = (await AsleepModule.getReportList(fromDate, toDate)) ?? [];
518
+ const result = reportList.map((session: any) => {
519
+ const converted = convertKeysToCamelCase(session);
520
+ return {
521
+ id: converted.sessionId || converted.id,
522
+ state: converted.state,
523
+ startTime: converted.sessionStartTime || converted.startTime,
524
+ endTime: converted.sessionEndTime || converted.endTime,
525
+ createdTimezone: converted.createdTimezone,
526
+ unexpectedEndTime: converted.unexpectedEndTime,
527
+ lastReceivedSeqNum: converted.lastReceivedSeqNum,
528
+ timeInBed: converted.timeInBed,
529
+ };
530
+ });
531
+ clearErrorIfUnchanged(errorBefore);
532
+ return result;
533
+ } catch (error) {
534
+ return guardedFailure(error, "GET_REPORT_LIST_FAILED", errorBefore);
535
+ }
536
+ },
537
+
538
+ getAverageReport: async (fromDate, toDate) => {
539
+ const errorBefore = useAsleepStore.getState().error;
540
+ try {
541
+ const payload = await AsleepModule.getAverageReport(fromDate, toDate);
542
+ if (payload == null) {
543
+ throw new AsleepError("REPORT_NOT_FOUND", `No average report available for ${fromDate} to ${toDate}.`);
623
544
  }
624
- return get().requestRequiredPermissions();
625
- },
626
-
627
- requestRequiredPermissions: async () => {
545
+ const result = convertKeysToCamelCase(payload);
546
+ clearErrorIfUnchanged(errorBefore);
547
+ return result;
548
+ } catch (error) {
549
+ return guardedFailure(error, "GET_AVERAGE_REPORT_FAILED", errorBefore);
550
+ }
551
+ },
552
+
553
+ deleteSession: async (sessionId) => {
554
+ const errorBefore = useAsleepStore.getState().error;
555
+ try {
556
+ await AsleepModule.deleteSession(sessionId);
557
+ clearErrorIfUnchanged(errorBefore);
558
+ } catch (error) {
559
+ return guardedFailure(error, "DELETE_SESSION_FAILED", errorBefore);
560
+ }
561
+ },
562
+
563
+ requestAnalysis: async () => {
564
+ const errorBefore = useAsleepStore.getState().error;
565
+ useAsleepStore.setState({ isAnalyzing: true });
566
+ try {
567
+ const result = convertKeysToCamelCase(await AsleepModule.requestAnalysis());
568
+ clearErrorIfUnchanged(errorBefore);
569
+ return result;
570
+ } catch (error) {
571
+ return guardedFailure(error, "REQUEST_ANALYSIS_FAILED", errorBefore, { isAnalyzing: false });
572
+ }
573
+ },
574
+
575
+ hasRequiredPermissions: async () => {
576
+ const errorBefore = useAsleepStore.getState().error;
577
+ try {
578
+ const result = await AsleepModule.hasRequiredPermissions();
579
+ clearErrorIfUnchanged(errorBefore);
580
+ return result;
581
+ } catch (error) {
582
+ return guardedFailure(error, "CHECK_PERMISSION_FAILED", errorBefore);
583
+ }
584
+ },
585
+
586
+ requestRequiredPermissions: async () => {
587
+ const errorBefore = useAsleepStore.getState().error;
588
+ try {
628
589
  if (Platform.OS === "android") {
629
- try {
630
- // Prepare permissions array with RECORD_AUDIO
631
- const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
632
-
633
- // Add POST_NOTIFICATIONS for Android 13+ (API level 33)
634
- if (Platform.Version >= 33) {
635
- permissions.push(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
636
- }
637
-
638
- // Request all permissions together for better UX (single dialog)
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
- }
590
+ const permissions = [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO];
591
+ if (Platform.Version >= 33) permissions.push(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
592
+ const results = await PermissionsAndroid.requestMultiple(permissions);
593
+ // POST_NOTIFICATIONS is requested for foreground-service notification
594
+ // visibility but is not needed for tracking to run, so the returned
595
+ // boolean mirrors hasRequiredPermissions(): microphone-side grants only.
596
+ const audioGranted =
597
+ results[PermissionsAndroid.PERMISSIONS.RECORD_AUDIO] === PermissionsAndroid.RESULTS.GRANTED;
598
+ clearErrorIfUnchanged(errorBefore);
599
+ return audioGranted;
656
600
  }
657
- // iOS uses native implementation
658
- return AsleepModule.requestRequiredPermissions();
659
- },
660
-
661
- setCustomNotification: async (_title: string, _text: string) => {
662
- // Native method removed; notification config now flows through startTracking options.
663
- if (typeof __DEV__ !== "undefined" && __DEV__)
664
- console.warn(
665
- "[Asleep] setCustomNotification is deprecated and a no-op; pass `{ android: { notification: { title, text, icon } } }` to startTracking() instead",
666
- );
667
- },
668
-
669
- enableLog: (print: boolean) => {
670
- if (Platform.OS === "ios") AsleepModule.enableLog(print);
671
- set({ showDebugLog: print });
672
- },
601
+ const result = await AsleepModule.requestRequiredPermissions();
602
+ clearErrorIfUnchanged(errorBefore);
603
+ return result;
604
+ } catch (error) {
605
+ return guardedFailure(error, "REQUEST_PERMISSION_FAILED", errorBefore);
606
+ }
607
+ },
608
+
609
+ setCustomNotification: async (_title, _text) => {
610
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
611
+ console.warn(
612
+ "[Asleep] setCustomNotification is deprecated and a no-op; pass notification options to startTracking() instead.",
613
+ );
614
+ }
615
+ },
673
616
 
674
- requestAnalysis: async () => {
675
- try {
676
- const { addLog, showDebugLog } = get();
677
- addLog("[requestAnalysis] Start");
617
+ enableLog: (print) => {
618
+ if (Platform.OS === "ios") AsleepModule.enableLog(print);
619
+ useAsleepStore.setState({ showDebugLog: print });
620
+ },
678
621
 
679
- set({ isAnalyzing: true, error: null, errorInfo: null });
622
+ clearError: () => useAsleepStore.setState({ error: null }),
680
623
 
681
- const result = await AsleepModule.requestAnalysis();
682
- const convertedResult = convertKeysToCamelCase(result);
624
+ addEventListener: (eventType, listener) => {
625
+ const subscription = emitter.addListener(eventType, listener);
626
+ return () => subscription.remove();
627
+ },
628
+ };
683
629
 
684
- // analysisResult and isAnalyzing are owned by the onAnalysisResult event handler on both
685
- // platforms. Android resolves the promise with the full session AND fires the event;
686
- // iOS resolves with an ack only. Writing state here would double-update on Android.
630
+ let lastInternal: InternalAsleepState | null = null;
631
+ let lastPublic: AsleepPublicApi | null = null;
632
+
633
+ export const toPublicState = (internal: InternalAsleepState): AsleepPublicApi => {
634
+ if (internal === lastInternal && lastPublic) return lastPublic;
635
+ // Recovery-required is still a live native session on main; preserve that
636
+ // contract while representing the recovery fact with one enum value.
637
+ const isTracking = internal.trackingStatus !== "idle";
638
+ const next: AsleepPublicApi = {
639
+ status: internal.trackingStatus,
640
+ isTracking,
641
+ isTrackingPaused: internal.trackingStatus === "paused",
642
+ isRecoveryRequired: internal.trackingStatus === "recoveryRequired",
643
+ isSetupInProgress: internal.setupStatus === "inProgress",
644
+ isSetupComplete: internal.setupStatus === "complete",
645
+ sessionId: internal.sessionId,
646
+ userId: internal.userId,
647
+ error: internal.error,
648
+ analysisResult: internal.analysisResult,
649
+ isAnalyzing: internal.isAnalyzing,
650
+ didClose: internal.didClose,
651
+ isODAEnabled: internal.isODAEnabled,
652
+ log: internal.log,
653
+ ...asleepActions,
654
+ };
655
+ lastInternal = internal;
656
+ if (
657
+ lastPublic &&
658
+ lastPublic.status === next.status &&
659
+ lastPublic.sessionId === next.sessionId &&
660
+ lastPublic.userId === next.userId &&
661
+ lastPublic.error === next.error &&
662
+ lastPublic.analysisResult === next.analysisResult &&
663
+ lastPublic.isAnalyzing === next.isAnalyzing &&
664
+ lastPublic.didClose === next.didClose &&
665
+ lastPublic.isODAEnabled === next.isODAEnabled &&
666
+ lastPublic.log === next.log &&
667
+ lastPublic.isSetupInProgress === next.isSetupInProgress &&
668
+ lastPublic.isSetupComplete === next.isSetupComplete
669
+ ) {
670
+ return lastPublic;
671
+ }
672
+ lastPublic = next;
673
+ return lastPublic;
674
+ };
687
675
 
688
- if (showDebugLog) addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
676
+ type EventName = keyof AsleepEventType;
677
+
678
+ const transitionForEvent = (
679
+ eventType: EventName,
680
+ payload: any,
681
+ state: InternalAsleepState,
682
+ ): { partial: Partial<InternalAsleepState>; log: string; requestAnalysis?: boolean } => {
683
+ switch (eventType) {
684
+ case "onUserJoined":
685
+ return { partial: { userId: payload.userId }, log: `[onUserJoined] userId: ${payload.userId}` };
686
+ case "onUserJoinFailed":
687
+ return {
688
+ partial: { error: normalizeError(payload, "USER_JOIN_FAILED") },
689
+ log: `[onUserJoinFailed] error: ${payload?.message ?? payload?.detail ?? payload?.error ?? "Unknown error"}`,
690
+ };
691
+ case "onUserDeleted":
692
+ return { partial: { userId: null }, log: `[onUserDeleted] userId: ${payload.userId}` };
693
+ case "onTrackingCreated":
694
+ return {
695
+ partial: { trackingStatus: "tracking", ...(payload?.sessionId ? { sessionId: payload.sessionId } : {}) },
696
+ log: `[onTrackingCreated]${payload?.sessionId ? ` sessionId: ${payload.sessionId}` : ""}`,
697
+ };
698
+ case "onTrackingUploaded": {
699
+ const shouldAnalyze =
700
+ state.trackingStatus !== "idle" &&
701
+ (state.isODAEnabled || (payload.sequence >= 10 && payload.sequence % 10 === 1));
702
+ return {
703
+ partial: {
704
+ // iOS 3.2.0 emits didResume before its engine restart is proven.
705
+ // Only a completed upload clears recovery; see AGENTS.md
706
+ // "Native Behavior Compensations".
707
+ ...(state.trackingStatus === "recoveryRequired" ? { trackingStatus: "tracking" as const } : {}),
708
+ ...(shouldAnalyze ? { isAnalyzing: true } : {}),
709
+ },
710
+ log: `[onTrackingUploaded] sequence: ${payload.sequence}`,
711
+ requestAnalysis: shouldAnalyze,
712
+ };
713
+ }
714
+ case "onTrackingClosed":
715
+ return {
716
+ partial: {
717
+ sessionId: payload.sessionId,
718
+ trackingStatus: "idle",
719
+ isAnalyzing: false,
720
+ didClose: true,
721
+ trackingStartTime: null,
722
+ },
723
+ log: `[onTrackingClosed] sessionId: ${payload.sessionId}`,
724
+ };
725
+ case "onTrackingFailed": {
726
+ const recordingDead = !!payload && RECORDING_DEAD_ERROR_CODES.has(payload.code);
727
+ const recoveryRequired = !!payload && RECOVERY_REQUIRED_ERROR_CODES.has(payload.code);
728
+ const terminal =
729
+ !!payload &&
730
+ !recordingDead &&
731
+ !recoveryRequired &&
732
+ (TERMINAL_TRACKING_ERROR_CODES.has(payload.code) || TERMINAL_TRACKING_SDK_CODES.has(payload.sdkCode));
733
+ const transient = !!payload && TRANSIENT_TRACKING_SDK_CODES.has(payload.sdkCode);
734
+ const category: AsleepErrorCategory = recordingDead
735
+ ? "recordingDead"
736
+ : recoveryRequired
737
+ ? "recoveryRequired"
738
+ : terminal
739
+ ? "terminal"
740
+ : transient
741
+ ? "transient"
742
+ : "unknown";
743
+ const error = normalizeError(payload, "TRACKING_FAILED", {
744
+ category,
745
+ sdkCode: typeof payload?.sdkCode === "number" ? payload.sdkCode : undefined,
746
+ caseName: typeof payload?.caseName === "string" ? payload.caseName : undefined,
747
+ });
689
748
 
690
- return convertedResult;
691
- } catch (error: any) {
692
- if (typeof __DEV__ !== "undefined" && __DEV__) console.warn("[Asleep] requestAnalysis failed:", error);
693
- set({ error: error.message, errorInfo: null, isAnalyzing: false });
694
- return null;
749
+ if (terminal) {
750
+ return {
751
+ partial: {
752
+ // iOS closeSessionSilently (upload 4xx) does not emit didClose, and
753
+ // start failures never create a session, so this branch must clear
754
+ // the projected session state itself.
755
+ error,
756
+ trackingStatus: "idle",
757
+ isAnalyzing: false,
758
+ didClose: true,
759
+ trackingStartTime: null,
760
+ },
761
+ log: `[onTrackingError] error: ${error.message}`,
762
+ };
695
763
  }
696
- },
697
-
698
- addEventListener: <K extends keyof AsleepEventType>(eventType: K, listener: (data: AsleepEventType[K]) => void) => {
699
- const subscription = emitter.addListener(eventType, listener);
700
- return () => subscription.remove();
701
- },
702
-
703
- getTrackingDurationMinutes: () => {
704
- const { trackingStartTime } = get();
705
- if (!trackingStartTime) return 0;
706
- return Math.floor((Date.now() - trackingStartTime.getTime()) / (1000 * 60));
707
- },
708
-
709
- // internal actions
710
- // setError takes a raw string, so any structured classification is stale;
711
- // reset errorInfo rather than let a previous event's category linger.
712
- setError: (error) => set({ error, errorInfo: null }),
713
- clearError: () => set({ error: null, errorInfo: null }),
714
- setUserId: (userId) => set({ userId }),
715
- setSessionId: (sessionId) => set({ sessionId }),
716
- setIsTracking: (isTracking) => set({ isTracking }),
717
- setIsTrackingPaused: (isTrackingPaused) => set({ isTrackingPaused }),
718
- setDidClose: (didClose) => set({ didClose }),
719
- setAnalysisResult: (result) => set({ analysisResult: result }),
720
- setIsAnalyzing: (isAnalyzing) => set({ isAnalyzing }),
721
- setTrackingStartTime: (time) => set({ trackingStartTime: time }),
722
- setIsInitialized: (initialized) => set({ isInitialized: initialized }),
723
- setIsSetupInProgress: (inProgress) => set({ isSetupInProgress: inProgress }),
724
- setIsSetupComplete: (complete) => set({ isSetupComplete: complete }),
725
- setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
726
- setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
727
-
728
- addLog: (log: string) => {
729
- // Zero-cost when the consumer has not opted into debug logging. Without
730
- // this guard, every native event handler would cause a spurious
731
- // subscriber notification on top of any actual data update.
732
- const { showDebugLog } = get();
733
- if (!showDebugLog) return;
734
- const now = new Date();
735
- const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
736
- .getMinutes()
737
- .toString()
738
- .padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
739
- const formattedLog = `[${dateString}]${log}`;
740
- console.log(`[Asleep]${formattedLog}`);
741
- set({ log: formattedLog });
742
- },
743
- })),
744
- );
745
-
746
- // Ref-counted registration. Each caller (useAsleep effect, background context,
747
- // etc.) increments on entry and decrements via the returned cleanup. Native
748
- // listeners only attach on 0→1 and detach on the final 1→0, so concurrent
749
- // consumers cannot tear each other's subscriptions down.
764
+ if (recordingDead) {
765
+ return {
766
+ partial: {
767
+ // iOS audioInitializationFailed and interruptionRecoveryFailed stop
768
+ // the recorder but keep the native session open (didClose=false).
769
+ error,
770
+ trackingStatus: "idle",
771
+ isAnalyzing: false,
772
+ didClose: false,
773
+ trackingStartTime: null,
774
+ },
775
+ log: `[onTrackingError] error: ${error.message}`,
776
+ };
777
+ }
778
+ if (recoveryRequired) {
779
+ return {
780
+ // iOS cannotActivateInBackground keeps the session alive. 3.3.x also
781
+ // retries on foreground; only a later upload proves recovery.
782
+ partial: { error, trackingStatus: "recoveryRequired" },
783
+ log: `[onTrackingError] error: ${error.message}`,
784
+ };
785
+ }
786
+ return { partial: { error }, log: `[onTrackingError] error: ${error.message}` };
787
+ }
788
+ case "onTrackingInterrupted":
789
+ return { partial: { trackingStatus: "paused" }, log: "[onTrackingInterrupted]" };
790
+ case "onTrackingResumed":
791
+ return {
792
+ partial: {
793
+ error: null,
794
+ // iOS 3.2.1-3.3.0 can emit didResume twice, and recovery paths can
795
+ // resume without a prior pause. Always clear the error, but mutate
796
+ // the paused state only for the first event.
797
+ ...(state.trackingStatus === "paused" ? { trackingStatus: "tracking" as const } : {}),
798
+ },
799
+ log:
800
+ state.trackingStatus === "paused"
801
+ ? "[onTrackingResumed]"
802
+ : "[onTrackingResumed] (no prior pause; error cleared)",
803
+ };
804
+ case "onMicPermissionDenied":
805
+ return { partial: {}, log: "[onMicPermissionDenied]" };
806
+ case "onDebugLog":
807
+ return { partial: {}, log: `[onDebugLog] message: ${payload.message}` };
808
+ case "onSetupDidComplete":
809
+ return { partial: { setupStatus: "complete" }, log: "[onSetupDidComplete]" };
810
+ case "onSetupDidFail":
811
+ return {
812
+ partial: { error: normalizeError(payload, "SETUP_FAILED"), setupStatus: "idle" },
813
+ log: `[onSetupDidFail] error: ${payload?.message ?? payload?.error ?? "Unknown error"}`,
814
+ };
815
+ case "onSetupInProgress":
816
+ return { partial: { setupStatus: "inProgress" }, log: `[onSetupInProgress] progress: ${payload.progress}%` };
817
+ case "onAnalysisResult": {
818
+ // Android SDK 3.2.x emits snake_case while iOS emits camelCase.
819
+ const analysisResult = convertKeysToCamelCase(payload);
820
+ return {
821
+ partial: { analysisResult, isAnalyzing: false },
822
+ log: `[onAnalysisResult] ${JSON.stringify(analysisResult)}`,
823
+ };
824
+ }
825
+ }
826
+ };
827
+
828
+ const applyEvent = (eventType: EventName, payload: unknown) => {
829
+ const state = useAsleepStore.getState();
830
+ const transition = transitionForEvent(eventType, payload, state);
831
+ useAsleepStore.setState({ ...transition.partial, ...logPartial(transition.log, state) });
832
+ if (transition.requestAnalysis) {
833
+ void asleepActions.requestAnalysis().catch((error) => {
834
+ addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
835
+ });
836
+ }
837
+ };
838
+
750
839
  let refCount = 0;
751
840
  let teardown: (() => void) | null = null;
752
841
 
753
842
  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
843
  if (teardown) {
761
844
  refCount++;
762
845
  return makeCleanup();
763
846
  }
764
847
 
765
- const store = useAsleepStore.getState();
766
- const { addLog, setUserId, setIsTrackingPaused, setIsSetupInProgress } = store;
767
-
768
- // event handlers — each native SDK event corresponds to one logical state
769
- // transaction. Use a single useAsleepStore.setState per handler so consumers
770
- // subscribed via useAsleep re-render once per event, not once per field.
771
- const handlers = {
772
- // Connected: iOS userDidJoin, Android onSuccess (AsleepConfigListener)
773
- onUserJoined: (data: any) => {
774
- setUserId(data.userId);
775
- addLog(`[onUserJoined] userId: ${data.userId}`);
776
- },
777
- // Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
778
- onUserJoinFailed: (error: any) => {
779
- const errorString = JSON.stringify(error);
780
- // Not a tracking-runtime failure; errorInfo stays reserved for
781
- // onTrackingFailed classification.
782
- useAsleepStore.setState({ error: errorString, errorInfo: null });
783
- addLog(`[onUserJoinFailed] error: ${errorString}`);
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
- });
848
+ const eventTypes: EventName[] = [
849
+ "onUserJoined",
850
+ "onUserJoinFailed",
851
+ "onUserDeleted",
852
+ "onTrackingCreated",
853
+ "onTrackingUploaded",
854
+ "onTrackingClosed",
855
+ "onTrackingFailed",
856
+ "onTrackingInterrupted",
857
+ "onTrackingResumed",
858
+ "onMicPermissionDenied",
859
+ "onDebugLog",
860
+ "onSetupDidComplete",
861
+ "onSetupDidFail",
862
+ "onSetupInProgress",
863
+ "onAnalysisResult",
864
+ ];
865
+ const subscriptions = eventTypes.map((eventType) =>
866
+ emitter.addListener(eventType, (payload: unknown) => applyEvent(eventType, payload)),
867
+ );
980
868
 
981
869
  refCount++;
982
870
  teardown = () => {
983
- subscriptions.forEach((unsubscribe) => unsubscribe());
871
+ subscriptions.forEach((subscription) => subscription.remove());
984
872
  teardown = null;
985
873
  };
986
-
987
874
  return makeCleanup();
988
875
  };
989
876
 
990
877
  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
878
  let called = false;
995
879
  return () => {
996
880
  if (called) return;