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.
@@ -2,16 +2,21 @@ import { EventEmitter } from "expo-modules-core";
2
2
  import { PermissionsAndroid, Platform } from "react-native";
3
3
  import type {
4
4
  AsleepAnalysisAck,
5
+ AsleepAnalysisRange,
5
6
  AsleepAnalysisResult,
6
7
  AsleepAverageReport,
7
8
  AsleepConfig,
8
9
  AsleepCredentials,
9
10
  AsleepErrorCategory,
10
11
  AsleepEventType,
12
+ AsleepProductInfo,
11
13
  AsleepReport,
12
14
  AsleepSession,
13
15
  AsleepSetupConfig,
16
+ AsleepUserMetadata,
17
+ ReanalyzeOptions,
14
18
  SetupStatus,
19
+ StopTrackingOptions,
15
20
  TrackingConfig,
16
21
  TrackingStatus,
17
22
  } from "./Asleep.types";
@@ -48,6 +53,12 @@ export interface InternalAsleepState {
48
53
  trackingStatus: TrackingStatus;
49
54
  sessionId: string | null;
50
55
  userId: string | null;
56
+ // The native user config for the most recent initAsleepConfig() exists.
57
+ // While an init is in progress its action is the only writer that may enable
58
+ // it (on resolution with a userId; both platforms resolve after the join).
59
+ // onUserJoined enables it only outside an init (SDK-initiated joins), and
60
+ // onUserJoinFailed/onUserDeleted may always disable it.
61
+ isUserConfigReady: boolean;
51
62
  error: AsleepError | null;
52
63
  analysisResult: AsleepAnalysisResult | null;
53
64
  isAnalyzing: boolean;
@@ -68,12 +79,15 @@ export interface AsleepActions {
68
79
  checkBatteryOptimization: () => Promise<{ exempted: boolean; platform: string; message?: string }>;
69
80
  requestBatteryOptimizationExemption: () => Promise<boolean>;
70
81
  startTracking: (config?: TrackingConfig) => Promise<void>;
71
- stopTracking: () => Promise<void>;
82
+ stopTracking: (options?: StopTrackingOptions) => Promise<void>;
72
83
  resumeTracking: () => Promise<void>;
73
84
  getReport: (sessionId: string) => Promise<AsleepReport>;
74
85
  getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
75
86
  getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport>;
76
87
  deleteSession: (sessionId: string) => Promise<void>;
88
+ reanalyze: (sessionId: string, options?: ReanalyzeOptions) => Promise<void>;
89
+ saveUserMetadata: (metadata: AsleepUserMetadata) => Promise<void>;
90
+ fetchUserMetadata: () => Promise<AsleepUserMetadata | null>;
77
91
  requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck>;
78
92
  hasRequiredPermissions: () => Promise<boolean>;
79
93
  requestRequiredPermissions: () => Promise<boolean>;
@@ -113,6 +127,7 @@ export const useAsleepStore = createStore<InternalAsleepState>(() => ({
113
127
  trackingStatus: initialTrackingStatus,
114
128
  sessionId: null,
115
129
  userId: null,
130
+ isUserConfigReady: false,
116
131
  error: null,
117
132
  analysisResult: null,
118
133
  isAnalyzing: false,
@@ -138,6 +153,10 @@ const convertKeysToCamelCase = (value: any): any => {
138
153
  return value;
139
154
  };
140
155
 
156
+ // Expo promise rejections carry only a code string and a message, so native
157
+ // rejections that know the documented SDK code encode it as "<CODE>:<sdkCode>".
158
+ const NATIVE_REJECTION_CODE = /^([A-Z][A-Z0-9_]*):(\d+)$/;
159
+
141
160
  type ErrorOptions = {
142
161
  category?: AsleepErrorCategory;
143
162
  sdkCode?: number;
@@ -158,7 +177,8 @@ export const normalizeError = (source: unknown, fallbackCode: string, options: E
158
177
  caseName?: unknown;
159
178
  })
160
179
  : undefined;
161
- const code = typeof payload?.code === "string" ? payload.code : fallbackCode;
180
+ const encoded = typeof payload?.code === "string" ? NATIVE_REJECTION_CODE.exec(payload.code) : null;
181
+ const code = encoded ? encoded[1] : typeof payload?.code === "string" ? payload.code : fallbackCode;
162
182
  const message =
163
183
  typeof payload?.message === "string"
164
184
  ? payload.message
@@ -177,9 +197,11 @@ export const normalizeError = (source: unknown, fallbackCode: string, options: E
177
197
  options.sdkCode ??
178
198
  (typeof payload?.sdkCode === "number"
179
199
  ? payload.sdkCode
180
- : source instanceof AsleepError
181
- ? source.sdkCode
182
- : undefined),
200
+ : encoded
201
+ ? Number(encoded[2])
202
+ : source instanceof AsleepError
203
+ ? source.sdkCode
204
+ : undefined),
183
205
  caseName:
184
206
  options.caseName ??
185
207
  (typeof payload?.caseName === "string"
@@ -259,6 +281,135 @@ const resolveCredentials = (config: AsleepCredentials): NativeCredentials => {
259
281
  return { appId, appSecret };
260
282
  };
261
283
 
284
+ const PRODUCT_INFO_FIELDS = new Set<string>(["model", "identifierType", "identifierValue"]);
285
+ const PRODUCT_INFO_LENGTH_LIMITS = { model: 100, identifierValue: 255 } as const;
286
+
287
+ // Mirrors the native pre-checks (iOS ProductManager.validate, Android
288
+ // ProductRegistrar.validate), which otherwise fail the whole setup with 13400:
289
+ // not blank after trimming, and the untrimmed value within the length limit.
290
+ // Returns null when no productInfo was supplied.
291
+ const resolveProductInfo = (productInfo: unknown): AsleepProductInfo | null => {
292
+ if (productInfo == null) return null;
293
+ if (typeof productInfo !== "object" || Array.isArray(productInfo)) {
294
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "productInfo must be an object."));
295
+ }
296
+ const source = productInfo as Record<string, unknown>;
297
+ const unknownField = Object.keys(source).find((field) => !PRODUCT_INFO_FIELDS.has(field));
298
+ if (unknownField !== undefined) {
299
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", `productInfo.${unknownField} is not a known field.`));
300
+ }
301
+ for (const [field, max] of Object.entries(PRODUCT_INFO_LENGTH_LIMITS)) {
302
+ const value = source[field];
303
+ if (typeof value !== "string" || value.trim().length === 0 || value.length > max) {
304
+ return storeAndThrow(
305
+ new AsleepError(
306
+ "INVALID_ARGUMENT",
307
+ `productInfo.${field} must be a non-blank string of at most ${max} characters.`,
308
+ ),
309
+ );
310
+ }
311
+ }
312
+ if (source.identifierType !== "serial" && source.identifierType !== "mac_address") {
313
+ return storeAndThrow(
314
+ new AsleepError("INVALID_ARGUMENT", 'productInfo.identifierType must be "serial" or "mac_address".'),
315
+ );
316
+ }
317
+ return {
318
+ model: source.model as string,
319
+ identifierType: source.identifierType,
320
+ identifierValue: source.identifierValue as string,
321
+ };
322
+ };
323
+
324
+ const isValidDate = (value: unknown): value is Date => value instanceof Date && Number.isFinite(value.getTime());
325
+
326
+ // Both native SDKs reject start >= end (iOS 11009 via didFail after stop has
327
+ // already resolved), and they compare at whole-second precision. Returns epoch
328
+ // milliseconds for the bridge, or null when no range was supplied.
329
+ const resolveAnalysisRange = (range: AsleepAnalysisRange | undefined): [number, number] | null => {
330
+ if (range == null) return null;
331
+ const { start, end } = range as { start?: unknown; end?: unknown };
332
+ if (!isValidDate(start) || !isValidDate(end)) {
333
+ return storeAndThrow(
334
+ new AsleepError("INVALID_ARGUMENT", "analysisRange.start and analysisRange.end must be valid Date objects."),
335
+ );
336
+ }
337
+ if (Math.floor(start.getTime() / 1000) >= Math.floor(end.getTime() / 1000)) {
338
+ return storeAndThrow(
339
+ new AsleepError("INVALID_ARGUMENT", "analysisRange.start must be at least one second before analysisRange.end."),
340
+ );
341
+ }
342
+ return [start.getTime(), end.getTime()];
343
+ };
344
+
345
+ const USER_METADATA_INTEGER_RANGES = {
346
+ birthYear: [1900, 2100],
347
+ birthMonth: [1, 12],
348
+ birthDay: [1, 31],
349
+ } as const;
350
+
351
+ const USER_METADATA_NUMBER_RANGES = {
352
+ height: [1, 500],
353
+ weight: [1, 1000],
354
+ } as const;
355
+
356
+ const USER_METADATA_GENDERS = new Set<string>(["male", "female", "non_binary", "other", "prefer_not_to_say"]);
357
+
358
+ // Mirrors the native range checks (iOS UserMetadata.validate(), Android
359
+ // UserMetadata init) so invalid input never reaches the bridge. Only known
360
+ // fields are forwarded; undefined and null mean "not provided".
361
+ const resolveUserMetadata = (metadata: AsleepUserMetadata): AsleepUserMetadata => {
362
+ if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata)) {
363
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "metadata must be an object."));
364
+ }
365
+ const source = metadata as Record<string, unknown>;
366
+ const resolved: Record<string, number | string> = {};
367
+ for (const [field, [min, max]] of Object.entries(USER_METADATA_INTEGER_RANGES)) {
368
+ const value = source[field];
369
+ if (value == null) continue;
370
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
371
+ return storeAndThrow(
372
+ new AsleepError("INVALID_ARGUMENT", `${field} must be an integer between ${min} and ${max}.`),
373
+ );
374
+ }
375
+ resolved[field] = value;
376
+ }
377
+ for (const [field, [min, max]] of Object.entries(USER_METADATA_NUMBER_RANGES)) {
378
+ const value = source[field];
379
+ if (value == null) continue;
380
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
381
+ return storeAndThrow(new AsleepError("INVALID_ARGUMENT", `${field} must be a number between ${min} and ${max}.`));
382
+ }
383
+ resolved[field] = value;
384
+ }
385
+ if (source.gender != null) {
386
+ if (typeof source.gender !== "string" || !USER_METADATA_GENDERS.has(source.gender)) {
387
+ return storeAndThrow(
388
+ new AsleepError(
389
+ "INVALID_ARGUMENT",
390
+ 'gender must be one of "male", "female", "non_binary", "other", or "prefer_not_to_say".',
391
+ ),
392
+ );
393
+ }
394
+ resolved.gender = source.gender;
395
+ }
396
+ return resolved as AsleepUserMetadata;
397
+ };
398
+
399
+ // The native user config exists only after the most recent initAsleepConfig()
400
+ // joined its user. A re-init in progress or a failed re-init invalidates it, so
401
+ // these calls never run against a previous user's config.
402
+ const requireUserConfig = (action: string) => {
403
+ if (!useAsleepStore.getState().isUserConfigReady) {
404
+ storeAndThrow(
405
+ new AsleepError(
406
+ "MISSING_PREREQUISITE",
407
+ `initAsleepConfig() must resolve (complete its user join) before ${action}().`,
408
+ ),
409
+ );
410
+ }
411
+ };
412
+
262
413
  const normalizeReport = (report: any, sessionId: string): AsleepReport => {
263
414
  const converted = convertKeysToCamelCase(report);
264
415
  if (converted && !converted.session && converted.sessionId) {
@@ -286,6 +437,7 @@ const normalizeReport = (report: any, sessionId: string): AsleepReport => {
286
437
  export const asleepActions: AsleepActions = {
287
438
  setup: async (config) => {
288
439
  const credentials = resolveCredentials(config);
440
+ const productInfo = resolveProductInfo(config.productInfo);
289
441
  const state = useAsleepStore.getState();
290
442
  if (state.setupStatus === "inProgress") {
291
443
  storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
@@ -296,16 +448,19 @@ export const asleepActions: AsleepActions = {
296
448
 
297
449
  const errorBefore = state.error;
298
450
  addLog("[setup] Start");
299
- useAsleepStore.setState({ setupStatus: "inProgress" });
451
+ // setup() reconfigures the SDK (possibly with other credentials), so the
452
+ // previous user config is no longer valid until initAsleepConfig() resolves.
453
+ useAsleepStore.setState({ setupStatus: "inProgress", isUserConfigReady: false });
300
454
  try {
455
+ // Credentials travel as one record: Expo's Kotlin AsyncFunction accepts at
456
+ // most eight parameters including the promise.
301
457
  await AsleepModule.setup(
302
- credentials.apiKey,
303
- credentials.appId,
304
- credentials.appSecret,
458
+ credentials,
305
459
  config.baseUrl,
306
460
  config.callbackUrl,
307
461
  config.service,
308
462
  config.enableODA,
463
+ productInfo,
309
464
  );
310
465
  useAsleepStore.setState({
311
466
  setupStatus: "complete",
@@ -330,9 +485,9 @@ export const asleepActions: AsleepActions = {
330
485
  // while trackingStatus is "tracking" (v1 behavior the restore flow relies on).
331
486
  const errorBefore = state.error;
332
487
  addLog("[initAsleepConfig] Start");
333
- useAsleepStore.setState({ setupStatus: "inProgress" });
488
+ useAsleepStore.setState({ setupStatus: "inProgress", isUserConfigReady: false });
334
489
  try {
335
- await AsleepModule.initAsleepConfig(
490
+ const result = await AsleepModule.initAsleepConfig(
336
491
  credentials.apiKey,
337
492
  credentials.appId,
338
493
  credentials.appSecret,
@@ -340,11 +495,21 @@ export const asleepActions: AsleepActions = {
340
495
  config.baseUrl,
341
496
  config.callbackUrl,
342
497
  );
343
- useAsleepStore.setState({ setupStatus: "complete", isInitialized: true });
498
+ // Both platforms resolve after the user join with { userId }. This
499
+ // resolution, not onUserJoined, enables readiness for this init.
500
+ const joined = typeof result?.userId === "string" && result.userId.length > 0;
501
+ useAsleepStore.setState({
502
+ setupStatus: "complete",
503
+ isInitialized: true,
504
+ ...(joined ? { isUserConfigReady: true } : {}),
505
+ });
344
506
  clearErrorIfUnchanged(errorBefore);
345
507
  addLog("[initAsleepConfig] Success");
346
508
  } catch (error) {
347
- return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, { setupStatus: "idle" });
509
+ return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, {
510
+ setupStatus: "idle",
511
+ isUserConfigReady: false,
512
+ });
348
513
  }
349
514
  },
350
515
 
@@ -465,10 +630,13 @@ export const asleepActions: AsleepActions = {
465
630
  }
466
631
  },
467
632
 
468
- stopTracking: async () => {
633
+ stopTracking: async (options) => {
634
+ const range = resolveAnalysisRange(options?.analysisRange);
469
635
  const errorBefore = useAsleepStore.getState().error;
470
636
  try {
471
- const result = await AsleepModule.stopTracking();
637
+ // Always pass both arguments: older expo-modules-core versions do not let
638
+ // trailing nullable arguments be omitted.
639
+ const result = await AsleepModule.stopTracking(range ? range[0] : null, range ? range[1] : null);
472
640
  useAsleepStore.setState({
473
641
  didClose: true,
474
642
  ...(typeof result === "string" && result ? { sessionId: result } : {}),
@@ -560,6 +728,49 @@ export const asleepActions: AsleepActions = {
560
728
  }
561
729
  },
562
730
 
731
+ reanalyze: async (sessionId, options) => {
732
+ if (typeof sessionId !== "string" || sessionId.trim().length === 0) {
733
+ storeAndThrow(new AsleepError("INVALID_ARGUMENT", "sessionId must be a non-empty string."));
734
+ }
735
+ const range = resolveAnalysisRange(options?.analysisRange);
736
+ requireUserConfig("reanalyze");
737
+ const errorBefore = useAsleepStore.getState().error;
738
+ try {
739
+ // Resolves once the server accepts the request, not when analysis finishes.
740
+ // Nulls are explicit: iOS treats arguments before a Promise as required.
741
+ await AsleepModule.reanalyze(sessionId, range?.[0] ?? null, range?.[1] ?? null);
742
+ clearErrorIfUnchanged(errorBefore);
743
+ } catch (error) {
744
+ return guardedFailure(error, "REANALYZE_FAILED", errorBefore);
745
+ }
746
+ },
747
+
748
+ saveUserMetadata: async (metadata) => {
749
+ const resolved = resolveUserMetadata(metadata);
750
+ requireUserConfig("saveUserMetadata");
751
+ const errorBefore = useAsleepStore.getState().error;
752
+ try {
753
+ await AsleepModule.saveUserMetadata(resolved);
754
+ clearErrorIfUnchanged(errorBefore);
755
+ } catch (error) {
756
+ return guardedFailure(error, "SAVE_USER_METADATA_FAILED", errorBefore);
757
+ }
758
+ },
759
+
760
+ fetchUserMetadata: async () => {
761
+ requireUserConfig("fetchUserMetadata");
762
+ const errorBefore = useAsleepStore.getState().error;
763
+ try {
764
+ const payload = await AsleepModule.fetchUserMetadata();
765
+ // Android serializes the native model with snake_case keys.
766
+ const result: AsleepUserMetadata | null = payload == null ? null : convertKeysToCamelCase(payload);
767
+ clearErrorIfUnchanged(errorBefore);
768
+ return result;
769
+ } catch (error) {
770
+ return guardedFailure(error, "FETCH_USER_METADATA_FAILED", errorBefore);
771
+ }
772
+ },
773
+
563
774
  requestAnalysis: async () => {
564
775
  const errorBefore = useAsleepStore.getState().error;
565
776
  useAsleepStore.setState({ isAnalyzing: true });
@@ -682,14 +893,22 @@ const transitionForEvent = (
682
893
  ): { partial: Partial<InternalAsleepState>; log: string; requestAnalysis?: boolean } => {
683
894
  switch (eventType) {
684
895
  case "onUserJoined":
685
- return { partial: { userId: payload.userId }, log: `[onUserJoined] userId: ${payload.userId}` };
896
+ // During initAsleepConfig() the action's resolution owns readiness, so a
897
+ // stale join from an earlier init cannot enable the config for this one.
898
+ return {
899
+ partial: {
900
+ userId: payload.userId,
901
+ ...(state.setupStatus === "inProgress" ? {} : { isUserConfigReady: true }),
902
+ },
903
+ log: `[onUserJoined] userId: ${payload.userId}`,
904
+ };
686
905
  case "onUserJoinFailed":
687
906
  return {
688
- partial: { error: normalizeError(payload, "USER_JOIN_FAILED") },
907
+ partial: { error: normalizeError(payload, "USER_JOIN_FAILED"), isUserConfigReady: false },
689
908
  log: `[onUserJoinFailed] error: ${payload?.message ?? payload?.detail ?? payload?.error ?? "Unknown error"}`,
690
909
  };
691
910
  case "onUserDeleted":
692
- return { partial: { userId: null }, log: `[onUserDeleted] userId: ${payload.userId}` };
911
+ return { partial: { userId: null, isUserConfigReady: false }, log: `[onUserDeleted] userId: ${payload.userId}` };
693
912
  case "onTrackingCreated":
694
913
  return {
695
914
  partial: { trackingStatus: "tracking", ...(payload?.sessionId ? { sessionId: payload.sessionId } : {}) },
package/src/index.ts CHANGED
@@ -40,20 +40,27 @@ export { AsleepError } from "./Asleep.types";
40
40
 
41
41
  export type {
42
42
  AsleepAnalysisAck,
43
+ AsleepAnalysisRange,
43
44
  AsleepAnalysisResult,
44
45
  AsleepAverageReport,
45
46
  AsleepConfig,
46
47
  AsleepCredentials,
47
48
  AsleepErrorCategory,
48
49
  AsleepEventType,
50
+ AsleepGender,
49
51
  AsleepNeverSleptSession,
52
+ AsleepProductIdentifierType,
53
+ AsleepProductInfo,
50
54
  AsleepReport,
51
55
  AsleepSession,
52
56
  AsleepSetupConfig,
53
57
  AsleepSleptSession,
54
58
  AsleepStat,
59
+ AsleepUserMetadata,
55
60
  AudioSessionOption,
61
+ ReanalyzeOptions,
56
62
  SetupStatus,
63
+ StopTrackingOptions,
57
64
  TrackingConfig,
58
65
  TrackingStatus,
59
66
  } from "./Asleep.types";