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.
package/README.md CHANGED
@@ -1,58 +1,84 @@
1
1
  # react-native-asleep
2
2
 
3
- Advanced sleep tracking SDK for React Native applications, powered by Asleep's AI technology.
3
+ [English](./README.md) | [한국어](./README.ko.md)
4
4
 
5
- ## Status
5
+ Sleep tracking for React Native and Expo apps, powered by Asleep's AI technology. The SDK uses the device microphone, requires no wearable, and exposes one React hook plus typed data models for iOS and Android.
6
6
 
7
- This SDK is under active development. The API may evolve between minor versions until v2.0 — pin to exact versions and review the [CHANGELOG](./CHANGELOG.md) before upgrading.
7
+ > This SDK is under active development. v2 has a deliberately small public surface. Pin exact versions and review the [changelog](./CHANGELOG.md) before upgrading.
8
8
 
9
- ## Overview
9
+ ## What is included
10
10
 
11
- Non-invasive sleep tracking via the device microphone — no wearables required. Detects sleep stages and produces detailed reports. Works on iOS and Android, exposes a single React hook plus typed data models.
11
+ - Microphone-based sleep tracking and Android service restoration
12
+ - Sleep reports, session lists, average reports, and in-progress analysis
13
+ - A shared state model across iOS and Android
14
+ - Structured `AsleepError` values with recovery categories
15
+ - `useAsleep()` for React and a small `Asleep` API for non-React code
16
+
17
+ ## Requirements
18
+
19
+ | Component | Minimum |
20
+ |---|---|
21
+ | React Native | 0.74 |
22
+ | React | 18.2 |
23
+ | iOS deployment target | 14.0 |
24
+ | Android `minSdkVersion` | 24 |
25
+
26
+ The example app is currently verified with React Native 0.79.2, Expo 53, React 19.0.0, and Android compile/target SDK 34.
27
+
28
+ Bundled native SDK versions. The React Native package follows its own semver; its version number does not mirror the native SDKs.
29
+
30
+ | react-native-asleep | iOS SDK | Android SDK |
31
+ |---|---|---|
32
+ | 2.0.0 | 3.3.2 | 3.3.1 |
33
+ | 1.0.17 – 1.2.0 | 3.2.0 | 3.2.1 |
34
+ | 1.0.15 | 3.2.0 | 3.2.0 |
35
+ | 1.0.14 | 3.1.8 | 3.1.5 |
36
+ | 1.0.13 | 3.1.6 | 3.1.4 |
37
+
38
+ 1.2.0 already contained the breaking v2 API; 2.0.0 is the semver-correct release of that API.
12
39
 
13
40
  ## Installation
14
41
 
15
- ### For Expo Managed Projects
42
+ ### Expo projects
16
43
 
17
44
  ```bash
18
45
  expo install react-native-asleep
19
46
  ```
20
47
 
21
- ### For Bare React Native Projects
22
-
23
- This library uses the Expo Modules API. Bare RN projects need Expo modules installed once; after that, autolinking handles the rest — no `react-native.config.js` or manual native linking.
48
+ This package contains native modules, so create a new development or store build after installing or upgrading it. It does not run in Expo Go and cannot be upgraded through an OTA update alone.
24
49
 
25
- 1. **Install Expo modules** (skip if already installed):
50
+ ### Bare React Native projects
26
51
 
27
- ```bash
28
- npx install-expo-modules@latest
29
- ```
52
+ This library uses the Expo Modules API. Install Expo modules once if the app does not already use them:
30
53
 
