react-native-asleep 1.2.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.
@@ -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,23 +40,77 @@ public class AsleepModule: Module {
27
40
  Events("onSetupInProgress")
28
41
  Events("onAnalysisResult")
29
42
 
30
- Function("setup") { (apiKey: String, baseUrl: String?, callbackUrl: String?, service: String?, enableODA: Bool?) in
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
+ }
31
59
  Asleep.setLogger(self)
32
- Asleep.setup(apiKey: apiKey,
33
- baseUrl: URL(string: baseUrl ?? ""),
34
- callbackUrl: URL(string: callbackUrl ?? ""),
35
- service: service,
36
- enableODA: enableODA ?? false,
37
- delegate: self)
60
+ if let appId = credentials.appId, let appSecret = credentials.appSecret {
61
+ Asleep.setup(appId: appId,
62
+ appSecret: appSecret,
63
+ baseUrl: URL(string: baseUrl ?? ""),
64
+ callbackUrl: URL(string: callbackUrl ?? ""),
65
+ service: service,
66
+ enableODA: enableODA ?? false,
67
+ productInfo: product,
68
+ delegate: self)
69
+ } else {
70
+ Asleep.setup(apiKey: credentials.apiKey ?? "",
71
+ baseUrl: URL(string: baseUrl ?? ""),
72
+ callbackUrl: URL(string: callbackUrl ?? ""),
73
+ service: service,
74
+ enableODA: enableODA ?? false,
75
+ productInfo: product,
76
+ delegate: self)
77
+ }
38
78
  }
39
79
 
40
- Function("initAsleepConfig") { (apiKey: String, userId: String?, baseUrl: String?, callbackUrl: String?) in
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
41
99
  Asleep.setLogger(self)
42
- Asleep.initAsleepConfig(apiKey: apiKey,
43
- userId: userId,
44
- baseUrl: URL(string: baseUrl ?? ""),
45
- callbackUrl: URL(string: callbackUrl ?? ""),
46
- delegate: self)
100
+ if let appId = appId, let appSecret = appSecret {
101
+ Asleep.initAsleepConfig(appId: appId,
102
+ appSecret: appSecret,
103
+ userId: userId,
104
+ baseUrl: URL(string: baseUrl ?? ""),
105
+ callbackUrl: URL(string: callbackUrl ?? ""),
106
+ delegate: callDelegate)
107
+ } else {
108
+ Asleep.initAsleepConfig(apiKey: apiKey,
109
+ userId: userId,
110
+ baseUrl: URL(string: baseUrl ?? ""),
111
+ callbackUrl: URL(string: callbackUrl ?? ""),
112
+ delegate: callDelegate)
113
+ }
47
114
  }
48
115
 
49
116
  // Gates SDK log forwarding natively so disabled logs never cross the
@@ -94,11 +161,17 @@ public class AsleepModule: Module {
94
161
  trackingManager.startTracking(additionalAudioSessionOptions: additionalOptions)
95
162
  }
96
163
 
97
- AsyncFunction("stopTracking") { () -> Void in
164
+ // Range bounds are epoch milliseconds; JS validates start < end before calling.
165
+ AsyncFunction("stopTracking") { (analysisStartMs: Double?, analysisEndMs: Double?) -> Void in
98
166
  guard let trackingManager = self.trackingManager else {
99
167
  throw NSError(domain: "AsleepModule", code: 1, userInfo: [NSLocalizedDescriptionKey: "Tracking manager not initialized"])
100
168
  }
101
- trackingManager.stopTracking()
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
+ }
102
175
  }
103
176
 
104
177
  AsyncFunction("resumeTracking") { () -> Void in
@@ -163,6 +236,62 @@ public class AsleepModule: Module {
163
236
  }
164
237
  }
165
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
+
166
295
  Function("isTracking") { () -> Bool in
167
296
  return trackingManager?.getTrackingStatus().sessionId != nil
168
297
  }
@@ -229,6 +358,41 @@ public class AsleepModule: Module {
229
358
  }
230
359
  }
