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.
- package/README.ko.md +404 -0
- package/README.md +289 -215
- package/android/build.gradle +1 -1
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +274 -77
- package/build/Asleep.types.d.ts +78 -4
- 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 +236 -29
- 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 +427 -0
- package/docs/INTEGRATION.md +474 -0
- package/ios/Asleep.podspec +1 -1
- package/ios/AsleepModule.swift +310 -19
- package/package.json +5 -3
- package/src/Asleep.types.ts +81 -5
- package/src/AsleepStore.ts +302 -30
- package/src/index.ts +8 -0
package/src/AsleepStore.ts
CHANGED
|
@@ -2,15 +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,
|
|
9
|
+
AsleepCredentials,
|
|
8
10
|
AsleepErrorCategory,
|
|
9
11
|
AsleepEventType,
|
|
12
|
+
AsleepProductInfo,
|
|
10
13
|
AsleepReport,
|
|
11
14
|
AsleepSession,
|
|
12
15
|
AsleepSetupConfig,
|
|
16
|
+
AsleepUserMetadata,
|
|
17
|
+
ReanalyzeOptions,
|
|
13
18
|
SetupStatus,
|
|
19
|
+
StopTrackingOptions,
|
|
14
20
|
TrackingConfig,
|
|
15
21
|
TrackingStatus,
|
|
16
22
|
} from "./Asleep.types";
|
|
@@ -21,18 +27,22 @@ import { createStore } from "./store/createStore";
|
|
|
21
27
|
const emitter = new EventEmitter(AsleepModule);
|
|
22
28
|
|
|
23
29
|
// Native sessions are already gone for these errors and no close event follows.
|
|
24
|
-
const TERMINAL_TRACKING_ERROR_CODES = new Set<string>(["UPLOAD_TRACKING_TERMINATED"
|
|
30
|
+
const TERMINAL_TRACKING_ERROR_CODES = new Set<string>(["UPLOAD_TRACKING_TERMINATED"]);
|
|
25
31
|
|
|
26
|
-
// iOS
|
|
27
|
-
const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED"]);
|
|
32
|
+
// iOS stops recording but leaves the native session open; stopTracking() closes it.
|
|
33
|
+
const RECORDING_DEAD_ERROR_CODES = new Set<string>(["AUDIO_INITIALIZATION_FAILED", "INTERRUPTION_RECOVERY_FAILED"]);
|
|
28
34
|
|
|
29
35
|
// iOS 3.2.0 needs an explicit foreground resume after this failure.
|
|
30
36
|
const RECOVERY_REQUIRED_ERROR_CODES = new Set<string>(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
|
|
31
37
|
|
|
32
|
-
// Android SDK 3.
|
|
33
|
-
// synchronized with AsleepModule.kt's TERMINAL_TRACKING_ERROR_CODES.
|
|
38
|
+
// The first 13 codes are the Android SDK 3.3.x session-teardown set; keep them
|
|
39
|
+
// synchronized with AsleepModule.kt's TERMINAL_TRACKING_ERROR_CODES. The rest are
|
|
40
|
+
// start failures after which no native session exists: iOS 3.3.2 create HTTP
|
|
41
|
+
// 400/403/429/404 (22400, 11403, 11404) and insufficient storage (11008, both
|
|
42
|
+
// platforms). Android reports create failures as 22000. 11010 (alreadyTracking)
|
|
43
|
+
// is deliberately absent because the existing session survives it.
|
|
34
44
|
const TERMINAL_TRACKING_SDK_CODES = new Set<number>([
|
|
35
|
-
11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500,
|
|
45
|
+
11003, 22000, 22401, 22409, 22422, 22500, 23499, 24000, 24400, 24401, 24403, 24404, 24500, 11008, 11403, 11404, 22400,
|
|
36
46
|
]);
|
|
37
47
|
|
|
38
48
|
// The native session survives these exhausted upload attempts.
|
|
@@ -43,6 +53,12 @@ export interface InternalAsleepState {
|
|
|
43
53
|
trackingStatus: TrackingStatus;
|
|
44
54
|
sessionId: string | null;
|
|
45
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;
|
|
46
62
|
error: AsleepError | null;
|
|
47
63
|
analysisResult: AsleepAnalysisResult | null;
|
|
48
64
|
isAnalyzing: boolean;
|
|
@@ -63,12 +79,15 @@ export interface AsleepActions {
|
|
|
63
79
|
checkBatteryOptimization: () => Promise<{ exempted: boolean; platform: string; message?: string }>;
|
|
64
80
|
requestBatteryOptimizationExemption: () => Promise<boolean>;
|
|
65
81
|
startTracking: (config?: TrackingConfig) => Promise<void>;
|
|
66
|
-
stopTracking: () => Promise<void>;
|
|
82
|
+
stopTracking: (options?: StopTrackingOptions) => Promise<void>;
|
|
67
83
|
resumeTracking: () => Promise<void>;
|
|
68
84
|
getReport: (sessionId: string) => Promise<AsleepReport>;
|
|
69
85
|
getReportList: (fromDate: string, toDate: string) => Promise<AsleepSession[]>;
|
|
70
86
|
getAverageReport: (fromDate: string, toDate: string) => Promise<AsleepAverageReport>;
|
|
71
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>;
|
|
72
91
|
requestAnalysis: () => Promise<AsleepAnalysisResult | AsleepAnalysisAck>;
|
|
73
92
|
hasRequiredPermissions: () => Promise<boolean>;
|
|
74
93
|
requestRequiredPermissions: () => Promise<boolean>;
|
|
@@ -108,6 +127,7 @@ export const useAsleepStore = createStore<InternalAsleepState>(() => ({
|
|
|
108
127
|
trackingStatus: initialTrackingStatus,
|
|
109
128
|
sessionId: null,
|
|
110
129
|
userId: null,
|
|
130
|
+
isUserConfigReady: false,
|
|
111
131
|
error: null,
|
|
112
132
|
analysisResult: null,
|
|
113
133
|
isAnalyzing: false,
|
|
@@ -133,6 +153,10 @@ const convertKeysToCamelCase = (value: any): any => {
|
|
|
133
153
|
return value;
|
|
134
154
|
};
|
|
135
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
|
+
|
|
136
160
|
type ErrorOptions = {
|
|
137
161
|
category?: AsleepErrorCategory;
|
|
138
162
|
sdkCode?: number;
|
|
@@ -153,7 +177,8 @@ export const normalizeError = (source: unknown, fallbackCode: string, options: E
|
|
|
153
177
|
caseName?: unknown;
|
|
154
178
|
})
|
|
155
179
|
: undefined;
|
|
156
|
-
const
|
|
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;
|
|
157
182
|
const message =
|
|
158
183
|
typeof payload?.message === "string"
|
|
159
184
|
? payload.message
|
|
@@ -172,9 +197,11 @@ export const normalizeError = (source: unknown, fallbackCode: string, options: E
|
|
|
172
197
|
options.sdkCode ??
|
|
173
198
|
(typeof payload?.sdkCode === "number"
|
|
174
199
|
? payload.sdkCode
|
|
175
|
-
:
|
|
176
|
-
?
|
|
177
|
-
:
|
|
200
|
+
: encoded
|
|
201
|
+
? Number(encoded[2])
|
|
202
|
+
: source instanceof AsleepError
|
|
203
|
+
? source.sdkCode
|
|
204
|
+
: undefined),
|
|
178
205
|
caseName:
|
|
179
206
|
options.caseName ??
|
|
180
207
|
(typeof payload?.caseName === "string"
|
|
@@ -225,6 +252,164 @@ const clearErrorIfUnchanged = (errorBefore: AsleepError | null) => {
|
|
|
225
252
|
if (current !== null && current === errorBefore) useAsleepStore.setState({ error: null });
|
|
226
253
|
};
|
|
227
254
|
|
|
255
|
+
type NativeCredentials = { apiKey?: string; appId?: string; appSecret?: string };
|
|
256
|
+
|
|
257
|
+
// Runtime guard for JS callers and casts that bypass the AsleepCredentials union.
|
|
258
|
+
const resolveCredentials = (config: AsleepCredentials): NativeCredentials => {
|
|
259
|
+
const { apiKey, appId, appSecret } = (config ?? {}) as { apiKey?: unknown; appId?: unknown; appSecret?: unknown };
|
|
260
|
+
const hasApiKey = apiKey !== undefined;
|
|
261
|
+
const hasToken = appId !== undefined || appSecret !== undefined;
|
|
262
|
+
if (hasApiKey && hasToken) {
|
|
263
|
+
return storeAndThrow(
|
|
264
|
+
new AsleepError("INVALID_ARGUMENT", "Pass either apiKey or appId/appSecret credentials, not both."),
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
if (!hasApiKey && !hasToken) {
|
|
268
|
+
return storeAndThrow(
|
|
269
|
+
new AsleepError("INVALID_ARGUMENT", "Credentials are required: pass apiKey or appId/appSecret."),
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
const isNonEmpty = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
273
|
+
if (hasApiKey) {
|
|
274
|
+
if (!isNonEmpty(apiKey))
|
|
275
|
+
return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "apiKey must be a non-empty string."));
|
|
276
|
+
return { apiKey };
|
|
277
|
+
}
|
|
278
|
+
if (!isNonEmpty(appId) || !isNonEmpty(appSecret)) {
|
|
279
|
+
return storeAndThrow(new AsleepError("INVALID_ARGUMENT", "appId and appSecret must both be non-empty strings."));
|
|
280
|
+
}
|
|
281
|
+
return { appId, appSecret };
|
|
282
|
+
};
|
|
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
|
+
|
|
228
413
|
const normalizeReport = (report: any, sessionId: string): AsleepReport => {
|
|
229
414
|
const converted = convertKeysToCamelCase(report);
|
|
230
415
|
if (converted && !converted.session && converted.sessionId) {
|
|
@@ -251,6 +436,8 @@ const normalizeReport = (report: any, sessionId: string): AsleepReport => {
|
|
|
251
436
|
|
|
252
437
|
export const asleepActions: AsleepActions = {
|
|
253
438
|
setup: async (config) => {
|
|
439
|
+
const credentials = resolveCredentials(config);
|
|
440
|
+
const productInfo = resolveProductInfo(config.productInfo);
|
|
254
441
|
const state = useAsleepStore.getState();
|
|
255
442
|
if (state.setupStatus === "inProgress") {
|
|
256
443
|
storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
|
|
@@ -261,9 +448,20 @@ export const asleepActions: AsleepActions = {
|
|
|
261
448
|
|
|
262
449
|
const errorBefore = state.error;
|
|
263
450
|
addLog("[setup] Start");
|
|
264
|
-
|
|
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 });
|
|
265
454
|
try {
|
|
266
|
-
|
|
455
|
+
// Credentials travel as one record: Expo's Kotlin AsyncFunction accepts at
|
|
456
|
+
// most eight parameters including the promise.
|
|
457
|
+
await AsleepModule.setup(
|
|
458
|
+
credentials,
|
|
459
|
+
config.baseUrl,
|
|
460
|
+
config.callbackUrl,
|
|
461
|
+
config.service,
|
|
462
|
+
config.enableODA,
|
|
463
|
+
productInfo,
|
|
464
|
+
);
|
|
267
465
|
useAsleepStore.setState({
|
|
268
466
|
setupStatus: "complete",
|
|
269
467
|
isODAEnabled: config.enableODA || false,
|
|
@@ -277,6 +475,7 @@ export const asleepActions: AsleepActions = {
|
|
|
277
475
|
},
|
|
278
476
|
|
|
279
477
|
initAsleepConfig: async (config) => {
|
|
478
|
+
const credentials = resolveCredentials(config);
|
|
280
479
|
const state = useAsleepStore.getState();
|
|
281
480
|
if (state.setupStatus === "inProgress") {
|
|
282
481
|
return storeAndThrow(new AsleepError("OPERATION_IN_PROGRESS", "Setup is already in progress."));
|
|
@@ -286,14 +485,31 @@ export const asleepActions: AsleepActions = {
|
|
|
286
485
|
// while trackingStatus is "tracking" (v1 behavior the restore flow relies on).
|
|
287
486
|
const errorBefore = state.error;
|
|
288
487
|
addLog("[initAsleepConfig] Start");
|
|
289
|
-
useAsleepStore.setState({ setupStatus: "inProgress" });
|
|
488
|
+
useAsleepStore.setState({ setupStatus: "inProgress", isUserConfigReady: false });
|
|
290
489
|
try {
|
|
291
|
-
await AsleepModule.initAsleepConfig(
|
|
292
|
-
|
|
490
|
+
const result = await AsleepModule.initAsleepConfig(
|
|
491
|
+
credentials.apiKey,
|
|
492
|
+
credentials.appId,
|
|
493
|
+
credentials.appSecret,
|
|
494
|
+
config.userId,
|
|
495
|
+
config.baseUrl,
|
|
496
|
+
config.callbackUrl,
|
|
497
|
+
);
|
|
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
|
+
});
|
|
293
506
|
clearErrorIfUnchanged(errorBefore);
|
|
294
507
|
addLog("[initAsleepConfig] Success");
|
|
295
508
|
} catch (error) {
|
|
296
|
-
return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, {
|
|
509
|
+
return guardedFailure(error, "INIT_CONFIG_FAILED", errorBefore, {
|
|
510
|
+
setupStatus: "idle",
|
|
511
|
+
isUserConfigReady: false,
|
|
512
|
+
});
|
|
297
513
|
}
|
|
298
514
|
},
|
|
299
515
|
|
|
@@ -414,10 +630,13 @@ export const asleepActions: AsleepActions = {
|
|
|
414
630
|
}
|
|
415
631
|
},
|
|
416
632
|
|
|
417
|
-
stopTracking: async () => {
|
|
633
|
+
stopTracking: async (options) => {
|
|
634
|
+
const range = resolveAnalysisRange(options?.analysisRange);
|
|
418
635
|
const errorBefore = useAsleepStore.getState().error;
|
|
419
636
|
try {
|
|
420
|
-
|
|
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);
|
|
421
640
|
useAsleepStore.setState({
|
|
422
641
|
didClose: true,
|
|
423
642
|
...(typeof result === "string" && result ? { sessionId: result } : {}),
|
|
@@ -509,6 +728,49 @@ export const asleepActions: AsleepActions = {
|
|
|
509
728
|
}
|
|
510
729
|
},
|
|
511
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
|
+
|
|
512
774
|
requestAnalysis: async () => {
|
|
513
775
|
const errorBefore = useAsleepStore.getState().error;
|
|
514
776
|
useAsleepStore.setState({ isAnalyzing: true });
|
|
@@ -631,14 +893,22 @@ const transitionForEvent = (
|
|
|
631
893
|
): { partial: Partial<InternalAsleepState>; log: string; requestAnalysis?: boolean } => {
|
|
632
894
|
switch (eventType) {
|
|
633
895
|
case "onUserJoined":
|
|
634
|
-
|
|
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
|
+
};
|
|
635
905
|
case "onUserJoinFailed":
|
|
636
906
|
return {
|
|
637
|
-
partial: { error: normalizeError(payload, "USER_JOIN_FAILED") },
|
|
907
|
+
partial: { error: normalizeError(payload, "USER_JOIN_FAILED"), isUserConfigReady: false },
|
|
638
908
|
log: `[onUserJoinFailed] error: ${payload?.message ?? payload?.detail ?? payload?.error ?? "Unknown error"}`,
|
|
639
909
|
};
|
|
640
910
|
case "onUserDeleted":
|
|
641
|
-
return { partial: { userId: null }, log: `[onUserDeleted] userId: ${payload.userId}` };
|
|
911
|
+
return { partial: { userId: null, isUserConfigReady: false }, log: `[onUserDeleted] userId: ${payload.userId}` };
|
|
642
912
|
case "onTrackingCreated":
|
|
643
913
|
return {
|
|
644
914
|
partial: { trackingStatus: "tracking", ...(payload?.sessionId ? { sessionId: payload.sessionId } : {}) },
|
|
@@ -698,8 +968,9 @@ const transitionForEvent = (
|
|
|
698
968
|
if (terminal) {
|
|
699
969
|
return {
|
|
700
970
|
partial: {
|
|
701
|
-
// iOS
|
|
702
|
-
//
|
|
971
|
+
// iOS closeSessionSilently (upload 4xx) does not emit didClose, and
|
|
972
|
+
// start failures never create a session, so this branch must clear
|
|
973
|
+
// the projected session state itself.
|
|
703
974
|
error,
|
|
704
975
|
trackingStatus: "idle",
|
|
705
976
|
isAnalyzing: false,
|
|
@@ -712,8 +983,8 @@ const transitionForEvent = (
|
|
|
712
983
|
if (recordingDead) {
|
|
713
984
|
return {
|
|
714
985
|
partial: {
|
|
715
|
-
// iOS
|
|
716
|
-
//
|
|
986
|
+
// iOS audioInitializationFailed and interruptionRecoveryFailed stop
|
|
987
|
+
// the recorder but keep the native session open (didClose=false).
|
|
717
988
|
error,
|
|
718
989
|
trackingStatus: "idle",
|
|
719
990
|
isAnalyzing: false,
|
|
@@ -725,8 +996,8 @@ const transitionForEvent = (
|
|
|
725
996
|
}
|
|
726
997
|
if (recoveryRequired) {
|
|
727
998
|
return {
|
|
728
|
-
// iOS
|
|
729
|
-
//
|
|
999
|
+
// iOS cannotActivateInBackground keeps the session alive. 3.3.x also
|
|
1000
|
+
// retries on foreground; only a later upload proves recovery.
|
|
730
1001
|
partial: { error, trackingStatus: "recoveryRequired" },
|
|
731
1002
|
log: `[onTrackingError] error: ${error.message}`,
|
|
732
1003
|
};
|
|
@@ -739,8 +1010,9 @@ const transitionForEvent = (
|
|
|
739
1010
|
return {
|
|
740
1011
|
partial: {
|
|
741
1012
|
error: null,
|
|
742
|
-
// iOS 3.2.1 can emit didResume twice
|
|
743
|
-
//
|
|
1013
|
+
// iOS 3.2.1-3.3.0 can emit didResume twice, and recovery paths can
|
|
1014
|
+
// resume without a prior pause. Always clear the error, but mutate
|
|
1015
|
+
// the paused state only for the first event.
|
|
744
1016
|
...(state.trackingStatus === "paused" ? { trackingStatus: "tracking" as const } : {}),
|
|
745
1017
|
},
|
|
746
1018
|
log:
|
package/src/index.ts
CHANGED
|
@@ -40,19 +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,
|
|
47
|
+
AsleepCredentials,
|
|
46
48
|
AsleepErrorCategory,
|
|
47
49
|
AsleepEventType,
|
|
50
|
+
AsleepGender,
|
|
48
51
|
AsleepNeverSleptSession,
|
|
52
|
+
AsleepProductIdentifierType,
|
|
53
|
+
AsleepProductInfo,
|
|
49
54
|
AsleepReport,
|
|
50
55
|
AsleepSession,
|
|
51
56
|
AsleepSetupConfig,
|
|
52
57
|
AsleepSleptSession,
|
|
53
58
|
AsleepStat,
|
|
59
|
+
AsleepUserMetadata,
|
|
54
60
|
AudioSessionOption,
|
|
61
|
+
ReanalyzeOptions,
|
|
55
62
|
SetupStatus,
|
|
63
|
+
StopTrackingOptions,
|
|
56
64
|
TrackingConfig,
|
|
57
65
|
TrackingStatus,
|
|
58
66
|
} from "./Asleep.types";
|