react-native-asleep 2.0.0 → 2.1.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.ko.md +71 -41
- package/README.md +72 -36
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +174 -10
- package/build/Asleep.types.d.ts +60 -0
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +6 -2
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +192 -15
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js.map +1 -1
- package/docs/INTEGRATION.ko.md +72 -40
- package/docs/INTEGRATION.md +73 -41
- package/ios/Asleep.podspec +1 -1
- package/ios/AsleepModule.swift +282 -12
- package/package.json +1 -1
- package/src/Asleep.types.ts +67 -0
- package/src/AsleepStore.ts +237 -18
- package/src/index.ts +7 -0
package/docs/INTEGRATION.md
CHANGED
|
@@ -12,7 +12,7 @@ The examples use service-based sleep tracking through `initAsleepConfig()`. ODA
|
|
|
12
12
|
flowchart LR
|
|
13
13
|
A["App starts"] --> B["Mount useAsleep or initialize listeners"]
|
|
14
14
|
B --> C["checkAndRestoreTracking()"]
|
|
15
|
-
C --> D["initAsleepConfig()
|
|
15
|
+
C --> D["await initAsleepConfig()"]
|
|
16
16
|
D --> E["checkBatteryOptimization()"]
|
|
17
17
|
E --> F{"Android service restored?"}
|
|
18
18
|
F -- "Yes" --> G["Render restored SDK state"]
|
|
@@ -87,9 +87,8 @@ releaseListeners();
|
|
|
87
87
|
Run this sequence once from the app-level integration owner:
|
|
88
88
|
|
|
89
89
|
```tsx
|
|
90
|
-
import { Platform } from "react-native";
|
|
91
90
|
import { useCallback } from "react";
|
|
92
|
-
import {
|
|
91
|
+
import { useAsleep } from "react-native-asleep";
|
|
93
92
|
|
|
94
93
|
export function useSleepTrackingBootstrap(stableUserId?: string) {
|
|
95
94
|
const asleep = useAsleep();
|
|
@@ -102,41 +101,7 @@ export function useSleepTrackingBootstrap(stableUserId?: string) {
|
|
|
102
101
|
userId: stableUserId,
|
|
103
102
|
};
|
|
104
103
|
|
|
105
|
-
|
|
106
|
-
let removeJoined = () => {};
|
|
107
|
-
let removeFailed = () => {};
|
|
108
|
-
const configurationFinished = new Promise<void>((resolve, reject) => {
|
|
109
|
-
removeJoined = asleep.addEventListener("onUserJoined", () => resolve());
|
|
110
|
-
removeFailed = asleep.addEventListener(
|
|
111
|
-
"onUserJoinFailed",
|
|
112
|
-
(failure) => {
|
|
113
|
-
reject(
|
|
114
|
-
new AsleepError(
|
|
115
|
-
"USER_JOIN_FAILED",
|
|
116
|
-
failure.detail ?? failure.error ?? "User join failed.",
|
|
117
|
-
{
|
|
118
|
-
sdkCode: failure.sdkCode,
|
|
119
|
-
caseName: failure.caseName,
|
|
120
|
-
cause: failure,
|
|
121
|
-
},
|
|
122
|
-
),
|
|
123
|
-
);
|
|
124
|
-
},
|
|
125
|
-
);
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
try {
|
|
129
|
-
await Promise.all([
|
|
130
|
-
asleep.initAsleepConfig(config),
|
|
131
|
-
configurationFinished,
|
|
132
|
-
]);
|
|
133
|
-
} finally {
|
|
134
|
-
removeJoined();
|
|
135
|
-
removeFailed();
|
|
136
|
-
}
|
|
137
|
-
} else {
|
|
138
|
-
await asleep.initAsleepConfig(config);
|
|
139
|
-
}
|
|
104
|
+
await asleep.initAsleepConfig(config);
|
|
140
105
|
|
|
141
106
|
const battery = await asleep.checkBatteryOptimization();
|
|
142
107
|
|
|
@@ -147,7 +112,6 @@ export function useSleepTrackingBootstrap(stableUserId?: string) {
|
|
|
147
112
|
}, [
|
|
148
113
|
asleep.checkAndRestoreTracking,
|
|
149
114
|
asleep.initAsleepConfig,
|
|
150
|
-
asleep.addEventListener,
|
|
151
115
|
asleep.checkBatteryOptimization,
|
|
152
116
|
stableUserId,
|
|
153
117
|
]);
|
|
@@ -160,8 +124,8 @@ export function useSleepTrackingBootstrap(stableUserId?: string) {
|
|
|
160
124
|
|
|
161
125
|
- `checkAndRestoreTracking()` asks Android native code whether tracking survived the JavaScript process and reconnects the service when needed. On iOS, the method is a required cross-platform prerequisite but returns `{ hasActiveSession: false }`; iOS has no persistent service to reconnect.
|
|
162
126
|
- `initAsleepConfig()` remains required after that check. A restored session does not mean the current JavaScript process has configured the SDK and report APIs.
|
|
163
|
-
-
|
|
164
|
-
-
|
|
127
|
+
- `await initAsleepConfig()` resolves after the native user join has created the tracking and report managers, and rejects when the join fails, on both platforms. Await the action itself rather than `onUserJoined`: the Android restored-service fast path resolves without emitting that event.
|
|
128
|
+
- A second `initAsleepConfig()` while one is in progress rejects with `OPERATION_IN_PROGRESS`. When switching users, let the previous call settle before starting the next. The native SDKs ignore an init, with no callback, while tracking is starting or stopping or while a previous init is still waiting for its response; on iOS the call then rejects with `INITIALIZATION_FAILED` after 60 seconds (a late SDK answer to it is applied and emits `onUserJoined`/`onUserJoinFailed` only if no newer `initAsleepConfig()` has started; otherwise it is ignored and per-user calls stay blocked until the next successful init), and a new call made while the SDK is still busy with the previous one can time out the same way; on Android it stays pending. Avoid calling `initAsleepConfig()` during a start or stop.
|
|
165
129
|
- `checkBatteryOptimization()` marks the required prerequisite as checked. On iOS it resolves with `{ exempted: true, platform: "ios" }`.
|
|
166
130
|
- `startTracking()` rejects with `MISSING_PREREQUISITE` if restoration or the battery check has not run.
|
|
167
131
|
|
|
@@ -179,6 +143,52 @@ If the app supplies `userId`, persist the stable identifier in app storage and r
|
|
|
179
143
|
|
|
180
144
|
Do not reconfigure a live session with a different product identity. Define any identity migration policy outside the SDK.
|
|
181
145
|
|
|
146
|
+
### User metadata
|
|
147
|
+
|
|
148
|
+
`saveUserMetadata(metadata)` and `fetchUserMetadata()` read and write optional profile data (birth date, gender, height, weight) on the configured user. Call them only after the most recent `initAsleepConfig()` has resolved. Earlier calls, calls while a re-init is in progress, and calls after a failed re-init reject with `MISSING_PREREQUISITE`; the previous user's config is never reused. `setup()` also invalidates it, so call `initAsleepConfig()` again after `setup()`.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
await asleep.saveUserMetadata({ birthYear: 1990, birthMonth: 5, birthDay: 17, gender: "female" });
|
|
152
|
+
const metadata = await asleep.fetchUserMetadata(); // null when nothing was saved
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The wrapper validates the native ranges before any bridge call and rejects with `INVALID_ARGUMENT`; see the README for the ranges. The server can still reject a value (for example a future `birthYear`) with `INVALID_ARGUMENT` and `sdkCode` 27400. Other failures arrive as `SAVE_USER_METADATA_FAILED` (`sdkCode` 27000) or `FETCH_USER_METADATA_FAILED` (`sdkCode` 27100). Both native SDKs truncate `height` and `weight` to one decimal place, so a fetched value can differ from the saved input. Whether and when to collect this data, consent, and editing UI are app-owned.
|
|
156
|
+
|
|
157
|
+
### Device registration
|
|
158
|
+
|
|
159
|
+
Hardware products register the device with Asleep by passing `productInfo` to `setup()` (`POST customer/v1/products`); `initAsleepConfig()` does not accept it. Register before `startTracking()`: only sessions created after a successful registration are bound to the product. Behavior below is as of iOS SDK 3.3.3 and Android SDK 3.3.1.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
await asleep.setup({
|
|
163
|
+
appId: "YOUR_APP_ID",
|
|
164
|
+
appSecret: "YOUR_APP_SECRET",
|
|
165
|
+
productInfo: { model: "YOUR_PRODUCT_MODEL", identifierType: "mac_address", identifierValue: deviceMacAddress },
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
| Field | Rule |
|
|
170
|
+
|---|---|
|
|
171
|
+
| `model` | 1-100 characters, not blank |
|
|
172
|
+
| `identifierType` | `"serial"` or `"mac_address"` |
|
|
173
|
+
| `identifierValue` | 1-255 characters, not blank |
|
|
174
|
+
|
|
175
|
+
Values are sent untrimmed. Invalid values and unknown fields reject with `INVALID_ARGUMENT` before any native call; without `productInfo`, `setup()` behaves as before and nothing is registered.
|
|
176
|
+
|
|
177
|
+
- **Idempotent per identifier.** The same `identifierType` and `identifierValue` return the existing product credential. A device that already holds a credential for the same credentials owner and the same `productInfo` makes no network call, so passing the same value on every launch is safe.
|
|
178
|
+
- **The first `model` wins.** The server keeps the model of the first registration for an identifier; the SDK cannot change it.
|
|
179
|
+
- **A new identifier is a new product.** It may be billable. Use real device identifiers and never send placeholder or test values with production credentials.
|
|
180
|
+
- **Changing credentials re-registers.** A different `apiKey` or `appId` drops the stored credential, and the next `setup()` with `productInfo` registers again.
|
|
181
|
+
- **Registration blocks setup.** On failure the whole `setup()` fails with code `SETUP_FAILED` and no `onSetupDidComplete`, and the native SDK is reset so `setup()` can be called again:
|
|
182
|
+
|
|
183
|
+
| `error.sdkCode` | Meaning | Suggested handling |
|
|
184
|
+
|---|---|---|
|
|
185
|
+
| 13400 | Rejected: a 4xx other than 429, or failed input checks | Do not retry unchanged; fix the input or the contract |
|
|
186
|
+
| 13000 | Network failure, 5xx, 429, or an unreadable response. The SDK already retried network failures, 5xx and 429 after 2, 4 and 8 seconds | Retry later with a bounded policy |
|
|
187
|
+
|
|
188
|
+
Offline, a 13000 failure can take about 1.5-3 minutes to arrive; keep tracking controls disabled until setup finishes.
|
|
189
|
+
|
|
190
|
+
On Android, `setup()` resolves after registration and setup complete, and rejects with the failure. On iOS, `setup()` returns once the native call starts and `isSetupComplete` can turn `true` before registration finishes. Register `onSetupDidComplete` and `onSetupDidFail` before calling `setup()` and wait for one of them. Do not call `setup()` again before it arrives: the native SDK ignores a second `setup()` while one is running and sends no callback.
|
|
191
|
+
|
|
182
192
|
## 4. Check prerequisites and start
|
|
183
193
|
|
|
184
194
|
Permission prompts must originate from a user-driven interaction:
|
|
@@ -360,6 +370,8 @@ Forward the `AsleepError` itself to observability so `cause`, `sdkCode`, and `ca
|
|
|
360
370
|
|
|
361
371
|
`stopTracking()` closes the active session and marks the public state closed. The final `sessionId` may also arrive through the native close event. Product cleanup—alarms, app timers, cloud state, and navigation—belongs to the app and should occur only after the SDK stop succeeds or a terminal event proves the session is gone.
|
|
362
372
|
|
|
373
|
+
To analyze only part of the recording, pass `stopTracking({ analysisRange: { start, end } })`. The wrapper rejects `INVALID_ARGUMENT` before any native call unless both bounds are valid `Date` objects and `start` is at least one whole second before `end`; the native SDKs would otherwise drop the range and report the failure only after the stop promise resolved. The rest of the stop flow and state handling are identical to a plain stop. A range that passes this check can still be ignored by the server, which then analyzes the full session without notifying the app. Keep the range inside the measured session: a range that starts before the native session start was verified on devices to produce no analyzed data (`missing_data_ratio` 1.0) and later `reanalyze()` then fails with 30410, so do not use an app-side timestamp taken before `startTracking()` resolved. Which window to send (for example, from an in-bed time the user confirmed) is app policy.
|
|
374
|
+
|
|
363
375
|
Report generation may lag behind session close. The wrapper produces `REPORT_NOT_FOUND` when native code resolves without a report payload, but platform SDK failures can arrive under another `AsleepError.code` such as Android `REPORT_ERROR`. Do not blanket-retry every report failure. Until all native not-found codes are normalized by the wrapper, choose retry behavior only for error cases the app has explicitly verified; keep network, authentication, and other failures visible.
|
|
364
376
|
|
|
365
377
|
Report APIs:
|
|
@@ -370,9 +382,29 @@ Report APIs:
|
|
|
370
382
|
| `getReportList(fromDate, toDate)` | `AsleepSession[]`; an empty array is a valid result |
|
|
371
383
|
| `getAverageReport(fromDate, toDate)` | `AsleepAverageReport`; may throw `REPORT_NOT_FOUND` when native resolves no payload |
|
|
372
384
|
| `deleteSession(sessionId)` | Deletes a session or throws |
|
|
385
|
+
| `reanalyze(sessionId, options?)` | Resolves when the server accepted a reanalysis request; poll `getReport()` for the result |
|
|
373
386
|
|
|
374
387
|
`getReportList()` currently returns at most 100 sessions and has no public pagination API. Pass dates as `YYYY-MM-DD`.
|
|
375
388
|
|
|
389
|
+
### Reanalysis
|
|
390
|
+
|
|
391
|
+
`reanalyze(sessionId)` re-runs server analysis for a closed session; `reanalyze(sessionId, { analysisRange: { start, end } })` restricts it to a window. The promise resolves when the server accepts the request, not when analysis is done. Poll `getReport(sessionId)` until `report.session.state` is `"COMPLETE"`; interval, timeout, and user messaging are app policy.
|
|
392
|
+
|
|
393
|
+
**Reanalyzing without a range replaces any earlier range on the server**, including one set through `stopTracking({ analysisRange })`: the whole session is analyzed and that result overwrites the trimmed one. To keep a window, pass it again.
|
|
394
|
+
|
|
395
|
+
Branch on `error.sdkCode` (code `REANALYZE_FAILED`):
|
|
396
|
+
|
|
397
|
+
| `sdkCode` | Meaning | Suggested handling |
|
|
398
|
+
|---|---|---|
|
|
399
|
+
| 30409 | A reanalysis is already in progress | Poll `getReport()` instead; if retrying, cap attempts with backoff, never loop unboundedly |
|
|
400
|
+
| 30422 | The session is still being tracked | Stop tracking first |
|
|
401
|
+
| 30404 / 30410 | Session not found / data retention expired | Do not retry |
|
|
402
|
+
| 30400 | Server rejected the range | Fix the input |
|
|
403
|
+
| 30401 / 30403 | Unauthorized / not allowed for this customer | Do not retry; check credentials and contract |
|
|
404
|
+
| 30000 / 30500 | Network or server failure | Retry with a bounded policy |
|
|
405
|
+
|
|
406
|
+
Input checks (empty `sessionId`, invalid range) reject with `INVALID_ARGUMENT` before any native call, and calls before the most recent `initAsleepConfig()` has resolved, while a re-init is in progress, or after it failed reject with `MISSING_PREREQUISITE`.
|
|
407
|
+
|
|
376
408
|
## 9. Consume analysis consistently
|
|
377
409
|
|
|
378
410
|
`requestAnalysis()` has different promise results:
|
package/ios/Asleep.podspec
CHANGED
package/ios/AsleepModule.swift
CHANGED
|
@@ -6,6 +6,19 @@ public class AsleepModule: Module {
|
|
|
6
6
|
private var reportManager: Asleep.Reports?
|
|
7
7
|
private(set) var config: Asleep.Config?
|
|
8
8
|
private var isLogEnabled = false
|
|
9
|
+
// Each initAsleepConfig call gets its own SDK delegate, so a callback can only
|
|
10
|
+
// settle the promise of the call that caused it. Only the most recent call's
|
|
11
|
+
// delegate may change the module's user config: an answer that arrives after a
|
|
12
|
+
// newer call started is ignored (per-user calls stay blocked until the app
|
|
13
|
+
// initializes again), so it can never re-activate a previous user. Only the
|
|
14
|
+
// current delegate is retained; replacing it releases the older one.
|
|
15
|
+
private let initLock = NSLock()
|
|
16
|
+
private var currentInit: InitCallDelegate?
|
|
17
|
+
// The SDK ignores initAsleepConfig without any callback while tracking is
|
|
18
|
+
// starting or stopping, or while a previous init is still waiting for its
|
|
19
|
+
// response (Asleep.swift isInitIgnoredWhileTrackingTransition, 3.3.3). Such a
|
|
20
|
+
// call is rejected after this timeout so it cannot block every later init.
|
|
21
|
+
fileprivate static let initResponseTimeout: TimeInterval = 60
|
|
9
22
|
|
|
10
23
|
public func definition() -> ModuleDefinition {
|
|
11
24
|
Name("Asleep")
|
|
@@ -27,28 +40,62 @@ public class AsleepModule: Module {
|
|
|
27
40
|
Events("onSetupInProgress")
|
|
28
41
|
Events("onAnalysisResult")
|
|
29
42
|
|
|
30
|
-
// JS validates that exactly one credential form is present: apiKey, or appId + appSecret
|
|
31
|
-
|
|
43
|
+
// JS validates that exactly one credential form is present: apiKey, or appId + appSecret,
|
|
44
|
+
// and validates productInfo. A nil productInfo skips product registration.
|
|
45
|
+
Function("setup") { (credentials: SetupCredentialsRecord, baseUrl: String?, callbackUrl: String?, service: String?, enableODA: Bool?, productInfo: ProductInfoRecord?) in
|
|
46
|
+
// setup() may switch credentials; drop the previous user config until the
|
|
47
|
+
// next userDidJoin so per-user calls never run as the previous user.
|
|
48
|
+
self.config = nil
|
|
49
|
+
self.reportManager = nil
|
|
50
|
+
var product: Asleep.ProductInfo?
|
|
51
|
+
if let productInfo = productInfo {
|
|
52
|
+
guard let identifierType = Asleep.ProductIdentifierType(rawValue: productInfo.identifierType) else {
|
|
53
|
+
throw Exception(name: "INVALID_ARGUMENT", description: "Unknown productInfo.identifierType: \(productInfo.identifierType)", code: "INVALID_ARGUMENT")
|
|
54
|
+
}
|
|
55
|
+
product = Asleep.ProductInfo(model: productInfo.model,
|
|
56
|
+
identifierType: identifierType,
|
|
57
|
+
identifierValue: productInfo.identifierValue)
|
|
58
|
+
}
|
|
32
59
|
Asleep.setLogger(self)
|
|
33
|
-
if let appId = appId, let appSecret = appSecret {
|
|
60
|
+
if let appId = credentials.appId, let appSecret = credentials.appSecret {
|
|
34
61
|
Asleep.setup(appId: appId,
|
|
35
62
|
appSecret: appSecret,
|
|
36
63
|
baseUrl: URL(string: baseUrl ?? ""),
|
|
37
64
|
callbackUrl: URL(string: callbackUrl ?? ""),
|
|
38
65
|
service: service,
|
|
39
66
|
enableODA: enableODA ?? false,
|
|
67
|
+
productInfo: product,
|
|
40
68
|
delegate: self)
|
|
41
69
|
} else {
|
|
42
|
-
Asleep.setup(apiKey: apiKey ?? "",
|
|
70
|
+
Asleep.setup(apiKey: credentials.apiKey ?? "",
|
|
43
71
|
baseUrl: URL(string: baseUrl ?? ""),
|
|
44
72
|
callbackUrl: URL(string: callbackUrl ?? ""),
|
|
45
73
|
service: service,
|
|
46
74
|
enableODA: enableODA ?? false,
|
|
75
|
+
productInfo: product,
|
|
47
76
|
delegate: self)
|
|
48
77
|
}
|
|
49
78
|
}
|
|
50
79
|
|
|
51
|
-
|
|
80
|
+
// Resolves with { userId } when this call's user join completes and rejects
|
|
81
|
+
// when it fails or the SDK never answers, matching Android. A call while
|
|
82
|
+
// another is still unsettled rejects without touching it.
|
|
83
|
+
AsyncFunction("initAsleepConfig") { (apiKey: String?, appId: String?, appSecret: String?, userId: String?, baseUrl: String?, callbackUrl: String?, promise: Promise) in
|
|
84
|
+
let callDelegate = InitCallDelegate(module: self, promise: promise)
|
|
85
|
+
self.initLock.lock()
|
|
86
|
+
if let current = self.currentInit, !current.isSettled {
|
|
87
|
+
self.initLock.unlock()
|
|
88
|
+
promise.reject("OPERATION_IN_PROGRESS", "initAsleepConfig is already in progress")
|
|
89
|
+
return
|
|
90
|
+
}
|
|
91
|
+
self.currentInit = callDelegate
|
|
92
|
+
self.initLock.unlock()
|
|
93
|
+
callDelegate.startTimeout()
|
|
94
|
+
// Drop the previous user's config until a join delivers the new one, so
|
|
95
|
+
// metadata and report calls never run as the previous user. The tracking
|
|
96
|
+
// manager is left alone so a running session is not disturbed.
|
|
97
|
+
self.config = nil
|
|
98
|
+
self.reportManager = nil
|
|
52
99
|
Asleep.setLogger(self)
|
|
53
100
|
if let appId = appId, let appSecret = appSecret {
|
|
54
101
|
Asleep.initAsleepConfig(appId: appId,
|
|
@@ -56,13 +103,13 @@ public class AsleepModule: Module {
|
|
|
56
103
|
userId: userId,
|
|
57
104
|
baseUrl: URL(string: baseUrl ?? ""),
|
|
58
105
|
callbackUrl: URL(string: callbackUrl ?? ""),
|
|
59
|
-
delegate:
|
|
106
|
+
delegate: callDelegate)
|
|
60
107
|
} else {
|
|
61
108
|
Asleep.initAsleepConfig(apiKey: apiKey,
|
|
62
109
|
userId: userId,
|
|
63
110
|
baseUrl: URL(string: baseUrl ?? ""),
|
|
64
111
|
callbackUrl: URL(string: callbackUrl ?? ""),
|
|
65
|
-
delegate:
|
|
112
|
+
delegate: callDelegate)
|
|
66
113
|
}
|
|
67
114
|
}
|
|
68
115
|
|
|
@@ -114,11 +161,17 @@ public class AsleepModule: Module {
|
|
|
114
161
|
trackingManager.startTracking(additionalAudioSessionOptions: additionalOptions)
|
|
115
162
|
}
|
|
116
163
|
|
|
117
|
-
|
|
164
|
+
// Range bounds are epoch milliseconds; JS validates start < end before calling.
|
|
165
|
+
AsyncFunction("stopTracking") { (analysisStartMs: Double?, analysisEndMs: Double?) -> Void in
|
|
118
166
|
guard let trackingManager = self.trackingManager else {
|
|
119
167
|
throw NSError(domain: "AsleepModule", code: 1, userInfo: [NSLocalizedDescriptionKey: "Tracking manager not initialized"])
|
|
120
168
|
}
|
|
121
|
-
|
|
169
|
+
if let analysisStartMs = analysisStartMs, let analysisEndMs = analysisEndMs {
|
|
170
|
+
trackingManager.stopTracking(analysisStartTime: Date(timeIntervalSince1970: analysisStartMs / 1000),
|
|
171
|
+
analysisEndTime: Date(timeIntervalSince1970: analysisEndMs / 1000))
|
|
172
|
+
} else {
|
|
173
|
+
trackingManager.stopTracking()
|
|
174
|
+
}
|
|
122
175
|
}
|
|
123
176
|
|
|
124
177
|
AsyncFunction("resumeTracking") { () -> Void in
|
|
@@ -183,6 +236,62 @@ public class AsleepModule: Module {
|
|
|
183
236
|
}
|
|
184
237
|
}
|
|
185
238
|
|
|
239
|
+
// Resolves when the server accepts the request; the completion block is
|
|
240
|
+
// not called on the main queue (Reports.Interface.swift). Range bounds are
|
|
241
|
+
// epoch milliseconds and are always passed explicitly (null when absent).
|
|
242
|
+
AsyncFunction("reanalyze") { (sessionId: String, analysisStartMs: Double?, analysisEndMs: Double?, promise: Promise) in
|
|
243
|
+
guard let reportManager = self.reportManager else {
|
|
244
|
+
promise.reject("MISSING_PREREQUISITE", "Reports not initialized")
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
let completion: (String?, Asleep.AsleepError?) -> Void = { _, error in
|
|
248
|
+
if let error = error {
|
|
249
|
+
let sdkCode = error.errorCode.code
|
|
250
|
+
// 11009 invalidParameter: start >= end (JS validates this first).
|
|
251
|
+
let code = sdkCode == 11009 ? "INVALID_ARGUMENT" : "REANALYZE_FAILED"
|
|
252
|
+
promise.reject(sdkRejection(code, sdkCode: sdkCode, message: sdkMessage(error)))
|
|
253
|
+
} else {
|
|
254
|
+
promise.resolve(nil)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if let analysisStartMs = analysisStartMs, let analysisEndMs = analysisEndMs {
|
|
258
|
+
reportManager.reanalyze(sessionId: sessionId,
|
|
259
|
+
analysisStartTime: Date(timeIntervalSince1970: analysisStartMs / 1000),
|
|
260
|
+
analysisEndTime: Date(timeIntervalSince1970: analysisEndMs / 1000),
|
|
261
|
+
completionBlock: completion)
|
|
262
|
+
} else {
|
|
263
|
+
reportManager.reanalyze(sessionId: sessionId, completionBlock: completion)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Promise style (not a throwing AsyncFunction) so rejections carry the SDK message
|
|
268
|
+
// as-is instead of Expo's "Calling the '...' function has failed" wrapper,
|
|
269
|
+
// matching reanalyze and Android.
|
|
270
|
+
AsyncFunction("saveUserMetadata") { (metadata: UserMetadataRecord, promise: Promise) in
|
|
271
|
+
Task {
|
|
272
|
+
do {
|
|
273
|
+
try await self.saveUserMetadata(metadata)
|
|
274
|
+
promise.resolve(nil)
|
|
275
|
+
} catch let exception as Exception {
|
|
276
|
+
promise.reject(exception)
|
|
277
|
+
} catch {
|
|
278
|
+
promise.reject(sdkRejection("SAVE_USER_METADATA_FAILED", sdkCode: 27000, message: error.localizedDescription))
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
AsyncFunction("fetchUserMetadata") { (promise: Promise) in
|
|
284
|
+
Task {
|
|
285
|
+
do {
|
|
286
|
+
promise.resolve(try await self.fetchUserMetadata())
|
|
287
|
+
} catch let exception as Exception {
|
|
288
|
+
promise.reject(exception)
|
|
289
|
+
} catch {
|
|
290
|
+
promise.reject(sdkRejection("FETCH_USER_METADATA_FAILED", sdkCode: 27100, message: error.localizedDescription))
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
186
295
|
Function("isTracking") { () -> Bool in
|
|
187
296
|
return trackingManager?.getTrackingStatus().sessionId != nil
|
|
188
297
|
}
|
|
@@ -249,6 +358,41 @@ public class AsleepModule: Module {
|
|
|
249
358
|
}
|
|
250
359
|
}
|
|
251
360
|
|
|
361
|
+
// Expo rejections carry only a code string and a message. JS normalizeError
|
|
362
|
+
// splits "<CODE>:<sdkCode>" back into AsleepError.code and AsleepError.sdkCode.
|
|
363
|
+
// AsleepError is not a LocalizedError, so localizedDescription is only the generic
|
|
364
|
+
// "The operation couldn't be completed" text. Prefer the SDK/server message.
|
|
365
|
+
private func sdkMessage(_ error: Asleep.AsleepError) -> String {
|
|
366
|
+
if let message = error.errorCode.message, !message.isEmpty { return message }
|
|
367
|
+
return String(describing: error)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
private func sdkRejection(_ code: String, sdkCode: Int, message: String) -> Exception {
|
|
371
|
+
let encoded = "\(code):\(sdkCode)"
|
|
372
|
+
return Exception(name: encoded, description: message, code: encoded)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
struct SetupCredentialsRecord: Record {
|
|
376
|
+
@Field var apiKey: String?
|
|
377
|
+
@Field var appId: String?
|
|
378
|
+
@Field var appSecret: String?
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
struct ProductInfoRecord: Record {
|
|
382
|
+
@Field var model: String = ""
|
|
383
|
+
@Field var identifierType: String = ""
|
|
384
|
+
@Field var identifierValue: String = ""
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
struct UserMetadataRecord: Record {
|
|
388
|
+
@Field var birthYear: Int?
|
|
389
|
+
@Field var birthMonth: Int?
|
|
390
|
+
@Field var birthDay: Int?
|
|
391
|
+
@Field var gender: String?
|
|
392
|
+
@Field var height: Double?
|
|
393
|
+
@Field var weight: Double?
|
|
394
|
+
}
|
|
395
|
+
|
|
252
396
|
extension AsleepModule: AsleepSetupDelegate {
|
|
253
397
|
public func setupDidComplete() {
|
|
254
398
|
sendEvent("onSetupDidComplete", [:])
|
|
@@ -266,17 +410,78 @@ extension AsleepModule: AsleepSetupDelegate {
|
|
|
266
410
|
public func setupInProgress(progress: Int) {
|
|
267
411
|
sendEvent("onSetupInProgress", ["progress": progress])
|
|
268
412
|
}
|
|
413
|
+
private func saveUserMetadata(_ metadata: UserMetadataRecord) async throws {
|
|
414
|
+
guard let config = self.config else {
|
|
415
|
+
throw Exception(name: "MISSING_PREREQUISITE", description: "AsleepConfig is not initialized", code: "MISSING_PREREQUISITE")
|
|
416
|
+
}
|
|
417
|
+
var gender: Asleep.Model.Gender?
|
|
418
|
+
if let rawGender = metadata.gender {
|
|
419
|
+
guard let parsed = Asleep.Model.Gender(rawValue: rawGender) else {
|
|
420
|
+
throw sdkRejection("INVALID_ARGUMENT", sdkCode: 27400, message: "Unknown gender: \(rawGender)")
|
|
421
|
+
}
|
|
422
|
+
gender = parsed
|
|
423
|
+
}
|
|
424
|
+
let model = Asleep.Model.UserMetadata(birthYear: metadata.birthYear,
|
|
425
|
+
birthMonth: metadata.birthMonth,
|
|
426
|
+
birthDay: metadata.birthDay,
|
|
427
|
+
gender: gender,
|
|
428
|
+
height: metadata.height,
|
|
429
|
+
weight: metadata.weight)
|
|
430
|
+
do {
|
|
431
|
+
try await Asleep.saveUserMetadata(model, config: config)
|
|
432
|
+
} catch let error as Asleep.AsleepError {
|
|
433
|
+
let sdkCode = error.errorCode.code
|
|
434
|
+
throw sdkRejection(sdkCode == 27400 ? "INVALID_ARGUMENT" : "SAVE_USER_METADATA_FAILED", sdkCode: sdkCode, message: sdkMessage(error))
|
|
435
|
+
} catch {
|
|
436
|
+
// Non-SDK failures (e.g. URLError) map to ERR_SAVE_METADATA_FAILED.
|
|
437
|
+
throw sdkRejection("SAVE_USER_METADATA_FAILED", sdkCode: 27000, message: error.localizedDescription)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private func fetchUserMetadata() async throws -> [String: Any]? {
|
|
442
|
+
guard let config = self.config else {
|
|
443
|
+
throw Exception(name: "MISSING_PREREQUISITE", description: "AsleepConfig is not initialized", code: "MISSING_PREREQUISITE")
|
|
444
|
+
}
|
|
445
|
+
let metadata: Asleep.Model.UserMetadata?
|
|
446
|
+
do {
|
|
447
|
+
metadata = try await Asleep.fetchUserMetadata(config: config)
|
|
448
|
+
} catch let error as Asleep.AsleepError {
|
|
449
|
+
throw sdkRejection("FETCH_USER_METADATA_FAILED", sdkCode: error.errorCode.code, message: sdkMessage(error))
|
|
450
|
+
} catch {
|
|
451
|
+
// Non-SDK failures (e.g. URLError) map to ERR_FETCH_METADATA_FAILED.
|
|
452
|
+
throw sdkRejection("FETCH_USER_METADATA_FAILED", sdkCode: 27100, message: error.localizedDescription)
|
|
453
|
+
}
|
|
454
|
+
return try metadata?.asDictionary()
|
|
455
|
+
}
|
|
456
|
+
|
|
269
457
|
}
|
|
270
458
|
|
|
271
459
|
extension AsleepModule: AsleepConfigDelegate {
|
|
272
460
|
public func userDidJoin(userId: String, config: Asleep.Config) {
|
|
461
|
+
applyUserJoin(userId: userId, config: config)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
public func didFailUserJoin(error: Asleep.AsleepError) {
|
|
465
|
+
applyUserJoinFailure(error: error)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
public func userDidDelete(userId: String) {
|
|
469
|
+
sendEvent("onUserDeleted", ["userId": userId])
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// The SDK is now configured for this user, whichever call it answers, so the
|
|
473
|
+
// module state follows it and the event is always emitted. Only the calling
|
|
474
|
+
// InitCallDelegate settles a promise.
|
|
475
|
+
fileprivate func applyUserJoin(userId: String, config: Asleep.Config) {
|
|
273
476
|
self.config = config
|
|
274
477
|
self.trackingManager = Asleep.createSleepTrackingManager(config: config, delegate: self)
|
|
275
478
|
self.reportManager = Asleep.createReports(config: config)
|
|
276
479
|
sendEvent("onUserJoined", ["userId": userId])
|
|
277
480
|
}
|
|
278
481
|
|
|
279
|
-
|
|
482
|
+
fileprivate func applyUserJoinFailure(error: Asleep.AsleepError) {
|
|
483
|
+
self.config = nil
|
|
484
|
+
self.reportManager = nil
|
|
280
485
|
sendEvent("onUserJoinFailed", [
|
|
281
486
|
"error": error.localizedDescription,
|
|
282
487
|
"caseName": String(describing: error),
|
|
@@ -285,8 +490,73 @@ extension AsleepModule: AsleepConfigDelegate {
|
|
|
285
490
|
])
|
|
286
491
|
}
|
|
287
492
|
|
|
288
|
-
|
|
289
|
-
|
|
493
|
+
fileprivate func isCurrentInit(_ callDelegate: InitCallDelegate) -> Bool {
|
|
494
|
+
initLock.lock()
|
|
495
|
+
defer { initLock.unlock() }
|
|
496
|
+
return currentInit === callDelegate
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/// The SDK delegate for one initAsleepConfig call. Settles its promise at most once.
|
|
501
|
+
final class InitCallDelegate: AsleepConfigDelegate {
|
|
502
|
+
private weak var module: AsleepModule?
|
|
503
|
+
private let promise: Promise
|
|
504
|
+
private let lock = NSLock()
|
|
505
|
+
private var settled = false
|
|
506
|
+
|
|
507
|
+
init(module: AsleepModule, promise: Promise) {
|
|
508
|
+
self.module = module
|
|
509
|
+
self.promise = promise
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
var isSettled: Bool {
|
|
513
|
+
lock.lock()
|
|
514
|
+
defer { lock.unlock() }
|
|
515
|
+
return settled
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
func startTimeout() {
|
|
519
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + AsleepModule.initResponseTimeout) { [weak self] in
|
|
520
|
+
guard let self = self else { return }
|
|
521
|
+
// The module keeps this delegate while it is the current call, so a late
|
|
522
|
+
// answer can still configure the module if no newer call has started.
|
|
523
|
+
self.settle { promise in
|
|
524
|
+
promise.reject("INITIALIZATION_FAILED", "initAsleepConfig got no response from the SDK within \(Int(AsleepModule.initResponseTimeout)) s (it ignores init while tracking is starting or stopping, or while a previous init is pending)")
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
func userDidJoin(userId: String, config: Asleep.Config) {
|
|
530
|
+
guard let module = module, module.isCurrentInit(self) else {
|
|
531
|
+
module?.sendEvent("onDebugLog", ["message": "Ignored a user join for a superseded initAsleepConfig call"])
|
|
532
|
+
return
|
|
533
|
+
}
|
|
534
|
+
module.applyUserJoin(userId: userId, config: config)
|
|
535
|
+
settle { $0.resolve(["userId": userId]) }
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
func didFailUserJoin(error: Asleep.AsleepError) {
|
|
539
|
+
guard let module = module, module.isCurrentInit(self) else {
|
|
540
|
+
module?.sendEvent("onDebugLog", ["message": "Ignored a user join failure for a superseded initAsleepConfig call"])
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
module.applyUserJoinFailure(error: error)
|
|
544
|
+
settle { $0.reject(sdkRejection("INITIALIZATION_FAILED", sdkCode: error.errorCode.code, message: sdkMessage(error))) }
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
func userDidDelete(userId: String) {
|
|
548
|
+
module?.userDidDelete(userId: userId)
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
private func settle(_ action: (Promise) -> Void) {
|
|
552
|
+
lock.lock()
|
|
553
|
+
if settled {
|
|
554
|
+
lock.unlock()
|
|
555
|
+
return
|
|
556
|
+
}
|
|
557
|
+
settled = true
|
|
558
|
+
lock.unlock()
|
|
559
|
+
action(promise)
|
|
290
560
|
}
|
|
291
561
|
}
|
|
292
562
|
|
package/package.json
CHANGED
package/src/Asleep.types.ts
CHANGED
|
@@ -13,11 +13,31 @@ export type AsleepConfig = AsleepCredentials & {
|
|
|
13
13
|
callbackUrl?: string;
|
|
14
14
|
};
|
|
15
15
|
|
|
16
|
+
export type AsleepProductIdentifierType = "serial" | "mac_address";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The hardware product this app runs on, registered with Asleep during
|
|
20
|
+
* `setup()`. `setup()` rejects invalid input with `INVALID_ARGUMENT` before any
|
|
21
|
+
* native call. Values are sent as given; they are not trimmed.
|
|
22
|
+
*/
|
|
23
|
+
export type AsleepProductInfo = {
|
|
24
|
+
/** Product model name, 1-100 characters, not blank. */
|
|
25
|
+
model: string;
|
|
26
|
+
identifierType: AsleepProductIdentifierType;
|
|
27
|
+
/** The device's serial number or MAC address, 1-255 characters, not blank. */
|
|
28
|
+
identifierValue: string;
|
|
29
|
+
};
|
|
30
|
+
|
|
16
31
|
export type AsleepSetupConfig = AsleepCredentials & {
|
|
17
32
|
baseUrl?: string;
|
|
18
33
|
callbackUrl?: string;
|
|
19
34
|
service?: string;
|
|
20
35
|
enableODA?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Registers this device as a product before setup completes. Omit it to skip
|
|
38
|
+
* registration. See "Device registration" in the README.
|
|
39
|
+
*/
|
|
40
|
+
productInfo?: AsleepProductInfo;
|
|
21
41
|
};
|
|
22
42
|
|
|
23
43
|
export type AsleepReport = {
|
|
@@ -156,6 +176,53 @@ export type AsleepAverageReport = {
|
|
|
156
176
|
sleptSessions?: AsleepSleptSession[];
|
|
157
177
|
};
|
|
158
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Wall-clock window the server analyzes instead of the whole recording.
|
|
181
|
+
* `start` must be at least one second before `end` (whole-second precision);
|
|
182
|
+
* otherwise the action rejects with `INVALID_ARGUMENT` before any native call.
|
|
183
|
+
*/
|
|
184
|
+
export type AsleepAnalysisRange = {
|
|
185
|
+
start: Date;
|
|
186
|
+
end: Date;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export type StopTrackingOptions = {
|
|
190
|
+
/**
|
|
191
|
+
* Analyze only this window of the session. The server may silently ignore
|
|
192
|
+
* an invalid range and analyze the full session; no event reports that.
|
|
193
|
+
*/
|
|
194
|
+
analysisRange?: AsleepAnalysisRange;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
export type ReanalyzeOptions = {
|
|
198
|
+
/**
|
|
199
|
+
* Re-run analysis only for this window. Omitting it re-analyzes the full
|
|
200
|
+
* session and replaces any range set earlier, including one set at stop.
|
|
201
|
+
*/
|
|
202
|
+
analysisRange?: AsleepAnalysisRange;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
export type AsleepGender = "male" | "female" | "non_binary" | "other" | "prefer_not_to_say";
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Optional user profile used by the server to personalize analysis. Every
|
|
209
|
+
* field is optional; omitted fields are not sent. `saveUserMetadata()` rejects
|
|
210
|
+
* out-of-range values with `INVALID_ARGUMENT` before any native call.
|
|
211
|
+
*/
|
|
212
|
+
export type AsleepUserMetadata = {
|
|
213
|
+
/** Integer, 1900-2100. */
|
|
214
|
+
birthYear?: number;
|
|
215
|
+
/** Integer, 1-12. */
|
|
216
|
+
birthMonth?: number;
|
|
217
|
+
/** Integer, 1-31. */
|
|
218
|
+
birthDay?: number;
|
|
219
|
+
gender?: AsleepGender;
|
|
220
|
+
/** Centimeters, 1-500. The native SDKs truncate to one decimal place. */
|
|
221
|
+
height?: number;
|
|
222
|
+
/** Kilograms, 1-1000. The native SDKs truncate to one decimal place. */
|
|
223
|
+
weight?: number;
|
|
224
|
+
};
|
|
225
|
+
|
|
159
226
|
export type AsleepAnalysisResult = {
|
|
160
227
|
id?: string;
|
|
161
228
|
state?: string;
|