231
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
+
232
396
  extension AsleepModule: AsleepSetupDelegate {
233
397
  public func setupDidComplete() {
234
398
  sendEvent("onSetupDidComplete", [:])
@@ -246,17 +410,78 @@ extension AsleepModule: AsleepSetupDelegate {
246
410
  public func setupInProgress(progress: Int) {
247
411
  sendEvent("onSetupInProgress", ["progress": progress])
248
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
+
249
457
  }
250
458
 
251
459
  extension AsleepModule: AsleepConfigDelegate {
252
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) {
253
476
  self.config = config
254
477
  self.trackingManager = Asleep.createSleepTrackingManager(config: config, delegate: self)
255
478
  self.reportManager = Asleep.createReports(config: config)
256
479
  sendEvent("onUserJoined", ["userId": userId])
257
480
  }
258
481
 
259
- public func didFailUserJoin(error: Asleep.AsleepError) {
482
+ fileprivate func applyUserJoinFailure(error: Asleep.AsleepError) {
483
+ self.config = nil
484
+ self.reportManager = nil
260
485
  sendEvent("onUserJoinFailed", [
261
486
  "error": error.localizedDescription,
262
487
  "caseName": String(describing: error),
@@ -265,8 +490,73 @@ extension AsleepModule: AsleepConfigDelegate {
265
490
  ])
266
491
  }
267
492
 
268
- public func userDidDelete(userId: String) {
269
- sendEvent("onUserDeleted", ["userId": userId])
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)
270
560
  }
271
561
  }
272
562
 
@@ -298,13 +588,14 @@ extension AsleepModule: AsleepSleepTrackingManagerDelegate {
298
588
  errorInfo["message"] = "Audio recording could not be initialized and the recording engine has been torn down. resumeTracking() will not help; the session must be stopped and restarted."
299
589
  case .cannotActivateInBackground:
300
590
  errorInfo["code"] = "CANNOT_ACTIVATE_IN_BACKGROUND"
301
- errorInfo["message"] = "Recording could not resume in background. resumeTracking() must be called in foreground."
591
+ errorInfo["message"] = "Recording could not resume in background. The SDK retries when the app becomes active; call resumeTracking() in foreground if uploads do not resume."
302
592
  default:
303
593
  errorInfo["code"] = "UNKNOWN_ERROR"
304
594
  errorInfo["caseName"] = String(describing: error)
305
595
  }
306
596
  // (error as NSError).code is the Swift enum declaration ordinal, not the
307
597
  // documented Asleep error code; kept for backward compatibility only.
598
+ // It shifts when the SDK adds enum cases (3.3.x moved 38/39 to 59/60).
308
599
  errorInfo["errorCode"] = (error as NSError).code
309
600
  // Documented numeric code (10000-34999) via the SDK's errorCode computed
310
601
  // property — the v3.2.0+ recommended API (Asleep.Interface.swift). This is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-asleep",
3
- "version": "1.2.0",
3
+ "version": "2.1.0",
4
4
  "description": "Asleep SDK for React Native",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -44,7 +44,9 @@
44
44
  "expo-module.config.json",
45
45
  "*.podspec",
46
46
  "LICENSE.md",
47
- "CHANGELOG.md"
47
+ "CHANGELOG.md",
48
+ "docs/INTEGRATION.md",
49
+ "docs/INTEGRATION.ko.md"
48
50
  ],
49
51
  "devDependencies": {
50
52
  "@types/react": "^19.0.0",
@@ -64,5 +66,5 @@
64
66
  "optional": true
65
67
  }
66
68
  },
67
- "packageManager": "pnpm@10.30.3"
69
+ "packageManager": "pnpm@12.21.0"
68
70
  }
@@ -1,16 +1,43 @@
1
- export type AsleepConfig = {
2
- apiKey: string;
1
+ /**
2
+ * Authentication passed to `setup()` and `initAsleepConfig()`: either an API
3
+ * key or a token-auth `appId` / `appSecret` pair. The two forms are mutually
4
+ * exclusive; supplying neither or both is rejected with `INVALID_ARGUMENT`.
5
+ */
6
+ export type AsleepCredentials =
7
+ | { apiKey: string; appId?: never; appSecret?: never }
8
+ | { appId: string; appSecret: string; apiKey?: never };
9
+
10
+ export type AsleepConfig = AsleepCredentials & {
3
11
  userId?: string;
4
12
  baseUrl?: string;
5
13
  callbackUrl?: string;
6
14
  };
7
15
 
8
- export type AsleepSetupConfig = {
9
- apiKey: string;
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
+
31
+ export type AsleepSetupConfig = AsleepCredentials & {
10
32
  baseUrl?: string;
11
33
  callbackUrl?: string;
12
34
  service?: string;
13
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;
14
41
  };
15
42
 
16
43
  export type AsleepReport = {
@@ -149,6 +176,53 @@ export type AsleepAverageReport = {
149
176
  sleptSessions?: AsleepSleptSession[];
150
177
  };
151
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
+
152
226
  export type AsleepAnalysisResult = {
153
227
  id?: string;
154
228
  state?: string;
@@ -243,7 +317,9 @@ export type AsleepEventType = {
243
317
  message?: string;
244
318
  /**
245
319
  * @deprecated On iOS this is the Swift enum declaration ordinal from
246
- * NSError bridging, not the documented Asleep error code. Use `sdkCode`.
320
+ * NSError bridging, not the documented Asleep error code, and it shifts
321
+ * when the native enum gains cases (iOS SDK 3.3.x moved 38/39 to 59/60).
322
+ * Use `sdkCode`, `caseName`, or `category`.
247
323
  */
248
324
  errorCode?: number;
249
325
  /** Numeric code documented by the native Asleep SDKs (both platforms). */