react-native-asleep 1.0.17 → 1.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.md +69 -304
- package/android/src/main/java/ai/asleep/reactnative/AsleepModule.kt +36 -17
- package/build/Asleep.types.d.ts +42 -0
- package/build/Asleep.types.d.ts.map +1 -1
- package/build/Asleep.types.js.map +1 -1
- package/build/AsleepStore.d.ts +6 -3
- package/build/AsleepStore.d.ts.map +1 -1
- package/build/AsleepStore.js +312 -115
- package/build/AsleepStore.js.map +1 -1
- package/build/index.d.ts +9 -4
- package/build/index.d.ts.map +1 -1
- package/build/index.js +10 -9
- package/build/index.js.map +1 -1
- package/ios/AsleepModule.swift +60 -4
- package/package.json +6 -23
- package/src/Asleep.types.ts +51 -1
- package/src/AsleepStore.ts +319 -133
- package/src/index.ts +19 -7
package/build/AsleepStore.js
CHANGED
|
@@ -4,6 +4,15 @@ import { EventEmitter } from "expo-modules-core";
|
|
|
4
4
|
import { Platform, PermissionsAndroid } from "react-native";
|
|
5
5
|
import AsleepModule from "./AsleepModule";
|
|
6
6
|
const emitter = new EventEmitter(AsleepModule);
|
|
7
|
+
// All dev-only warnings below are gated with an inline
|
|
8
|
+
// `typeof __DEV__ !== "undefined" && __DEV__` check rather than a helper
|
|
9
|
+
// function. Metro's inline plugin substitutes the bare `__DEV__` identifier
|
|
10
|
+
// for the literal at build time, then constant-folds `typeof <literal>` and
|
|
11
|
+
// the `&&` so the entire branch is dead-code-eliminated in production
|
|
12
|
+
// bundles. Wrapping the check in a function (e.g. `if (isDev())`) defeats
|
|
13
|
+
// that DCE because Metro does not constant-fold through call expressions.
|
|
14
|
+
// The `typeof` guard also keeps the module importable from plain Node,
|
|
15
|
+
// custom bundlers, or unconfigured jest setups without a ReferenceError.
|
|
7
16
|
// Error codes emitted on onTrackingFailed for which the native SDK has already
|
|
8
17
|
// terminated the session and will not deliver onTrackingClosed. JS must clear
|
|
9
18
|
// tracking state itself when one of these arrives. See AGENTS.md "Native Behavior
|
|
@@ -12,6 +21,42 @@ const TERMINAL_TRACKING_ERROR_CODES = new Set([
|
|
|
12
21
|
"UPLOAD_TRACKING_TERMINATED", // iOS 403/429 closeSessionSilently; Android errorCode 23499
|
|
13
22
|
"INTERRUPTION_RECOVERY_FAILED", // iOS 3 failed auto-resume attempts (3.2.0+)
|
|
14
23
|
]);
|
|
24
|
+
// iOS SDK 3.2.0 stops the recorder without closing the native session when
|
|
25
|
+
// audio engine initialization fails. The session must be stopped and restarted.
|
|
26
|
+
const RECORDING_DEAD_ERROR_CODES = new Set(["AUDIO_INITIALIZATION_FAILED"]);
|
|
27
|
+
// iOS SDK 3.2.0 reports this when the audio engine cannot restart in the
|
|
28
|
+
// background. The consumer must call resumeTracking() after returning foreground.
|
|
29
|
+
const RECOVERY_REQUIRED_ERROR_CODES = new Set(["CANNOT_ACTIVATE_IN_BACKGROUND"]);
|
|
30
|
+
// Numeric-code twin of TERMINAL_TRACKING_ERROR_CODES, matched against the
|
|
31
|
+
// `sdkCode` payload field. Android SDK 3.2.x AsleepCore.onErrorCodeReceived
|
|
32
|
+
// tears the session down and dual-fires onFail + onFinish for exactly these
|
|
33
|
+
// codes (the native module suppresses the duplicate onFinish), so JS must
|
|
34
|
+
// clear tracking state here or isTracking stays stuck true.
|
|
35
|
+
// Must stay in sync with the Kotlin TERMINAL_TRACKING_ERROR_CODES companion
|
|
36
|
+
// set in android/src/main/java/ai/asleep/reactnative/AsleepModule.kt.
|
|
37
|
+
const TERMINAL_TRACKING_SDK_CODES = new Set([
|
|
38
|
+
11003, // ERR_AUDIO
|
|
39
|
+
22000,
|
|
40
|
+
22401,
|
|
41
|
+
22409,
|
|
42
|
+
22422,
|
|
43
|
+
22500, // ERR_CREATE_*
|
|
44
|
+
23499, // ERR_UPLOAD_TRACKING_TERMINATED
|
|
45
|
+
24000,
|
|
46
|
+
24400,
|
|
47
|
+
24401,
|
|
48
|
+
24403,
|
|
49
|
+
24404,
|
|
50
|
+
24500, // ERR_CLOSE_*
|
|
51
|
+
]);
|
|
52
|
+
// Upload failures the native session survives: absent from the AsleepCore
|
|
53
|
+
// terminal set above, so the Android SDK 3.2.x keeps the session open and later
|
|
54
|
+
// uploads continue (UploadDataTask retries 5xx internally before reporting).
|
|
55
|
+
// Deliberately small — only codes verifiable in upstream sources.
|
|
56
|
+
const TRANSIENT_TRACKING_SDK_CODES = new Set([
|
|
57
|
+
23000, // ERR_UPLOAD_FAILED
|
|
58
|
+
23500, // ERR_UPLOAD_SERVER_ERROR
|
|
59
|
+
]);
|
|
15
60
|
const convertKeysToCamelCase = (obj) => {
|
|
16
61
|
if (Array.isArray(obj)) {
|
|
17
62
|
return obj.map(convertKeysToCamelCase);
|
|
@@ -30,7 +75,9 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
30
75
|
didClose: false,
|
|
31
76
|
isTracking: AsleepModule.isTracking ? AsleepModule.isTracking() : false,
|
|
32
77
|
isTrackingPaused: false,
|
|
78
|
+
isRecoveryRequired: false,
|
|
33
79
|
error: null,
|
|
80
|
+
errorInfo: null,
|
|
34
81
|
userId: null,
|
|
35
82
|
sessionId: null,
|
|
36
83
|
showDebugLog: false,
|
|
@@ -61,20 +108,23 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
61
108
|
throw new Error("Cannot execute setup while tracking is in progress.");
|
|
62
109
|
}
|
|
63
110
|
addLog("[setup] Start");
|
|
64
|
-
set({ isSetupInProgress: true, error: null });
|
|
111
|
+
set({ isSetupInProgress: true, error: null, errorInfo: null });
|
|
65
112
|
await AsleepModule.setup(config.apiKey, config.baseUrl, config.callbackUrl, config.service, config.enableODA);
|
|
66
|
-
// Store ODA enabled state
|
|
113
|
+
// Store ODA enabled state. Clearing `error` on success keeps the
|
|
114
|
+
// reactive `useAsleep().error` field aligned with the actual SDK status
|
|
115
|
+
// (no stale failure messages after a successful retry).
|
|
67
116
|
set({
|
|
68
117
|
isODAEnabled: config.enableODA || false,
|
|
69
118
|
isInitialized: true,
|
|
70
119
|
isSetupInProgress: false,
|
|
71
120
|
isSetupComplete: true,
|
|
121
|
+
error: null,
|
|
122
|
+
errorInfo: null,
|
|
72
123
|
});
|
|
73
124
|
addLog(`[setup] Success - ODA enabled: ${config.enableODA || false}`);
|
|
74
125
|
}
|
|
75
126
|
catch (error) {
|
|
76
|
-
|
|
77
|
-
set({ error: error.message, isSetupInProgress: false });
|
|
127
|
+
set({ error: error.message, errorInfo: null, isSetupInProgress: false });
|
|
78
128
|
throw error;
|
|
79
129
|
}
|
|
80
130
|
},
|
|
@@ -83,13 +133,12 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
83
133
|
const { addLog } = get();
|
|
84
134
|
addLog("[initAsleepConfig] Start");
|
|
85
135
|
const result = await AsleepModule.initAsleepConfig(config.apiKey, config.userId, config.baseUrl, config.callbackUrl);
|
|
86
|
-
set({ isInitialized: true });
|
|
136
|
+
set({ isInitialized: true, error: null, errorInfo: null });
|
|
87
137
|
addLog("[initAsleepConfig] Success");
|
|
88
138
|
return result;
|
|
89
139
|
}
|
|
90
140
|
catch (error) {
|
|
91
|
-
|
|
92
|
-
set({ error: error.message });
|
|
141
|
+
set({ error: error.message, errorInfo: null });
|
|
93
142
|
throw error;
|
|
94
143
|
}
|
|
95
144
|
},
|
|
@@ -120,8 +169,7 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
120
169
|
};
|
|
121
170
|
}
|
|
122
171
|
catch (error) {
|
|
123
|
-
|
|
124
|
-
set({ error: error.message });
|
|
172
|
+
set({ error: error.message, errorInfo: null });
|
|
125
173
|
throw error;
|
|
126
174
|
}
|
|
127
175
|
},
|
|
@@ -188,6 +236,10 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
188
236
|
* @throws Error if prerequisites are not met or tracking is already in progress
|
|
189
237
|
*/
|
|
190
238
|
startTracking: async (config) => {
|
|
239
|
+
// Snapshot so the catch can tell a verdict published DURING this call
|
|
240
|
+
// (Android fires classified onTrackingFailed before rejecting the same
|
|
241
|
+
// promise) apart from a stale one left by an earlier failure.
|
|
242
|
+
const errorInfoBefore = get().errorInfo;
|
|
191
243
|
try {
|
|
192
244
|
const { requestRequiredPermissions, addLog, isODAEnabled, isSetupInProgress, hasCheckedStatus } = get();
|
|
193
245
|
// Enforce that checkAndRestoreTracking must be called first
|
|
@@ -237,7 +289,10 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
237
289
|
didClose: false,
|
|
238
290
|
isTracking: true,
|
|
239
291
|
isAnalyzing: false,
|
|
292
|
+
isRecoveryRequired: false,
|
|
240
293
|
trackingStartTime: new Date(),
|
|
294
|
+
error: null,
|
|
295
|
+
errorInfo: null,
|
|
241
296
|
});
|
|
242
297
|
await AsleepModule.startTracking(config);
|
|
243
298
|
if (isODAEnabled) {
|
|
@@ -249,9 +304,14 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
249
304
|
addLog("[startTracking] Success");
|
|
250
305
|
}
|
|
251
306
|
catch (error) {
|
|
252
|
-
|
|
307
|
+
// Preserve only a verdict that arrived during this call — the raw
|
|
308
|
+
// rejection message carries strictly less information than the
|
|
309
|
+
// numeric-code verdict. Reference inequality against the snapshot
|
|
310
|
+
// excludes stale verdicts, so guard failures still write the new error.
|
|
311
|
+
const nowInfo = get().errorInfo;
|
|
312
|
+
const classified = nowInfo !== null && nowInfo !== errorInfoBefore;
|
|
253
313
|
set({
|
|
254
|
-
error: error.message,
|
|
314
|
+
...(classified ? {} : { error: error.message, errorInfo: null }),
|
|
255
315
|
isTracking: false,
|
|
256
316
|
isAnalyzing: false,
|
|
257
317
|
trackingStartTime: null,
|
|
@@ -260,6 +320,8 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
260
320
|
}
|
|
261
321
|
},
|
|
262
322
|
stopTracking: async () => {
|
|
323
|
+
// Same dual-signal race as startTracking; see the snapshot rationale there.
|
|
324
|
+
const errorInfoBefore = get().errorInfo;
|
|
263
325
|
try {
|
|
264
326
|
const { addLog } = get();
|
|
265
327
|
addLog("[stopTracking] Start");
|
|
@@ -269,23 +331,45 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
269
331
|
...(result ? { sessionId: result } : {}),
|
|
270
332
|
isTracking: false,
|
|
271
333
|
isAnalyzing: false,
|
|
334
|
+
isRecoveryRequired: false,
|
|
272
335
|
trackingStartTime: null,
|
|
336
|
+
error: null,
|
|
337
|
+
errorInfo: null,
|
|
273
338
|
});
|
|
274
339
|
addLog(`[stopTracking] Success - result: ${result}`);
|
|
275
340
|
}
|
|
276
341
|
catch (error) {
|
|
277
|
-
|
|
278
|
-
|
|
342
|
+
const nowInfo = get().errorInfo;
|
|
343
|
+
if (nowInfo === null || nowInfo === errorInfoBefore)
|
|
344
|
+
set({ error: error.message, errorInfo: null });
|
|
279
345
|
throw error;
|
|
280
346
|
}
|
|
281
347
|
},
|
|
348
|
+
resumeTracking: async () => {
|
|
349
|
+
if (Platform.OS !== "ios") {
|
|
350
|
+
throw Object.assign(new Error("resumeTracking is only supported on iOS."), {
|
|
351
|
+
name: "AsleepPlatformError",
|
|
352
|
+
code: "UNSUPPORTED_PLATFORM",
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
await AsleepModule.resumeTracking();
|
|
356
|
+
},
|
|
282
357
|
getReport: async (sessionId) => {
|
|
358
|
+
// Snapshot the error before the await so we only clear it on success
|
|
359
|
+
// if no concurrent failure (e.g. onTrackingFailed firing during the
|
|
360
|
+
// network round-trip) wrote a different error in the meantime.
|
|
361
|
+
const errorBefore = get().error;
|
|
283
362
|
try {
|
|
284
363
|
const { addLog } = get();
|
|
285
364
|
addLog(`[getReport] sessionId: ${sessionId}`);
|
|
286
365
|
const report = await AsleepModule.getReport(sessionId);
|
|
287
366
|
const convertedReport = convertKeysToCamelCase(report);
|
|
288
367
|
addLog("[getReport] Success");
|
|
368
|
+
// Guard so a successful query after a clean run does not spam an empty
|
|
369
|
+
// notification, and so we never clobber an unrelated tracking error
|
|
370
|
+
// that arrived during the await.
|
|
371
|
+
if (get().error !== null && get().error === errorBefore)
|
|
372
|
+
set({ error: null, errorInfo: null });
|
|
289
373
|
// Ensure the report has the expected AsleepReport structure
|
|
290
374
|
// Handle cases where native modules might return data in different formats
|
|
291
375
|
if (convertedReport && !convertedReport.session && convertedReport.sessionId) {
|
|
@@ -312,12 +396,18 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
312
396
|
return convertedReport;
|
|
313
397
|
}
|
|
314
398
|
catch (error) {
|
|
315
|
-
|
|
316
|
-
|
|
399
|
+
// Silent return on failure is a public-API quirk preserved for v1.x
|
|
400
|
+
// compat (v2.0 throws). Surface a dev-only warn so the consumer's
|
|
401
|
+
// Metro log still shows the failure when they're debugging without
|
|
402
|
+
// observing `useAsleep().error` directly.
|
|
403
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
404
|
+
console.warn("[Asleep] getReport failed:", error);
|
|
405
|
+
set({ error: error.message, errorInfo: null });
|
|
317
406
|
return null;
|
|
318
407
|
}
|
|
319
408
|
},
|
|
320
409
|
getReportList: async (fromDate, toDate) => {
|
|
410
|
+
const errorBefore = get().error;
|
|
321
411
|
try {
|
|
322
412
|
const { addLog } = get();
|
|
323
413
|
addLog(`[getReportList] fromDate: ${fromDate}, toDate: ${toDate}`);
|
|
@@ -337,39 +427,48 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
337
427
|
};
|
|
338
428
|
});
|
|
339
429
|
addLog("[getReportList] Success");
|
|
430
|
+
if (get().error !== null && get().error === errorBefore)
|
|
431
|
+
set({ error: null, errorInfo: null });
|
|
340
432
|
return convertedList;
|
|
341
433
|
}
|
|
342
434
|
catch (error) {
|
|
343
|
-
|
|
344
|
-
|
|
435
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
436
|
+
console.warn("[Asleep] getReportList failed:", error);
|
|
437
|
+
set({ error: error.message, errorInfo: null });
|
|
345
438
|
return [];
|
|
346
439
|
}
|
|
347
440
|
},
|
|
348
441
|
deleteSession: async (sessionId) => {
|
|
442
|
+
const errorBefore = get().error;
|
|
349
443
|
try {
|
|
350
444
|
const { addLog } = get();
|
|
351
445
|
addLog(`[deleteSession] sessionId: ${sessionId}`);
|
|
352
446
|
await AsleepModule.deleteSession(sessionId);
|
|
353
447
|
addLog("[deleteSession] Success");
|
|
448
|
+
if (get().error !== null && get().error === errorBefore)
|
|
449
|
+
set({ error: null, errorInfo: null });
|
|
354
450
|
}
|
|
355
451
|
catch (error) {
|
|
356
|
-
|
|
357
|
-
set({ error: error.message });
|
|
452
|
+
set({ error: error.message, errorInfo: null });
|
|
358
453
|
throw error;
|
|
359
454
|
}
|
|
360
455
|
},
|
|
361
456
|
getAverageReport: async (fromDate, toDate) => {
|
|
457
|
+
const errorBefore = get().error;
|
|
362
458
|
try {
|
|
363
459
|
const { addLog } = get();
|
|
364
460
|
addLog(`[getAverageReport] fromDate: ${fromDate}, toDate: ${toDate}`);
|
|
365
461
|
const averageReport = await AsleepModule.getAverageReport(fromDate, toDate);
|
|
366
462
|
const convertedReport = convertKeysToCamelCase(averageReport);
|
|
367
463
|
addLog("[getAverageReport] Success");
|
|
464
|
+
if (get().error !== null && get().error === errorBefore)
|
|
465
|
+
set({ error: null, errorInfo: null });
|
|
368
466
|
return convertedReport;
|
|
369
467
|
}
|
|
370
468
|
catch (error) {
|
|
371
|
-
|
|
372
|
-
|
|
469
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
470
|
+
console.warn("[Asleep] getAverageReport failed:", error);
|
|
471
|
+
set({ error: error.message, errorInfo: null });
|
|
373
472
|
return null;
|
|
374
473
|
}
|
|
375
474
|
},
|
|
@@ -377,7 +476,9 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
377
476
|
* @deprecated Use requestRequiredPermissions instead. This method will be removed in a future version.
|
|
378
477
|
*/
|
|
379
478
|
requestMicrophonePermission: async () => {
|
|
380
|
-
|
|
479
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
480
|
+
console.warn("[Asleep] requestMicrophonePermission is deprecated. Please use requestRequiredPermissions instead.");
|
|
481
|
+
}
|
|
381
482
|
return get().requestRequiredPermissions();
|
|
382
483
|
},
|
|
383
484
|
requestRequiredPermissions: async () => {
|
|
@@ -400,45 +501,42 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
400
501
|
return audioGranted && notificationGranted;
|
|
401
502
|
}
|
|
402
503
|
catch (err) {
|
|
403
|
-
|
|
504
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
505
|
+
console.warn("[Asleep] Permission request error:", err);
|
|
404
506
|
return false;
|
|
405
507
|
}
|
|
406
508
|
}
|
|
407
509
|
// iOS uses native implementation
|
|
408
510
|
return AsleepModule.requestRequiredPermissions();
|
|
409
511
|
},
|
|
410
|
-
setCustomNotification: async (
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
else {
|
|
415
|
-
console.warn("setCustomNotification is not supported on this platform");
|
|
416
|
-
}
|
|
512
|
+
setCustomNotification: async (_title, _text) => {
|
|
513
|
+
// Native method removed; notification config now flows through startTracking options.
|
|
514
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
515
|
+
console.warn("[Asleep] setCustomNotification is deprecated and a no-op; pass `{ android: { notification: { title, text, icon } } }` to startTracking() instead");
|
|
417
516
|
},
|
|
418
517
|
enableLog: (print) => {
|
|
518
|
+
if (Platform.OS === "ios")
|
|
519
|
+
AsleepModule.enableLog(print);
|
|
419
520
|
set({ showDebugLog: print });
|
|
420
521
|
},
|
|
421
522
|
requestAnalysis: async () => {
|
|
422
523
|
try {
|
|
423
|
-
const { addLog } = get();
|
|
524
|
+
const { addLog, showDebugLog } = get();
|
|
424
525
|
addLog("[requestAnalysis] Start");
|
|
425
|
-
set({ isAnalyzing: true });
|
|
526
|
+
set({ isAnalyzing: true, error: null, errorInfo: null });
|
|
426
527
|
const result = await AsleepModule.requestAnalysis();
|
|
427
528
|
const convertedResult = convertKeysToCamelCase(result);
|
|
428
|
-
//
|
|
429
|
-
// Android
|
|
430
|
-
// iOS
|
|
431
|
-
if (
|
|
432
|
-
|
|
433
|
-
set({ analysisResult: convertedResult, isAnalyzing: false });
|
|
434
|
-
}
|
|
435
|
-
// For iOS, isAnalyzing will be set to false when onAnalysisResult event fires
|
|
436
|
-
addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
|
|
529
|
+
// analysisResult and isAnalyzing are owned by the onAnalysisResult event handler on both
|
|
530
|
+
// platforms. Android resolves the promise with the full session AND fires the event;
|
|
531
|
+
// iOS resolves with an ack only. Writing state here would double-update on Android.
|
|
532
|
+
if (showDebugLog)
|
|
533
|
+
addLog(`[requestAnalysis] Request sent - ${JSON.stringify(convertedResult)}`);
|
|
437
534
|
return convertedResult;
|
|
438
535
|
}
|
|
439
536
|
catch (error) {
|
|
440
|
-
|
|
441
|
-
|
|
537
|
+
if (typeof __DEV__ !== "undefined" && __DEV__)
|
|
538
|
+
console.warn("[Asleep] requestAnalysis failed:", error);
|
|
539
|
+
set({ error: error.message, errorInfo: null, isAnalyzing: false });
|
|
442
540
|
return null;
|
|
443
541
|
}
|
|
444
542
|
},
|
|
@@ -453,8 +551,10 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
453
551
|
return Math.floor((Date.now() - trackingStartTime.getTime()) / (1000 * 60));
|
|
454
552
|
},
|
|
455
553
|
// internal actions
|
|
456
|
-
setError
|
|
457
|
-
|
|
554
|
+
// setError takes a raw string, so any structured classification is stale;
|
|
555
|
+
// reset errorInfo rather than let a previous event's category linger.
|
|
556
|
+
setError: (error) => set({ error, errorInfo: null }),
|
|
557
|
+
clearError: () => set({ error: null, errorInfo: null }),
|
|
458
558
|
setUserId: (userId) => set({ userId }),
|
|
459
559
|
setSessionId: (sessionId) => set({ sessionId }),
|
|
460
560
|
setIsTracking: (isTracking) => set({ isTracking }),
|
|
@@ -469,43 +569,44 @@ export const useAsleepStore = create()(subscribeWithSelector((set, get) => ({
|
|
|
469
569
|
setHasCheckedStatus: (checked) => set({ hasCheckedStatus: checked }),
|
|
470
570
|
setHasCheckedBatteryOptimization: (checked) => set({ hasCheckedBatteryOptimization: checked }),
|
|
471
571
|
addLog: (log) => {
|
|
572
|
+
// Zero-cost when the consumer has not opted into debug logging. Without
|
|
573
|
+
// this guard, every native event handler would cause a spurious
|
|
574
|
+
// subscriber notification on top of any actual data update.
|
|
472
575
|
const { showDebugLog } = get();
|
|
576
|
+
if (!showDebugLog)
|
|
577
|
+
return;
|
|
473
578
|
const now = new Date();
|
|
474
579
|
const dateString = `${now.getHours().toString().padStart(2, "0")}:${now
|
|
475
580
|
.getMinutes()
|
|
476
581
|
.toString()
|
|
477
582
|
.padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
|
|
478
583
|
const formattedLog = `[${dateString}]${log}`;
|
|
479
|
-
|
|
480
|
-
console.log(`[Asleep]${formattedLog}`);
|
|
481
|
-
}
|
|
584
|
+
console.log(`[Asleep]${formattedLog}`);
|
|
482
585
|
set({ log: formattedLog });
|
|
483
586
|
},
|
|
484
587
|
})));
|
|
485
|
-
//
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
//
|
|
588
|
+
// Ref-counted registration. Each caller (useAsleep effect, background context,
|
|
589
|
+
// etc.) increments on entry and decrements via the returned cleanup. Native
|
|
590
|
+
// listeners only attach on 0→1 and detach on the final 1→0, so concurrent
|
|
591
|
+
// consumers cannot tear each other's subscriptions down.
|
|
592
|
+
let refCount = 0;
|
|
593
|
+
let teardown = null;
|
|
489
594
|
export const initializeAsleepListeners = () => {
|
|
490
|
-
//
|
|
491
|
-
|
|
492
|
-
|
|
595
|
+
// Cold start when no teardown is installed. `teardown` is the single source
|
|
596
|
+
// of truth for "listeners are currently attached"; refCount is just an
|
|
597
|
+
// increment-only counter for cleanup balancing. Always incrementing
|
|
598
|
+
// (instead of assigning =1 on cold start) keeps the count correct even if
|
|
599
|
+
// a future change introduces an async seam between this check and the
|
|
600
|
+
// listener registration below.
|
|
601
|
+
if (teardown) {
|
|
602
|
+
refCount++;
|
|
603
|
+
return makeCleanup();
|
|
493
604
|
}
|
|
494
605
|
const store = useAsleepStore.getState();
|
|
495
|
-
const { addLog, setUserId,
|
|
496
|
-
//
|
|
497
|
-
//
|
|
498
|
-
//
|
|
499
|
-
// subscribers are notified once instead of four times.
|
|
500
|
-
const clearTrackingState = () => {
|
|
501
|
-
useAsleepStore.setState({
|
|
502
|
-
isTracking: false,
|
|
503
|
-
isAnalyzing: false,
|
|
504
|
-
didClose: true,
|
|
505
|
-
trackingStartTime: null,
|
|
506
|
-
});
|
|
507
|
-
};
|
|
508
|
-
// event handlers
|
|
606
|
+
const { addLog, setUserId, setIsTrackingPaused, setIsSetupInProgress } = store;
|
|
607
|
+
// event handlers — each native SDK event corresponds to one logical state
|
|
608
|
+
// transaction. Use a single useAsleepStore.setState per handler so consumers
|
|
609
|
+
// subscribed via useAsleep re-render once per event, not once per field.
|
|
509
610
|
const handlers = {
|
|
510
611
|
// Connected: iOS userDidJoin, Android onSuccess (AsleepConfigListener)
|
|
511
612
|
onUserJoined: (data) => {
|
|
@@ -515,7 +616,9 @@ export const initializeAsleepListeners = () => {
|
|
|
515
616
|
// Connected: iOS didFailUserJoin, Android onFail (AsleepConfigListener)
|
|
516
617
|
onUserJoinFailed: (error) => {
|
|
517
618
|
const errorString = JSON.stringify(error);
|
|
518
|
-
|
|
619
|
+
// Not a tracking-runtime failure; errorInfo stays reserved for
|
|
620
|
+
// onTrackingFailed classification.
|
|
621
|
+
useAsleepStore.setState({ error: errorString, errorInfo: null });
|
|
519
622
|
addLog(`[onUserJoinFailed] error: ${errorString}`);
|
|
520
623
|
},
|
|
521
624
|
// Connected: iOS userDidDelete, Android NOT IMPLEMENTED
|
|
@@ -525,48 +628,129 @@ export const initializeAsleepListeners = () => {
|
|
|
525
628
|
},
|
|
526
629
|
// Connected: iOS didCreate, Android onStart (AsleepTrackingListener)
|
|
527
630
|
onTrackingCreated: (data) => {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
}
|
|
631
|
+
useAsleepStore.setState({
|
|
632
|
+
isTracking: true,
|
|
633
|
+
...(data?.sessionId ? { sessionId: data.sessionId } : {}),
|
|
634
|
+
});
|
|
532
635
|
addLog(`[onTrackingCreated]${data?.sessionId ? ` sessionId: ${data.sessionId}` : ""}`);
|
|
533
636
|
},
|
|
534
637
|
// Connected: iOS didUpload, Android onPerform (AsleepTrackingListener)
|
|
535
638
|
// Triggers automatic analysis requests in both ODA and non-ODA modes
|
|
536
639
|
onTrackingUploaded: (data) => {
|
|
537
640
|
addLog(`[onTrackingUploaded] sequence: ${data.sequence}`);
|
|
641
|
+
// requestAnalysis() flips isAnalyzing internally; no separate setter
|
|
642
|
+
// needed before invoking it (avoids a duplicate subscriber notification).
|
|
538
643
|
const state = useAsleepStore.getState();
|
|
644
|
+
// A completed upload is the only positive proof that recording actually came
|
|
645
|
+
// back — didResume fires before the engine restart is even attempted, so it
|
|
646
|
+
// cannot be trusted to clear this.
|
|
647
|
+
if (state.isRecoveryRequired)
|
|
648
|
+
useAsleepStore.setState({ isRecoveryRequired: false });
|
|
649
|
+
const triggerAnalysis = () => state.requestAnalysis().catch((error) => {
|
|
650
|
+
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
651
|
+
state.setIsAnalyzing(false);
|
|
652
|
+
});
|
|
539
653
|
if (state.isODAEnabled && state.isTracking) {
|
|
540
|
-
|
|
541
|
-
state.requestAnalysis().catch((error) => {
|
|
542
|
-
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
543
|
-
state.setIsAnalyzing(false);
|
|
544
|
-
});
|
|
654
|
+
triggerAnalysis();
|
|
545
655
|
}
|
|
546
656
|
else if (!state.isODAEnabled && state.isTracking) {
|
|
547
657
|
if (data.sequence >= 10 && data.sequence % 10 === 1) {
|
|
548
|
-
|
|
549
|
-
state.requestAnalysis().catch((error) => {
|
|
550
|
-
addLog(`[onTrackingUploaded] Auto analysis failed: ${error.message}`);
|
|
551
|
-
state.setIsAnalyzing(false);
|
|
552
|
-
});
|
|
658
|
+
triggerAnalysis();
|
|
553
659
|
}
|
|
554
660
|
}
|
|
555
661
|
},
|
|
556
662
|
// Connected: iOS didClose, Android onFinish (AsleepTrackingListener)
|
|
557
663
|
onTrackingClosed: (data) => {
|
|
558
|
-
|
|
559
|
-
|
|
664
|
+
useAsleepStore.setState({
|
|
665
|
+
sessionId: data.sessionId,
|
|
666
|
+
isTracking: false,
|
|
667
|
+
isAnalyzing: false,
|
|
668
|
+
isRecoveryRequired: false,
|
|
669
|
+
didClose: true,
|
|
670
|
+
trackingStartTime: null,
|
|
671
|
+
});
|
|
560
672
|
addLog(`[onTrackingClosed] sessionId: ${data.sessionId}`);
|
|
561
673
|
},
|
|
562
674
|
// Connected: iOS didFail, Android onFail (AsleepTrackingListener)
|
|
675
|
+
// Four state buckets, each writing tracking state in the same setState as the
|
|
676
|
+
// error so subscribers see one event: terminal (native session already gone),
|
|
677
|
+
// recording-dead (recorder torn down but session still open — clearing
|
|
678
|
+
// isTracking is what unblocks a restart), recovery-required (resumeTracking()
|
|
679
|
+
// in foreground can revive it), and everything else (error only).
|
|
680
|
+
// The two dead-session buckets must also clear isRecoveryRequired: iOS retries
|
|
681
|
+
// cannotActivateInBackground and then gives up with interruptionRecoveryFailed,
|
|
682
|
+
// and no upload will ever arrive to clear the flag on that path.
|
|
683
|
+
// The bucket verdict is also published as errorInfo.category (with the
|
|
684
|
+
// else-bucket split into "transient" vs "unknown") so consumers can gate
|
|
685
|
+
// log severity on data instead of re-deriving code lists themselves.
|
|
563
686
|
onTrackingFailed: (error) => {
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
687
|
+
// The explicit iOS string buckets must win before the numeric terminal
|
|
688
|
+
// fallback: the numeric set encodes Android teardown semantics, and iOS
|
|
689
|
+
// reuses 11003 (.audioInitializationFailed -> .audio) for a failure whose
|
|
690
|
+
// session is still open. The numeric fallback still matters on iOS for
|
|
691
|
+
// start/stop failures that arrive as UNKNOWN_ERROR + 22xxx/24xxx and must
|
|
692
|
+
// clear the optimistically-set isTracking.
|
|
693
|
+
const recordingDead = !!(error && RECORDING_DEAD_ERROR_CODES.has(error.code));
|
|
694
|
+
const recoveryRequired = !!(error && RECOVERY_REQUIRED_ERROR_CODES.has(error.code));
|
|
695
|
+
const terminal = !!(error &&
|
|
696
|
+
!recordingDead &&
|
|
697
|
+
!recoveryRequired &&
|
|
698
|
+
(TERMINAL_TRACKING_ERROR_CODES.has(error.code) || TERMINAL_TRACKING_SDK_CODES.has(error.sdkCode)));
|
|
699
|
+
const transient = !!(error && TRANSIENT_TRACKING_SDK_CODES.has(error.sdkCode));
|
|
700
|
+
let category;
|
|
701
|
+
if (recordingDead)
|
|
702
|
+
category = "recordingDead";
|
|
703
|
+
else if (recoveryRequired)
|
|
704
|
+
category = "recoveryRequired";
|
|
705
|
+
else if (terminal)
|
|
706
|
+
category = "terminal";
|
|
707
|
+
else if (transient)
|
|
708
|
+
category = "transient";
|
|
709
|
+
else
|
|
710
|
+
category = "unknown";
|
|
711
|
+
// Category rides along in the stringified error too, so consumers still
|
|
712
|
+
// parsing the legacy string see the same verdict as errorInfo readers.
|
|
713
|
+
const errorString = JSON.stringify(error ? { ...error, category } : error);
|
|
714
|
+
const errorInfo = error
|
|
715
|
+
? {
|
|
716
|
+
code: typeof error.code === "string" ? error.code : "UNKNOWN_ERROR",
|
|
717
|
+
category,
|
|
718
|
+
...(typeof error.sdkCode === "number" ? { sdkCode: error.sdkCode } : {}),
|
|
719
|
+
...(typeof error.message === "string" ? { message: error.message } : {}),
|
|
720
|
+
...(typeof error.caseName === "string" ? { caseName: error.caseName } : {}),
|
|
721
|
+
}
|
|
722
|
+
: null;
|
|
723
|
+
let nextState;
|
|
724
|
+
if (terminal) {
|
|
725
|
+
nextState = {
|
|
726
|
+
error: errorString,
|
|
727
|
+
errorInfo,
|
|
728
|
+
isTracking: false,
|
|
729
|
+
isAnalyzing: false,
|
|
730
|
+
isRecoveryRequired: false,
|
|
731
|
+
didClose: true,
|
|
732
|
+
trackingStartTime: null,
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
else if (recordingDead) {
|
|
736
|
+
nextState = {
|
|
737
|
+
error: errorString,
|
|
738
|
+
errorInfo,
|
|
739
|
+
isTracking: false,
|
|
740
|
+
isAnalyzing: false,
|
|
741
|
+
isRecoveryRequired: false,
|
|
742
|
+
didClose: false,
|
|
743
|
+
trackingStartTime: null,
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
else if (recoveryRequired) {
|
|
747
|
+
nextState = { error: errorString, errorInfo, isTracking: true, isRecoveryRequired: true };
|
|
569
748
|
}
|
|
749
|
+
else {
|
|
750
|
+
nextState = { error: errorString, errorInfo };
|
|
751
|
+
}
|
|
752
|
+
useAsleepStore.setState(nextState);
|
|
753
|
+
addLog(`[onTrackingError] error: ${errorString}`);
|
|
570
754
|
},
|
|
571
755
|
// Connected: iOS didInterrupt, Android NOT IMPLEMENTED
|
|
572
756
|
onTrackingInterrupted: () => {
|
|
@@ -578,35 +762,35 @@ export const initializeAsleepListeners = () => {
|
|
|
578
762
|
// retry) reach this handler without a preceding didInterrupt, and the stale error
|
|
579
763
|
// should still be cleared. Only the paused-state mutation is gated, to dedup the
|
|
580
764
|
// iOS 3.2.1+ double fire from handleRecovering -> handleResumed.
|
|
765
|
+
// isRecoveryRequired, not isTrackingPaused, is authoritative when recording is
|
|
766
|
+
// dead because didResume fires before the engine restart is attempted.
|
|
581
767
|
onTrackingResumed: () => {
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
return;
|
|
586
|
-
}
|
|
587
|
-
setIsTrackingPaused(false);
|
|
588
|
-
addLog(`[onTrackingResumed]`);
|
|
768
|
+
const wasPaused = useAsleepStore.getState().isTrackingPaused;
|
|
769
|
+
useAsleepStore.setState(wasPaused ? { error: null, errorInfo: null, isTrackingPaused: false } : { error: null, errorInfo: null });
|
|
770
|
+
addLog(wasPaused ? `[onTrackingResumed]` : `[onTrackingResumed] (no prior pause; error cleared)`);
|
|
589
771
|
},
|
|
590
772
|
// Connected: iOS micPermissionWasDenied, Android NOT IMPLEMENTED
|
|
591
773
|
onMicPermissionDenied: () => {
|
|
592
774
|
addLog(`[onMicPermissionDenied]`);
|
|
593
775
|
},
|
|
594
|
-
// Connected: iOS
|
|
776
|
+
// Connected: iOS AsleepLogger callbacks, Android sendEvent called directly
|
|
595
777
|
onDebugLog: (data) => {
|
|
596
778
|
addLog(`[onDebugLog] message: ${data.message}`);
|
|
597
779
|
},
|
|
598
780
|
// Connected: iOS setupDidComplete, Android onComplete (AsleepSetupListener)
|
|
599
781
|
onSetupDidComplete: () => {
|
|
600
|
-
|
|
601
|
-
setIsSetupComplete(true);
|
|
782
|
+
useAsleepStore.setState({ isSetupInProgress: false, isSetupComplete: true });
|
|
602
783
|
addLog(`[onSetupDidComplete]`);
|
|
603
784
|
},
|
|
604
785
|
// Connected: iOS setupDidFail, Android onFail (AsleepSetupListener)
|
|
605
786
|
onSetupDidFail: (data) => {
|
|
606
787
|
const errorString = JSON.stringify(data);
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
788
|
+
useAsleepStore.setState({
|
|
789
|
+
error: errorString,
|
|
790
|
+
errorInfo: null,
|
|
791
|
+
isSetupInProgress: false,
|
|
792
|
+
isSetupComplete: false,
|
|
793
|
+
});
|
|
610
794
|
addLog(`[onSetupDidFail] error: ${errorString}`);
|
|
611
795
|
},
|
|
612
796
|
// Connected: iOS setupInProgress, Android onProgress (AsleepSetupListener)
|
|
@@ -615,10 +799,13 @@ export const initializeAsleepListeners = () => {
|
|
|
615
799
|
addLog(`[onSetupInProgress] progress: ${data.progress}%`);
|
|
616
800
|
},
|
|
617
801
|
// Connected: iOS analyzing (session), Android onSleepDataReceived (AsleepSleepDataListener)
|
|
802
|
+
// Android serializes snake_case; normalize so both platforms match AsleepAnalysisResult.
|
|
618
803
|
onAnalysisResult: (data) => {
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
804
|
+
const normalized = convertKeysToCamelCase(data);
|
|
805
|
+
useAsleepStore.setState({ analysisResult: normalized, isAnalyzing: false });
|
|
806
|
+
if (useAsleepStore.getState().showDebugLog) {
|
|
807
|
+
addLog(`[onAnalysisResult] ${JSON.stringify(normalized)}`);
|
|
808
|
+
}
|
|
622
809
|
},
|
|
623
810
|
};
|
|
624
811
|
// register all event listeners
|
|
@@ -627,15 +814,25 @@ export const initializeAsleepListeners = () => {
|
|
|
627
814
|
const subscription = emitter.addListener(eventType, handler);
|
|
628
815
|
subscriptions.push(() => subscription.remove());
|
|
629
816
|
});
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
// Create cleanup function
|
|
633
|
-
cleanupFunction = () => {
|
|
817
|
+
refCount++;
|
|
818
|
+
teardown = () => {
|
|
634
819
|
subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
635
|
-
|
|
636
|
-
|
|
820
|
+
teardown = null;
|
|
821
|
+
};
|
|
822
|
+
return makeCleanup();
|
|
823
|
+
};
|
|
824
|
+
const makeCleanup = () => {
|
|
825
|
+
// Idempotent per-caller cleanup. The `called` flag is closure-private so
|
|
826
|
+
// calling the returned function twice (e.g. Strict Mode double-effect)
|
|
827
|
+
// decrements the shared ref count only once.
|
|
828
|
+
let called = false;
|
|
829
|
+
return () => {
|
|
830
|
+
if (called)
|
|
831
|
+
return;
|
|
832
|
+
called = true;
|
|
833
|
+
refCount--;
|
|
834
|
+
if (refCount === 0 && teardown)
|
|
835
|
+
teardown();
|
|
637
836
|
};
|
|
638
|
-
// return cleanup function
|
|
639
|
-
return cleanupFunction;
|
|
640
837
|
};
|
|
641
838
|
//# sourceMappingURL=AsleepStore.js.map
|