31
- It prompts `Install the Expo CLI integration? (Y/n)` — either answer wires the bare modules. See the [Expo bare guide](https://docs.expo.dev/bare/installing-expo-modules/) for details.
32
-
33
- 2. **Install the package** (`npm install` / `pnpm add` / `yarn add`):
54
+ ```bash
55
+ npx install-expo-modules@latest
56
+ npm install react-native-asleep
57
+ ```
34
58
 
35
- ```bash
36
- npm install react-native-asleep zustand
37
- ```
59
+ Then install iOS pods:
38
60
 
39
- `zustand` is a peer dependency through v1.x and will be removed in v2.0.
61
+ ```bash
62
+ cd ios
63
+ bundle install
64
+ bundle exec pod install
65
+ ```
40
66
 
41
- 3. **iOS**: in `ios/`, run `bundle install` (once) then `bundle exec pod install`. The project's `Gemfile` avoids host Ruby/CocoaPods conflicts. **Android**: no extra step.
67
+ Android needs no additional linking step.
42
68
 
43
- #### Static framework note
69
+ #### Static frameworks
44
70
 
45
- The iOS podspec sets `s.static_framework = true`. **Do not add `use_frameworks!` to your `Podfile`.** If your project already requires it, pin to static linkage:
71
+ The iOS pod is a static framework. Do not add `use_frameworks!` only for this package. If the app already requires it, use static linkage:
46
72
 
47
73
  ```ruby
48
74
  use_frameworks! :linkage => :static
49
75
  ```
50
76
 
51
- `:linkage => :dynamic` is known to break Expo SDK 55 builds (see [expo/expo#44487](https://github.com/expo/expo/issues/44487), [#41556](https://github.com/expo/expo/issues/41556)).
77
+ Dynamic linkage is known to break Expo SDK 55 builds; see [expo/expo#44487](https://github.com/expo/expo/issues/44487) and [expo/expo#41556](https://github.com/expo/expo/issues/41556).
52
78
 
53
- #### Monorepo / workspace projects
79
+ #### Monorepos and workspaces
54
80
 
55
- If `react-native-asleep` is hoisted to a parent `node_modules`, configure autolinking in your app's `package.json`:
81
+ If `react-native-asleep` is hoisted to a parent `node_modules`, configure Expo autolinking in the app's `package.json`:
56
82
 
57
83
  ```json
58
84
  {
@@ -64,42 +90,22 @@ If `react-native-asleep` is hoisted to a parent `node_modules`, configure autoli
64
90
  }
65
91
  ```
66
92
 
67
- #### Reference configuration
68
-
69
- The [example app](./example) is the reference setup. Adjacent versions are expected to work but aren't verified.
70
-
71
- | Component | Version |
72
- | --------------------------- | -------- |
73
- | React Native | 0.79.2 |
74
- | Expo | 53 |
75
- | React | 19.0.0 |
76
- | iOS deployment target | 14.0 |
77
- | Android `minSdkVersion` | 24 |
78
- | Android `compileSdkVersion` | 34 |
79
- | Android `targetSdkVersion` | 34 |
80
-
81
- ## Setup
93
+ ## Native configuration
82
94
 
83
- ### 1. Get API Key
95
+ Create an API key in the [Asleep Dashboard](https://dashboard.asleep.ai).
84
96
 
85
- 1. Visit [Asleep Dashboard](https://dashboard.asleep.ai)
86
- 2. Create an account and generate your API key
87
- 3. Note your API key for configuration
97
+ ### iOS
88
98
 
89
- ### 2. Permissions
99
+ Your app must declare microphone usage and background audio.
90
100
 
91
- #### iOS — declared by your app
92
-
93
- Add the microphone usage description and audio background mode.
94
-
95
- **For Expo Managed Projects (app.json):**
101
+ For Expo projects:
96
102
 
97
103
  ```json
98
104
  {
99
105
  "expo": {
100
106
  "ios": {
101
107
  "infoPlist": {
102
- "NSMicrophoneUsageDescription": "This app needs microphone access for sleep tracking",
108
+ "NSMicrophoneUsageDescription": "This app uses the microphone for sleep tracking.",
103
109
  "UIBackgroundModes": ["audio"]
104
110
  }
105
111
  }
@@ -107,152 +113,301 @@ Add the microphone usage description and audio background mode.
107
113
  }
108
114
  ```
109
115
 
110
- **For Bare React Native Projects (ios/YourApp/Info.plist):**
116
+ For bare React Native projects, add the equivalent entries to the app's `Info.plist`:
111
117
 
112
118
  ```xml
113
119
  <key>NSMicrophoneUsageDescription</key>
114
- <string>This app needs microphone access for sleep tracking</string>
120
+ <string>This app uses the microphone for sleep tracking.</string>
115
121
  <key>UIBackgroundModes</key>
116
122
  <array>
117
123
  <string>audio</string>
118
124
  </array>
119
125
  ```
120
126
 
121
- #### Android — declared by the library
127
+ ### Android
122
128
 
123
- The library declares its own permissions; the manifest merger combines them into your app. No `<uses-permission>` entries are needed in your `AndroidManifest.xml`. For reference, the library declares:
124
-
125
- ```xml
126
- <uses-permission android:name="android.permission.INTERNET" />
127
- <uses-permission android:name="android.permission.RECORD_AUDIO" />
128
- <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
129
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
130
- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
131
- <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
132
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
133
- <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
134
- ```
129
+ The library declares its required permissions and foreground service in its manifest. The manifest merger adds them to the app, so do not duplicate them only for this SDK.
135
130
 
136
- `RECORD_AUDIO` and `POST_NOTIFICATIONS` are runtime permissions — request them via `useAsleep().requestRequiredPermissions()` (or `PermissionsAndroid`) before starting tracking.
131
+ `RECORD_AUDIO` is required at runtime. On Android 13 and later, `requestRequiredPermissions()` also requests `POST_NOTIFICATIONS` so the foreground-service notification can remain visible, but notification denial does not make its return value `false`.
137
132
 
138
133
  ## Quick Start
139
134
 
135
+ The required startup order is:
136
+
137
+ ```text
138
+ check for an existing Android tracking service
139
+ → initialize the SDK configuration
140
+ → check battery optimization
141
+ → request permissions from a user action
142
+ → start tracking
143
+ ```
144
+
145
+ Always call `initAsleepConfig()` after `checkAndRestoreTracking()`, including when an Android service session was restored. On iOS, the restoration check is a required cross-platform prerequisite but reports no persistent service.
146
+
140
147
  ```tsx
141
- import { useEffect } from "react";
142
- import { Button, View } from "react-native";
143
- import { useAsleep } from "react-native-asleep";
144
-
145
- function SleepTracker() {
146
- const {
147
- isTracking,
148
- sessionId,
149
- error,
150
- initAsleepConfig,
151
- checkAndRestoreTracking,
152
- checkBatteryOptimization,
153
- requestRequiredPermissions,
154
- startTracking,
155
- stopTracking,
156
- } = useAsleep();
157
-
158
- // Required order before startTracking: configure -> restore any in-progress session -> battery check
148
+ import { useEffect, useRef, useState } from "react";
149
+ import { Button, Platform, Text, View } from "react-native";
150
+ import { AsleepError, useAsleep } from "react-native-asleep";
151
+
152
+ export function SleepTracker() {
153
+ const asleep = useAsleep();
154
+ const hasBootstrapped = useRef(false);
155
+ const [isReady, setIsReady] = useState(false);
156
+ const [bootstrapMessage, setBootstrapMessage] = useState<string | null>(null);
157
+
159
158
  useEffect(() => {
160
- (async () => {
161
- await initAsleepConfig({ apiKey: "YOUR_API_KEY" });
162
- await checkAndRestoreTracking();
163
- await checkBatteryOptimization();
164
- })();
165
- }, []);
166
-
167
- const handleStart = async () => {
168
- await requestRequiredPermissions();
169
- await startTracking({
170
- android: { notification: { title: "Sleep tracking", text: "Recording..." } },
159
+ if (hasBootstrapped.current) return;
160
+ hasBootstrapped.current = true;
161
+
162
+ async function bootstrap() {
163
+ await asleep.checkAndRestoreTracking();
164
+
165
+ const config = { apiKey: "YOUR_API_KEY" };
166
+ if (Platform.OS === "ios") {
167
+ let removeJoined = () => {};
168
+ let removeFailed = () => {};
169
+ const configurationFinished = new Promise<void>((resolve, reject) => {
170
+ removeJoined = asleep.addEventListener("onUserJoined", () => resolve());
171
+ removeFailed = asleep.addEventListener("onUserJoinFailed", (failure) => {
172
+ reject(
173
+ new AsleepError(
174
+ "USER_JOIN_FAILED",
175
+ failure.detail ?? failure.error ?? "User join failed.",
176
+ {
177
+ sdkCode: failure.sdkCode,
178
+ caseName: failure.caseName,
179
+ cause: failure,
180
+ },
181
+ ),
182
+ );
183
+ });
184
+ });
185
+
186
+ try {
187
+ await Promise.all([
188
+ asleep.initAsleepConfig(config),
189
+ configurationFinished,
190
+ ]);
191
+ } finally {
192
+ removeJoined();
193
+ removeFailed();
194
+ }
195
+ } else {
196
+ await asleep.initAsleepConfig(config);
197
+ }
198
+
199
+ await asleep.checkBatteryOptimization();
200
+ setIsReady(true);
201
+ }
202
+
203
+ void bootstrap().catch((cause: unknown) => {
204
+ setBootstrapMessage(cause instanceof Error ? cause.message : String(cause));
171
205
  });
172
- };
206
+ }, [
207
+ asleep.checkAndRestoreTracking,
208
+ asleep.initAsleepConfig,
209
+ asleep.addEventListener,
210
+ asleep.checkBatteryOptimization,
211
+ ]);
212
+
213
+ async function start() {
214
+ try {
215
+ if (!(await asleep.hasRequiredPermissions())) {
216
+ const granted = await asleep.requestRequiredPermissions();
217
+ if (!granted) return;
218
+ }
219
+
220
+ const battery = await asleep.checkBatteryOptimization();
221
+ if (!battery.exempted) {
222
+ await asleep.requestBatteryOptimizationExemption();
223
+ return; // Check again after the user returns from Android settings.
224
+ }
225
+
226
+ await asleep.startTracking({
227
+ android: {
228
+ notification: {
229
+ title: "Sleep tracking",
230
+ text: "Sleep analysis is running.",
231
+ },
232
+ },
233
+ });
234
+ } catch (cause: unknown) {
235
+ if (!(cause instanceof AsleepError)) throw cause;
236
+ // The same AsleepError is also available reactively as asleep.error.
237
+ }
238
+ }
239
+
240
+ async function stop() {
241
+ try {
242
+ await asleep.stopTracking();
243
+ } catch (cause: unknown) {
244
+ if (!(cause instanceof AsleepError)) throw cause;
245
+ }
246
+ }
247
+
248
+ const shouldStop =
249
+ asleep.isTracking || asleep.error?.category === "recordingDead";
173
250
 
174
251
  return (
175
252
  <View>
176
- <Button title={isTracking ? "Stop" : "Start"} onPress={isTracking ? stopTracking : handleStart} />
253
+ <Text>Status: {asleep.status}</Text>
254
+ {bootstrapMessage ? <Text>{bootstrapMessage}</Text> : null}
255
+ {asleep.error ? <Text>{asleep.error.message}</Text> : null}
256
+ <Button
257
+ title={shouldStop ? "Stop tracking" : "Start tracking"}
258
+ disabled={!isReady}
259
+ onPress={shouldStop ? stop : start}
260
+ />
177
261
  </View>
178
262
  );
179
263
  }
180
264
  ```
181
265
 
182
- For ODA (On-Device Analysis) mode, call `setup()` instead of `initAsleepConfig()`. See [`example/App.tsx`](./example/App.tsx) for the full flow including report fetch and event-driven state.
266
+ Call `requestRequiredPermissions()` from a user-driven interaction. `startTracking()` checks permission but never opens a permission dialog. On Android, return from the battery settings screen and call `checkBatteryOptimization()` again before retrying.
267
+
268
+ On iOS, `initAsleepConfig()` starts asynchronous user configuration but its bridge call can return before the native managers are ready. Register the user events before calling it and wait for `onUserJoined` or `onUserJoinFailed`, as shown above. Android resolves `initAsleepConfig()` after configuration; do not wait for `onUserJoined` there because a restored-service fast path does not emit it.
183
269
 
184
- ## API surface
270
+ The `recordingDead` category is another deliberate exception: `isTracking` is `false`, but the native session remains open, so the action must still call `stopTracking()` before starting a new session.
185
271
 
186
- The library exports a single React hook plus types:
272
+ For ODA (On-Device Analysis), `setup()` is the configuration entry point for a new ODA session. This Quick Start documents service mode; `setup()` cannot run while a restored session is tracking.
273
+
274
+ ## Core API
187
275
 
188
276
  ```ts
189
- import { useAsleep, type AsleepReport, type AsleepSession, type AsleepAverageReport } from "react-native-asleep";
277
+ import {
278
+ Asleep,
279
+ AsleepError,
280
+ useAsleep,
281
+ type AsleepReport,
282
+ type AsleepSession,
283
+ type TrackingStatus,
284
+ } from "react-native-asleep";
190
285
  ```
191
286
 
192
- `useAsleep()` returns reactive state (`isTracking`, `sessionId`, `error`, `analysisResult`, ...) and bound actions (`startTracking`, `stopTracking`, `getReport`, `getReportList`, `requestAnalysis`, ...). Hover the return type in your editor for the full surface; the type definitions in [`src/Asleep.types.ts`](./src/Asleep.types.ts) are the source of truth and stay in sync with the native modules.
287
+ ### Credentials
288
+
289
+ `setup()` and `initAsleepConfig()` accept exactly one credential form, typed as `AsleepCredentials`:
193
290
 
194
- On iOS, `isRecoveryRequired` becomes `true` when recording cannot resume while the app is in the background. After the app returns to the foreground, call `resumeTracking()`. The flag clears only after the next successful audio upload. `resumeTracking()` is iOS-only and rejects with `UNSUPPORTED_PLATFORM` on Android.
291
+ ```ts
292
+ const asleep = useAsleep();
293
+
294
+ await asleep.initAsleepConfig({ apiKey: "YOUR_API_KEY", userId });
295
+ // or token authentication
296
+ await asleep.initAsleepConfig({ appId: "YOUR_APP_ID", appSecret: "YOUR_APP_SECRET", userId });
297
+ ```
195
298
 
196
- ## Tracking lifecycle and platform compensations
299
+ Mixing `apiKey` with `appId`/`appSecret` is a type error. At runtime, passing neither form, both forms, an incomplete pair, or an empty string rejects with `AsleepError` code `INVALID_ARGUMENT` before any native call. Keep the secret out of source control like the API key.
197
300
 
198
- The library handles a number of platform quirks internally so JS sees a consistent event model:
301
+ ### `useAsleep()`
199
302
 
200
- - iOS 3.2.1 `closeSessionSilently()` on 403/429 tears down a session without firing `didClose` — the wrapper detects terminal error codes and resets `isTracking` / `isAnalyzing` itself.
201
- - Android SDK 3.2.x emits both `onFail` and `onFinish` for fatal codes — the wrapper suppresses the spurious `onTrackingClosed` so JS doesn't misread a fatal error as a clean close.
202
- - iOS interruption recovery may emit duplicate `didResume` events — the wrapper deduplicates while still clearing `error`.
203
- - iOS audio initialization failure stops recording without closing the native session — stop and restart the session; `resumeTracking()` cannot recover it.
303
+ The primary React API. It attaches the ref-counted native listeners while mounted and returns state plus actions from the shared SDK store.
204
304
 
205
- See [AGENTS.md](./AGENTS.md#native-behavior-compensations) for the full table including upstream SDK versions and rationale.
305
+ Important state:
206
306
 
207
- ## Error classification
307
+ | Field | Meaning |
308
+ |---|---|
309
+ | `status` | `"idle"`, `"tracking"`, `"paused"`, or `"recoveryRequired"` |
310
+ | `isTracking` | `true` for every status except `"idle"` |
311
+ | `isTrackingPaused` | The native session is temporarily interrupted |
312
+ | `isRecoveryRequired` | iOS needs an explicit foreground `resumeTracking()` |
313
+ | `isSetupComplete` | SDK configuration completed |
314
+ | `sessionId`, `userId` | Current native identifiers |
315
+ | `analysisResult`, `isAnalyzing` | Latest analysis event and request state |
316
+ | `error` | The latest `AsleepError`, or `null` |
208
317
 
209
- `useAsleep().errorInfo` is a structured view of the last tracking failure. Its `category` field is the library's objective verdict on recoverability; the app decides what severity to log at:
318
+ Important actions:
210
319
 
211
- | `category` | Meaning | Suggested app-side severity |
212
- |---|---|---|
213
- | `terminal` | Native session is gone; no `onTrackingClosed` will follow. Start a new session. | error |
214
- | `recordingDead` | Recorder torn down but the session is still open; `stopTracking()` then start again. | error |
215
- | `recoveryRequired` | Tracking is alive; call `resumeTracking()` in the foreground (`isRecoveryRequired` is also set). | warning |
216
- | `transient` | The native session survived (e.g. one upload window failed after internal retries); later uploads continue. | warning |
217
- | `unknown` | Unclassified code — do not assume it is benign. | error |
320
+ | Area | Actions |
321
+ |---|---|
322
+ | Configuration and restore | `setup`, `initAsleepConfig`, `checkAndRestoreTracking` |
323
+ | Prerequisites | `checkBatteryOptimization`, `requestBatteryOptimizationExemption`, `hasRequiredPermissions`, `requestRequiredPermissions` |
324
+ | Tracking | `startTracking`, `stopTracking`, `resumeTracking` |
325
+ | Reports | `getReport`, `getReportList`, `getAverageReport`, `deleteSession` |
326
+ | Analysis | `requestAnalysis` |
327
+ | Utilities | `addEventListener`, `enableLog`, `clearError` |
328
+
329
+ ### `Asleep`
330
+
331
+ Use the imperative escape hatch where React hooks are unavailable:
332
+
333
+ ```ts
334
+ import { Asleep } from "react-native-asleep";
335
+
336
+ const releaseListeners = Asleep.initialize();
337
+ const unsubscribe = Asleep.subscribe((state) => {
338
+ console.log(state.status, state.error?.code);
339
+ });
340
+
341
+ console.log(Asleep.getState().status);
342
+
343
+ unsubscribe();
344
+ releaseListeners();
345
+ ```
346
+
347
+ `Asleep.initialize()` is ref-counted and must be paired with its returned cleanup function. Importing the package alone does not attach native listeners.
348
+
349
+ ### Errors
350
+
351
+ Every failed action throws `AsleepError`; the same error is stored in `useAsleep().error` when applicable.
218
352
 
219
353
  ```ts
220
- const { errorInfo } = useAsleep();
221
-
222
- useEffect(() => {
223
- if (!errorInfo) return;
224
- if (errorInfo.category === "recoveryRequired" || errorInfo.category === "transient") {
225
- analytics.track("asleep_recoverable_error", errorInfo); // visibility without paging
226
- } else {
227
- Sentry.captureException(new Error(`[Asleep] ${errorInfo.code}`), { extra: errorInfo });
354
+ try {
355
+ await asleep.startTracking();
356
+ } catch (cause: unknown) {
357
+ if (cause instanceof AsleepError) {
358
+ console.log(cause.code, cause.category, cause.sdkCode);
228
359
  }
229
- }, [errorInfo]);
360
+ }
230
361
  ```
231
362
 
232
- `errorInfo.sdkCode` carries the numeric error code documented by the native Asleep SDKs (both platforms). The legacy `errorCode` event-payload field is deprecated: on iOS it holds a Swift enum ordinal from NSError bridging, not the documented code.
363
+ Use `code` for stable machine branching and `message` for display. Runtime tracking failures can also have one of these recovery categories:
364
+
365
+ | Category | Meaning |
366
+ |---|---|
367
+ | `terminal` | The native session is already gone |
368
+ | `recordingDead` | Recording stopped but the native session remains open |
369
+ | `recoveryRequired` | The live iOS session needs a foreground resume |
370
+ | `transient` | The native session survived the failure |
371
+ | `unknown` | The failure is not classified; do not assume it is recoverable |
372
+
373
+ See the integration guide for the required action for each category.
374
+
375
+ ## Production integration
376
+
377
+ The README covers installation and the first successful tracking flow. Before shipping, read the [Integration Guide](./docs/INTEGRATION.md) for:
233
378
 
234
- ## Best practices
379
+ - cold-start restoration and listener ownership
380
+ - app-owned versus SDK-owned state
381
+ - Android foreground-service and battery behavior
382
+ - iOS interruption recovery
383
+ - recovery-category handling
384
+ - analysis and report timing
385
+ - real-device release checks
235
386
 
236
- - **Permission flow**: call `requestRequiredPermissions()` *before* `startTracking()`. As of v1.0.18 the Android native module rejects `startTracking` with `PERMISSION_REQUIRED` when `RECORD_AUDIO` / `FOREGROUND_SERVICE_MICROPHONE` aren't granted.
237
- - **Battery optimization (Android, required)**: long sessions get killed without an exemption. Call `checkBatteryOptimization()` before `startTracking()`; if not exempted, call `requestBatteryOptimizationExemption()` and follow the system prompt. iOS's no-op call keeps cross-platform code uniform.
238
- - **Error handling**: gate log severity on `useAsleep().errorInfo?.category` (see [Error classification](#error-classification)) and switch on `errorInfo.code` for category-specific UI rather than parsing `message` substrings.
387
+ ## Migrating from 1.x
239
388
 
240
- ## Troubleshooting
389
+ v2 removes the parallel and mutable v1 surfaces:
241
390
 
242
- - **`PERMISSION_REQUIRED` from `startTracking`**: call `requestRequiredPermissions()` first, then retry.
243
- - **`MISSING_PREREQUISITE` from `startTracking`**: call `checkAndRestoreTracking()` and `checkBatteryOptimization()` before `startTracking()`.
244
- - **Tracking ends unexpectedly on Android**: battery optimization is on; call `checkBatteryOptimization()` and follow the prompt.
245
- - **Network errors**: verify API key and connectivity.
391
+ | 1.x | v2 |
392
+ |---|---|
393
+ | `error: string \| null` and `errorInfo` | One `AsleepError`; use `message`, `code`, `category`, and `sdkCode` |
394
+ | Report failures returned `null` or `[]` | Report APIs throw `AsleepError`; an empty report list remains a valid result |
395
+ | Public state setters and raw store | Native events and SDK actions are the only writers |
396
+ | `getTrackingDurationMinutes()` | Store a wall-clock start time in the app |
397
+ | `requestMicrophonePermission()` | `requestRequiredPermissions()` |
398
+ | `startTracking()` requested permission | Check and request permission explicitly before starting |
399
+ | Default export, `AsleepSDK`, and `Asleep` class | `useAsleep()` and the named thin `Asleep` escape hatch |
400
+ | Required `zustand` dependency | No external state-library dependency |
246
401
 
247
- Enable debug logs with `useAsleep().enableLog(true)`.
402
+ Android 13 and later still request notification permission, but `requestRequiredPermissions()` now returns the microphone-side result that determines whether tracking can start. Pin the new version, update all imports and error branches, and test cold-start permissions before release.
248
403
 
249
404
  ## Example app
250
405
 
251
- See [`example/`](./example) for a full implementation.
406
+ See the [example app on GitHub](https://github.com/asleep-ai/asleep-sdk-react-native/tree/main/example) for a runnable implementation.
252
407
 
253
408
  ## License
254
409
 
255
- MIT.
410
+ See [LICENSE.md](./LICENSE.md).
256
411
 
257
412
  ## Support
258
413
 
@@ -73,7 +73,7 @@ repositories {
73
73
  }
74
74
 
75
75
  dependencies {
76
- implementation('ai.asleep:asleepsdk:3.2.1') {
76
+ implementation('ai.asleep:asleepsdk:3.3.1') {
77
77
  exclude group: 'com.android.support'
78
78
  }
79
79