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