react-native-asleep 1.0.18 → 1.2.0

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