@adminide-stack/yantra-mobile 12.0.85 → 12.0.86-alpha.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/lib/compute.js +52 -1
- package/lib/compute.js.map +1 -1
- package/lib/config/env-config.js +11 -1
- package/lib/config/env-config.js.map +1 -1
- package/lib/features/health/HealthSyncRunner.js +36 -0
- package/lib/features/health/HealthSyncRunner.js.map +1 -0
- package/lib/features/health/buildDays.js +182 -0
- package/lib/features/health/buildDays.js.map +1 -0
- package/lib/features/health/fitnessClient.js +138 -0
- package/lib/features/health/fitnessClient.js.map +1 -0
- package/lib/features/health/format.js +20 -0
- package/lib/features/health/format.js.map +1 -0
- package/lib/features/health/healthConnectLinks.js +9 -0
- package/lib/features/health/healthConnectLinks.js.map +1 -0
- package/lib/features/health/healthConnectMapping.js +126 -0
- package/lib/features/health/healthConnectMapping.js.map +1 -0
- package/lib/features/health/healthConnectReader.js +213 -0
- package/lib/features/health/healthConnectReader.js.map +1 -0
- package/lib/features/health/healthSync.js +15 -0
- package/lib/features/health/healthSync.js.map +1 -0
- package/lib/features/health/healthSyncStore.js +314 -0
- package/lib/features/health/healthSyncStore.js.map +1 -0
- package/lib/features/health/healthkitMapping.js +69 -0
- package/lib/features/health/healthkitMapping.js.map +1 -0
- package/lib/features/health/healthkitReader.js +151 -0
- package/lib/features/health/healthkitReader.js.map +1 -0
- package/lib/features/health/model.js +15 -0
- package/lib/features/health/model.js.map +1 -0
- package/lib/features/health/reader.js +44 -0
- package/lib/features/health/reader.js.map +1 -0
- package/lib/features/health/sleep.js +143 -0
- package/lib/features/health/sleep.js.map +1 -0
- package/lib/features/health/syncEngine.js +143 -0
- package/lib/features/health/syncEngine.js.map +1 -0
- package/lib/features/health/syncState.js +65 -0
- package/lib/features/health/syncState.js.map +1 -0
- package/lib/features/health/time.js +99 -0
- package/lib/features/health/time.js.map +1 -0
- package/lib/features/health/types.js +30 -0
- package/lib/features/health/types.js.map +1 -0
- package/lib/features/health/units.js +35 -0
- package/lib/features/health/units.js.map +1 -0
- package/lib/features/health/workoutTypes.js +177 -0
- package/lib/features/health/workoutTypes.js.map +1 -0
- package/lib/features/health/zones.js +31 -0
- package/lib/features/health/zones.js.map +1 -0
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/routes.json +52 -0
- package/lib/screens/Account/index.js +29 -1
- package/lib/screens/Account/index.js.map +1 -1
- package/lib/screens/Health/index.js +457 -0
- package/lib/screens/Health/index.js.map +1 -0
- package/package.json +6 -4
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import {createFitnessClient}from'./fitnessClient.js';import {describeSyncError,runHealthSync}from'./syncEngine.js';import {loadSyncState,saveSyncState,INITIAL_SYNC_STATE}from'./syncState.js';import {zoneClock,deviceTimeZone}from'./time.js';var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
+
const FOREGROUND_THROTTLE_MS = 15 * 6e4;
|
|
22
|
+
const SESSION_WAIT_MS = 3e4;
|
|
23
|
+
class HealthSyncStore {
|
|
24
|
+
constructor(deps) {
|
|
25
|
+
this.deps = deps;
|
|
26
|
+
__publicField(this, "snapshot", {
|
|
27
|
+
loaded: false,
|
|
28
|
+
sync: __spreadValues({}, INITIAL_SYNC_STATE),
|
|
29
|
+
running: false
|
|
30
|
+
});
|
|
31
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Set());
|
|
32
|
+
__publicField(this, "loading", null);
|
|
33
|
+
__publicField(this, "inFlight", null);
|
|
34
|
+
__publicField(this, "reader", null);
|
|
35
|
+
__publicField(this, "session", null);
|
|
36
|
+
__publicField(this, "sessionWaiters", []);
|
|
37
|
+
/** Bumped by disconnect, so a sync still finishing cannot turn sync back on. */
|
|
38
|
+
__publicField(this, "generation", 0);
|
|
39
|
+
__publicField(this, "subscribe", (listener) => {
|
|
40
|
+
this.listeners.add(listener);
|
|
41
|
+
return () => {
|
|
42
|
+
this.listeners.delete(listener);
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
__publicField(this, "getSnapshot", () => this.snapshot);
|
|
46
|
+
}
|
|
47
|
+
set(patch) {
|
|
48
|
+
this.snapshot = __spreadValues(__spreadValues({}, this.snapshot), patch);
|
|
49
|
+
this.listeners.forEach((l) => l());
|
|
50
|
+
}
|
|
51
|
+
getReader() {
|
|
52
|
+
if (!this.reader) this.reader = this.deps.createReader().catch(() => null);
|
|
53
|
+
return this.reader;
|
|
54
|
+
}
|
|
55
|
+
/** Opens the platform's own permission settings (Health Connect); false when there is none. */
|
|
56
|
+
async openStoreSettings() {
|
|
57
|
+
const reader = await this.getReader();
|
|
58
|
+
if (!(reader == null ? void 0 : reader.openSettings)) return false;
|
|
59
|
+
try {
|
|
60
|
+
await reader.openSettings();
|
|
61
|
+
return true;
|
|
62
|
+
} catch (e) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Load the saved state once; safe to call from many places. */
|
|
67
|
+
load() {
|
|
68
|
+
if (!this.loading) {
|
|
69
|
+
this.loading = (async () => {
|
|
70
|
+
const sync = await loadSyncState(this.deps.storage);
|
|
71
|
+
this.set({
|
|
72
|
+
loaded: true,
|
|
73
|
+
sync
|
|
74
|
+
});
|
|
75
|
+
})();
|
|
76
|
+
}
|
|
77
|
+
return this.loading;
|
|
78
|
+
}
|
|
79
|
+
async persist(sync) {
|
|
80
|
+
this.set({
|
|
81
|
+
sync
|
|
82
|
+
});
|
|
83
|
+
await saveSyncState(this.deps.storage, sync);
|
|
84
|
+
}
|
|
85
|
+
/** The root runner hands over the sign-in session (or null when it is gone). */
|
|
86
|
+
setSession(session, error) {
|
|
87
|
+
this.session = session;
|
|
88
|
+
this.set({
|
|
89
|
+
sessionError: session ? null : error != null ? error : null
|
|
90
|
+
});
|
|
91
|
+
if (session) {
|
|
92
|
+
const waiters = this.sessionWaiters;
|
|
93
|
+
this.sessionWaiters = [];
|
|
94
|
+
waiters.forEach((w) => w(session));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
waitForSession() {
|
|
98
|
+
if (this.session) return Promise.resolve(this.session);
|
|
99
|
+
return new Promise((resolve) => {
|
|
100
|
+
const timer = setTimeout(() => {
|
|
101
|
+
this.sessionWaiters = this.sessionWaiters.filter((w) => w !== done);
|
|
102
|
+
resolve(null);
|
|
103
|
+
}, SESSION_WAIT_MS);
|
|
104
|
+
const done = (s) => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
resolve(s);
|
|
107
|
+
};
|
|
108
|
+
this.sessionWaiters.push(done);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
async refreshStatus() {
|
|
112
|
+
await this.load();
|
|
113
|
+
const reader = await this.getReader();
|
|
114
|
+
if (!reader) {
|
|
115
|
+
this.set({
|
|
116
|
+
availability: {
|
|
117
|
+
status: "unsupported",
|
|
118
|
+
reason: "Health data is not available in this version of the app. Update Yantra to connect."
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const availability = await reader.availability();
|
|
124
|
+
this.set({
|
|
125
|
+
availability
|
|
126
|
+
});
|
|
127
|
+
if (availability.status === "available" && this.snapshot.sync.connected) {
|
|
128
|
+
try {
|
|
129
|
+
this.set({
|
|
130
|
+
granted: await reader.grantedTypes()
|
|
131
|
+
});
|
|
132
|
+
} catch (e) {
|
|
133
|
+
this.set({
|
|
134
|
+
granted: void 0
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Ask for access, turn sync on, run the 30-day backfill. Resolves false if not connected. */
|
|
140
|
+
async connect() {
|
|
141
|
+
var _a;
|
|
142
|
+
await this.load();
|
|
143
|
+
const reader = await this.getReader();
|
|
144
|
+
if (!reader) return false;
|
|
145
|
+
this.set({
|
|
146
|
+
busy: "connecting"
|
|
147
|
+
});
|
|
148
|
+
try {
|
|
149
|
+
const availability = await reader.availability();
|
|
150
|
+
this.set({
|
|
151
|
+
availability
|
|
152
|
+
});
|
|
153
|
+
if (availability.status !== "available") return false;
|
|
154
|
+
const granted = await reader.requestAccess();
|
|
155
|
+
this.set({
|
|
156
|
+
granted
|
|
157
|
+
});
|
|
158
|
+
if (granted && granted.length === 0) {
|
|
159
|
+
await this.persist(__spreadProps(__spreadValues({}, this.snapshot.sync), {
|
|
160
|
+
lastError: `No data types were allowed. Allow them in ${reader.storeName} to sync.`
|
|
161
|
+
}));
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
const now = new Date(this.now()).toISOString();
|
|
165
|
+
await this.persist(__spreadProps(__spreadValues({}, this.snapshot.sync), {
|
|
166
|
+
connected: true,
|
|
167
|
+
source: reader.source,
|
|
168
|
+
connectedAt: (_a = this.snapshot.sync.connectedAt) != null ? _a : now,
|
|
169
|
+
lastError: void 0
|
|
170
|
+
}));
|
|
171
|
+
} catch (err) {
|
|
172
|
+
await this.persist(__spreadProps(__spreadValues({}, this.snapshot.sync), {
|
|
173
|
+
lastError: describeSyncError(err)
|
|
174
|
+
}));
|
|
175
|
+
return false;
|
|
176
|
+
} finally {
|
|
177
|
+
this.set({
|
|
178
|
+
busy: void 0
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
void this.syncNow({
|
|
182
|
+
interactive: false
|
|
183
|
+
});
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Stop syncing. With `deleteData`, also delete everything this phone sent
|
|
188
|
+
* to Yantra (the coach then forgets it). Health Connect access is given
|
|
189
|
+
* back; Apple Health access can only be removed in the Health app.
|
|
190
|
+
*/
|
|
191
|
+
async disconnect(opts) {
|
|
192
|
+
await this.load();
|
|
193
|
+
const reader = await this.getReader();
|
|
194
|
+
this.set({
|
|
195
|
+
busy: "disconnecting"
|
|
196
|
+
});
|
|
197
|
+
try {
|
|
198
|
+
if (opts.deleteData && reader) {
|
|
199
|
+
const session = await this.waitForSession();
|
|
200
|
+
if (!session) {
|
|
201
|
+
return {
|
|
202
|
+
ok: false,
|
|
203
|
+
message: "Could not sign in to delete the data. Try again in a moment."
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
await createFitnessClient({
|
|
208
|
+
url: session.url,
|
|
209
|
+
token: session.token,
|
|
210
|
+
fetchImpl: this.deps.fetchImpl
|
|
211
|
+
}).deleteSource(reader.source);
|
|
212
|
+
} catch (err) {
|
|
213
|
+
return {
|
|
214
|
+
ok: false,
|
|
215
|
+
message: describeSyncError(err)
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
this.generation += 1;
|
|
220
|
+
await (reader == null ? void 0 : reader.revoke());
|
|
221
|
+
await this.persist(__spreadValues({}, INITIAL_SYNC_STATE));
|
|
222
|
+
this.set({
|
|
223
|
+
granted: void 0
|
|
224
|
+
});
|
|
225
|
+
return {
|
|
226
|
+
ok: true
|
|
227
|
+
};
|
|
228
|
+
} finally {
|
|
229
|
+
this.set({
|
|
230
|
+
busy: void 0
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** Foreground trigger: syncs when connected and the last attempt is old enough. */
|
|
235
|
+
async syncIfDue() {
|
|
236
|
+
await this.load();
|
|
237
|
+
const {
|
|
238
|
+
sync
|
|
239
|
+
} = this.snapshot;
|
|
240
|
+
if (!sync.connected) return;
|
|
241
|
+
const last = sync.lastAttemptAt ? Date.parse(sync.lastAttemptAt) : 0;
|
|
242
|
+
if (this.now() - last < FOREGROUND_THROTTLE_MS) return;
|
|
243
|
+
await this.syncNow({
|
|
244
|
+
interactive: false
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Run a sync now (joins one already running). `interactive` = the person
|
|
249
|
+
* tapped "Sync now": on Apple Health this re-shows the permission sheet
|
|
250
|
+
* if HealthKit still needs it, which an automatic sync never does.
|
|
251
|
+
*/
|
|
252
|
+
syncNow(opts = {
|
|
253
|
+
interactive: true
|
|
254
|
+
}) {
|
|
255
|
+
if (this.inFlight) return this.inFlight;
|
|
256
|
+
this.inFlight = (async () => {
|
|
257
|
+
var _a;
|
|
258
|
+
this.set({
|
|
259
|
+
running: true
|
|
260
|
+
});
|
|
261
|
+
const {
|
|
262
|
+
generation
|
|
263
|
+
} = this;
|
|
264
|
+
try {
|
|
265
|
+
await this.load();
|
|
266
|
+
const reader = await this.getReader();
|
|
267
|
+
if (!reader || !this.snapshot.sync.connected) return false;
|
|
268
|
+
if (opts.interactive) {
|
|
269
|
+
try {
|
|
270
|
+
const granted = await reader.requestAccess();
|
|
271
|
+
this.set({
|
|
272
|
+
granted
|
|
273
|
+
});
|
|
274
|
+
} catch (e) {
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const session = await this.waitForSession();
|
|
278
|
+
if (generation !== this.generation) return false;
|
|
279
|
+
if (!session) {
|
|
280
|
+
await this.persist(__spreadProps(__spreadValues({}, this.snapshot.sync), {
|
|
281
|
+
lastAttemptAt: new Date(this.now()).toISOString(),
|
|
282
|
+
lastError: this.snapshot.sessionError || "Could not sign in to Yantra to sync. Check your connection and try again."
|
|
283
|
+
}));
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
const outcome = await runHealthSync(this.snapshot.sync, {
|
|
287
|
+
reader,
|
|
288
|
+
client: createFitnessClient({
|
|
289
|
+
url: session.url,
|
|
290
|
+
token: session.token,
|
|
291
|
+
fetchImpl: this.deps.fetchImpl
|
|
292
|
+
}),
|
|
293
|
+
clock: zoneClock(((_a = this.deps.timeZone) != null ? _a : deviceTimeZone)()),
|
|
294
|
+
owner: session.owner,
|
|
295
|
+
now: () => this.now(),
|
|
296
|
+
onProgress: async (state) => {
|
|
297
|
+
if (generation === this.generation) await this.persist(state);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
return outcome.ok;
|
|
301
|
+
} finally {
|
|
302
|
+
this.inFlight = null;
|
|
303
|
+
this.set({
|
|
304
|
+
running: false
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
})();
|
|
308
|
+
return this.inFlight;
|
|
309
|
+
}
|
|
310
|
+
now() {
|
|
311
|
+
var _a;
|
|
312
|
+
return ((_a = this.deps.now) != null ? _a : Date.now)();
|
|
313
|
+
}
|
|
314
|
+
}export{FOREGROUND_THROTTLE_MS,HealthSyncStore};//# sourceMappingURL=healthSyncStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"healthSyncStore.js","sources":["../../../src/features/health/healthSyncStore.ts"],"sourcesContent":["/**\n * App-wide health sync state: one instance shared by the Health screen and\n * the root HealthSyncRunner (which owns the session and the foreground\n * trigger). A plain external store (useSyncExternalStore) instead of a React\n * context, so the runner can live at the app root while the screen mounts and\n * unmounts.\n *\n * Every sync is single-flight: a second trigger while one runs joins it.\n */\nimport { createFitnessClient } from './fitnessClient';\nimport type { HealthAvailability, HealthDataType, HealthReader } from './reader';\nimport { describeSyncError, runHealthSync } from './syncEngine';\nimport { INITIAL_SYNC_STATE, loadSyncState, saveSyncState, type HealthSyncState, type StorageLike } from './syncState';\nimport { deviceTimeZone, zoneClock } from './time';\n\n/** Foreground syncs are at most this frequent. \"Sync now\" ignores it. */\nexport const FOREGROUND_THROTTLE_MS = 15 * 60_000;\n/** How long a sync waits for the sign-in session before giving up. */\nconst SESSION_WAIT_MS = 30_000;\n\nexport interface HealthSession {\n token: string;\n url: string;\n /** Account the token belongs to. */\n owner?: string;\n}\n\nexport interface HealthSyncSnapshot {\n loaded: boolean;\n sync: HealthSyncState;\n running: boolean;\n availability?: HealthAvailability;\n /** Granted types; null = the platform does not tell (Apple Health). */\n granted?: HealthDataType[] | null;\n /** Plain words, when signing in for sync failed. */\n sessionError?: string | null;\n /** A connect / disconnect action in progress. */\n busy?: 'connecting' | 'disconnecting';\n}\n\nexport interface HealthSyncStoreDeps {\n storage: StorageLike;\n /** Resolves null when this build has no health store (no native module, unsupported OS). */\n createReader: () => Promise<HealthReader | null>;\n fetchImpl?: typeof fetch;\n now?: () => number;\n timeZone?: () => string;\n}\n\nexport class HealthSyncStore {\n private snapshot: HealthSyncSnapshot = { loaded: false, sync: { ...INITIAL_SYNC_STATE }, running: false };\n\n private listeners = new Set<() => void>();\n\n private loading: Promise<void> | null = null;\n\n private inFlight: Promise<boolean> | null = null;\n\n private reader: Promise<HealthReader | null> | null = null;\n\n private session: HealthSession | null = null;\n\n private sessionWaiters: Array<(s: HealthSession | null) => void> = [];\n\n /** Bumped by disconnect, so a sync still finishing cannot turn sync back on. */\n private generation = 0;\n\n constructor(private readonly deps: HealthSyncStoreDeps) {}\n\n subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getSnapshot = (): HealthSyncSnapshot => this.snapshot;\n\n private set(patch: Partial<HealthSyncSnapshot>) {\n this.snapshot = { ...this.snapshot, ...patch };\n this.listeners.forEach((l) => l());\n }\n\n private getReader(): Promise<HealthReader | null> {\n if (!this.reader) this.reader = this.deps.createReader().catch(() => null);\n return this.reader;\n }\n\n /** Opens the platform's own permission settings (Health Connect); false when there is none. */\n async openStoreSettings(): Promise<boolean> {\n const reader = await this.getReader();\n if (!reader?.openSettings) return false;\n try {\n await reader.openSettings();\n return true;\n } catch {\n return false;\n }\n }\n\n /** Load the saved state once; safe to call from many places. */\n load(): Promise<void> {\n if (!this.loading) {\n this.loading = (async () => {\n const sync = await loadSyncState(this.deps.storage);\n this.set({ loaded: true, sync });\n })();\n }\n return this.loading;\n }\n\n private async persist(sync: HealthSyncState) {\n this.set({ sync });\n await saveSyncState(this.deps.storage, sync);\n }\n\n /** The root runner hands over the sign-in session (or null when it is gone). */\n setSession(session: HealthSession | null, error?: string | null) {\n this.session = session;\n this.set({ sessionError: session ? null : (error ?? null) });\n if (session) {\n const waiters = this.sessionWaiters;\n this.sessionWaiters = [];\n waiters.forEach((w) => w(session));\n }\n }\n\n private waitForSession(): Promise<HealthSession | null> {\n if (this.session) return Promise.resolve(this.session);\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n this.sessionWaiters = this.sessionWaiters.filter((w) => w !== done);\n resolve(null);\n }, SESSION_WAIT_MS);\n const done = (s: HealthSession | null) => {\n clearTimeout(timer);\n resolve(s);\n };\n this.sessionWaiters.push(done);\n });\n }\n\n async refreshStatus(): Promise<void> {\n await this.load();\n const reader = await this.getReader();\n if (!reader) {\n this.set({\n availability: {\n status: 'unsupported',\n reason: 'Health data is not available in this version of the app. Update Yantra to connect.',\n },\n });\n return;\n }\n const availability = await reader.availability();\n this.set({ availability });\n if (availability.status === 'available' && this.snapshot.sync.connected) {\n try {\n this.set({ granted: await reader.grantedTypes() });\n } catch {\n this.set({ granted: undefined });\n }\n }\n }\n\n /** Ask for access, turn sync on, run the 30-day backfill. Resolves false if not connected. */\n async connect(): Promise<boolean> {\n await this.load();\n const reader = await this.getReader();\n if (!reader) return false;\n this.set({ busy: 'connecting' });\n try {\n const availability = await reader.availability();\n this.set({ availability });\n if (availability.status !== 'available') return false;\n const granted = await reader.requestAccess();\n this.set({ granted });\n if (granted && granted.length === 0) {\n await this.persist({\n ...this.snapshot.sync,\n lastError: `No data types were allowed. Allow them in ${reader.storeName} to sync.`,\n });\n return false;\n }\n const now = new Date(this.now()).toISOString();\n await this.persist({\n ...this.snapshot.sync,\n connected: true,\n source: reader.source,\n connectedAt: this.snapshot.sync.connectedAt ?? now,\n lastError: undefined,\n });\n } catch (err) {\n await this.persist({ ...this.snapshot.sync, lastError: describeSyncError(err) });\n return false;\n } finally {\n this.set({ busy: undefined });\n }\n void this.syncNow({ interactive: false });\n return true;\n }\n\n /**\n * Stop syncing. With `deleteData`, also delete everything this phone sent\n * to Yantra (the coach then forgets it). Health Connect access is given\n * back; Apple Health access can only be removed in the Health app.\n */\n async disconnect(opts: { deleteData: boolean }): Promise<{ ok: boolean; message?: string }> {\n await this.load();\n const reader = await this.getReader();\n this.set({ busy: 'disconnecting' });\n try {\n if (opts.deleteData && reader) {\n const session = await this.waitForSession();\n if (!session) {\n return { ok: false, message: 'Could not sign in to delete the data. Try again in a moment.' };\n }\n try {\n await createFitnessClient({\n url: session.url,\n token: session.token,\n fetchImpl: this.deps.fetchImpl,\n }).deleteSource(reader.source);\n } catch (err) {\n return { ok: false, message: describeSyncError(err) };\n }\n }\n this.generation += 1;\n await reader?.revoke();\n await this.persist({ ...INITIAL_SYNC_STATE });\n this.set({ granted: undefined });\n return { ok: true };\n } finally {\n this.set({ busy: undefined });\n }\n }\n\n /** Foreground trigger: syncs when connected and the last attempt is old enough. */\n async syncIfDue(): Promise<void> {\n await this.load();\n const { sync } = this.snapshot;\n if (!sync.connected) return;\n const last = sync.lastAttemptAt ? Date.parse(sync.lastAttemptAt) : 0;\n if (this.now() - last < FOREGROUND_THROTTLE_MS) return;\n await this.syncNow({ interactive: false });\n }\n\n /**\n * Run a sync now (joins one already running). `interactive` = the person\n * tapped \"Sync now\": on Apple Health this re-shows the permission sheet\n * if HealthKit still needs it, which an automatic sync never does.\n */\n syncNow(opts: { interactive: boolean } = { interactive: true }): Promise<boolean> {\n if (this.inFlight) return this.inFlight;\n this.inFlight = (async () => {\n this.set({ running: true });\n const { generation } = this;\n try {\n await this.load();\n const reader = await this.getReader();\n if (!reader || !this.snapshot.sync.connected) return false;\n if (opts.interactive) {\n try {\n const granted = await reader.requestAccess();\n this.set({ granted });\n } catch {\n // The read below reports what is missing.\n }\n }\n const session = await this.waitForSession();\n if (generation !== this.generation) return false;\n if (!session) {\n await this.persist({\n ...this.snapshot.sync,\n lastAttemptAt: new Date(this.now()).toISOString(),\n lastError:\n this.snapshot.sessionError ||\n 'Could not sign in to Yantra to sync. Check your connection and try again.',\n });\n return false;\n }\n const outcome = await runHealthSync(this.snapshot.sync, {\n reader,\n client: createFitnessClient({\n url: session.url,\n token: session.token,\n fetchImpl: this.deps.fetchImpl,\n }),\n clock: zoneClock((this.deps.timeZone ?? deviceTimeZone)()),\n owner: session.owner,\n now: () => this.now(),\n onProgress: async (state) => {\n if (generation === this.generation) await this.persist(state);\n },\n });\n return outcome.ok;\n } finally {\n this.inFlight = null;\n this.set({ running: false });\n }\n })();\n return this.inFlight;\n }\n\n private now(): number {\n return (this.deps.now ?? Date.now)();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBO,MAAM,yBAAyB,EAAK,GAAA;AAE3C,MAAM,eAAkB,GAAA,GAAA;AA2BjB,MAAM,eAAgB,CAAA;AAAA,EAiB3B,YAA6B,IAA2B,EAAA;AAA3B,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAhB7B,IAAA,aAAA,CAAA,IAAA,EAAQ,UAA+B,EAAA;AAAA,MACrC,MAAQ,EAAA,KAAA;AAAA,MACR,MAAM,cACD,CAAA,EAAA,EAAA,kBAAA,CAAA;AAAA,MAEL,OAAS,EAAA;AAA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ed",
|
|
3
|
+
1: "asleep",
|
|
4
|
+
2: "awake",
|
|
5
|
+
3: "light",
|
|
6
|
+
4: "deep",
|
|
7
|
+
5: "rem"
|
|
8
|
+
};
|
|
9
|
+
function hkSleepSegments(samples) {
|
|
10
|
+
var _a, _b, _c, _d;
|
|
11
|
+
const out = [];
|
|
12
|
+
for (const s of samples) {
|
|
13
|
+
const stage = HK_SLEEP_STAGE[s.value];
|
|
14
|
+
if (!stage) continue;
|
|
15
|
+
out.push({
|
|
16
|
+
start: s.startDate.getTime(),
|
|
17
|
+
end: s.endDate.getTime(),
|
|
18
|
+
stage,
|
|
19
|
+
sourceKey: ((_b = (_a = s.sourceRevision) == null ? void 0 : _a.source) == null ? void 0 : _b.bundleIdentifier) || ((_d = (_c = s.sourceRevision) == null ? void 0 : _c.source) == null ? void 0 : _d.name) || "unknown"
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
function hkValues(samples, transform = (v) => v) {
|
|
25
|
+
return samples.filter((s) => Number.isFinite(s.quantity)).map((s) => ({
|
|
26
|
+
t: s.startDate.getTime(),
|
|
27
|
+
value: transform(s.quantity)
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
const hkSpo2Values = (samples) => hkValues(samples, fractionToPercent);
|
|
31
|
+
function hkDailyTotals(stats, clock) {
|
|
32
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
33
|
+
const put = (field, buckets) => {
|
|
34
|
+
var _a, _b;
|
|
35
|
+
for (const b of buckets != null ? buckets : []) {
|
|
36
|
+
const value = (_a = b.sumQuantity) == null ? void 0 : _a.quantity;
|
|
37
|
+
if (!b.startDate || value === void 0 || !Number.isFinite(value)) continue;
|
|
38
|
+
const date = clock.dateOf(b.startDate.getTime() + 6e4);
|
|
39
|
+
const row = (_b = byDate.get(date)) != null ? _b : {
|
|
40
|
+
date
|
|
41
|
+
};
|
|
42
|
+
row[field] = value;
|
|
43
|
+
byDate.set(date, row);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
put("steps", stats.steps);
|
|
47
|
+
put("activeCalories", stats.activeCalories);
|
|
48
|
+
put("distanceMeters", stats.distanceMeters);
|
|
49
|
+
put("activeMinutes", stats.activeMinutes);
|
|
50
|
+
return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));
|
|
51
|
+
}
|
|
52
|
+
function hkWorkout(w, stats = {}) {
|
|
53
|
+
var _a, _b;
|
|
54
|
+
const out = {
|
|
55
|
+
id: w.uuid,
|
|
56
|
+
start: w.startDate.getTime(),
|
|
57
|
+
end: w.endDate.getTime(),
|
|
58
|
+
type: healthKitWorkoutType(w.workoutActivityType)
|
|
59
|
+
};
|
|
60
|
+
const duration = toMinutes(w.duration);
|
|
61
|
+
if (duration !== void 0) out.durationMin = duration;
|
|
62
|
+
const calories = (_a = stats.calories) != null ? _a : toKcal(w.totalEnergyBurned);
|
|
63
|
+
if (calories !== void 0) out.calories = calories;
|
|
64
|
+
const distance = (_b = stats.distanceMeters) != null ? _b : toMeters(w.totalDistance);
|
|
65
|
+
if (distance !== void 0 && distance > 0) out.distanceMeters = distance;
|
|
66
|
+
if (stats.avgHr !== void 0) out.avgHr = stats.avgHr;
|
|
67
|
+
if (stats.maxHr !== void 0) out.maxHr = stats.maxHr;
|
|
68
|
+
return out;
|
|
69
|
+
}export{hkDailyTotals,hkSleepSegments,hkSpo2Values,hkValues,hkWorkout};//# sourceMappingURL=healthkitMapping.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"healthkitMapping.js","sources":["../../../src/features/health/healthkitMapping.ts"],"sourcesContent":["/**\n * @kingstinct/react-native-healthkit records -> RawHealthData pieces.\n *\n * The input interfaces are the subset of the library's types this reads\n * (QuantitySample, CategorySample, QueryStatisticsResponse, WorkoutSample),\n * declared structurally so the mapping runs under jest without the native\n * module. Values are queried in fixed units (healthkitReader.ts), so only\n * the workout totals need unit conversion.\n */\nimport type { DailyTotals, RawWorkout, SleepSegment, SleepStage, TimedValue } from './model';\nimport type { ZoneClock } from './time';\nimport { fractionToPercent, toKcal, toMeters, toMinutes, type UnitQuantity } from './units';\nimport { healthKitWorkoutType } from './workoutTypes';\n\nexport interface HKSourceLike {\n readonly source?: { readonly bundleIdentifier?: string; readonly name?: string };\n}\n\nexport interface HKQuantitySampleLike {\n readonly uuid?: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly quantity: number;\n}\n\nexport interface HKCategorySampleLike {\n readonly uuid?: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly value: number;\n readonly sourceRevision?: HKSourceLike;\n}\n\nexport interface HKStatisticsLike {\n readonly startDate?: Date;\n readonly sumQuantity?: UnitQuantity;\n}\n\nexport interface HKWorkoutLike {\n readonly uuid: string;\n readonly startDate: Date;\n readonly endDate: Date;\n readonly workoutActivityType: number;\n readonly duration?: UnitQuantity;\n readonly totalEnergyBurned?: UnitQuantity;\n readonly totalDistance?: UnitQuantity;\n}\n\n/** Per-workout statistics the reader asked HealthKit for in fixed units. */\nexport interface HKWorkoutStats {\n calories?: number;\n distanceMeters?: number;\n avgHr?: number;\n maxHr?: number;\n}\n\n/** HKCategoryValueSleepAnalysis raw values. */\nconst HK_SLEEP_STAGE: Record<number, SleepStage> = {\n 0: 'inBed',\n 1: 'asleep',\n 2: 'awake',\n 3: 'light',\n 4: 'deep',\n 5: 'rem',\n};\n\nexport function hkSleepSegments(samples: readonly HKCategorySampleLike[]): SleepSegment[] {\n const out: SleepSegment[] = [];\n for (const s of samples) {\n const stage = HK_SLEEP_STAGE[s.value];\n if (!stage) continue;\n out.push({\n start: s.startDate.getTime(),\n end: s.endDate.getTime(),\n stage,\n sourceKey: s.sourceRevision?.source?.bundleIdentifier || s.sourceRevision?.source?.name || 'unknown',\n });\n }\n return out;\n}\n\n/** Point-in-time values; an interval sample counts at its start. */\nexport function hkValues(\n samples: readonly HKQuantitySampleLike[],\n transform: (v: number) => number = (v) => v,\n): TimedValue[] {\n return samples\n .filter((s) => Number.isFinite(s.quantity))\n .map((s) => ({ t: s.startDate.getTime(), value: transform(s.quantity) }));\n}\n\nexport const hkSpo2Values = (samples: readonly HKQuantitySampleLike[]) => hkValues(samples, fractionToPercent);\n\nexport interface HKDailyStatistics {\n steps?: readonly HKStatisticsLike[];\n activeCalories?: readonly HKStatisticsLike[];\n distanceMeters?: readonly HKStatisticsLike[];\n activeMinutes?: readonly HKStatisticsLike[];\n}\n\n/**\n * Daily statistics-collection buckets (anchored at local midnight, one day\n * each) -> DailyTotals. HealthKit's statistics already merge phone + watch\n * without double counting, which summing raw samples would not.\n */\nexport function hkDailyTotals(stats: HKDailyStatistics, clock: ZoneClock): DailyTotals[] {\n const byDate = new Map<string, DailyTotals>();\n const put = (field: Exclude<keyof DailyTotals, 'date'>, buckets: readonly HKStatisticsLike[] | undefined) => {\n for (const b of buckets ?? []) {\n const value = b.sumQuantity?.quantity;\n if (!b.startDate || value === undefined || !Number.isFinite(value)) continue;\n // +1 min: a bucket starts AT local midnight; never let float/DST\n // rounding push it onto the previous date.\n const date = clock.dateOf(b.startDate.getTime() + 60_000);\n const row = byDate.get(date) ?? { date };\n row[field] = value;\n byDate.set(date, row);\n }\n };\n put('steps', stats.steps);\n put('activeCalories', stats.activeCalories);\n put('distanceMeters', stats.distanceMeters);\n put('activeMinutes', stats.activeMinutes);\n return [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));\n}\n\nexport function hkWorkout(w: HKWorkoutLike, stats: HKWorkoutStats = {}): RawWorkout {\n const out: RawWorkout = {\n id: w.uuid,\n start: w.startDate.getTime(),\n end: w.endDate.getTime(),\n type: healthKitWorkoutType(w.workoutActivityType),\n };\n const duration = toMinutes(w.duration);\n if (duration !== undefined) out.durationMin = duration;\n const calories = stats.calories ?? toKcal(w.totalEnergyBurned);\n if (calories !== undefined) out.calories = calories;\n const distance = stats.distanceMeters ?? toMeters(w.totalDistance);\n if (distance !== undefined && distance > 0) out.distanceMeters = distance;\n if (stats.avgHr !== undefined)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AAa,QAAW,GAAA,CAAA,MAAO,cAAiB,GAAA,QAAA;AACjE,EAAA,IAAI,KAAM,CAAA,KAAA,KAAU,MAAW,EAAA,GAAA,CAAI,QAAQ,KAAM,CAAA,KAAA;AACjD,EAAA,IAAI,KAAM,CAAA,KAAA,KAAU,MAAW,EAAA,GAAA,CAAI,QAAQ,KAAM,CAAA,KAAA;AACjD,EAAO,OAAA,GAAA;AACT"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import {getRequestStatusForAuthorization,AuthorizationRequestStatus,requestAuthorization,isHealthDataAvailableAsync,queryQuantitySamples,queryCategorySamples,queryWorkoutSamples,queryStatisticsCollectionForQuantity}from'@kingstinct/react-native-healthkit';import {hkDailyTotals,hkValues,hkSpo2Values,hkSleepSegments,hkWorkout}from'./healthkitMapping.js';import {emptyRawHealthData}from'./model.js';class HealthAccessNeededError extends Error {
|
|
2
|
+
constructor() {
|
|
3
|
+
super("Yantra needs to ask for access to Apple Health again.");
|
|
4
|
+
this.name = "HealthAccessNeededError";
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
const READ_TYPES = {
|
|
8
|
+
steps: "HKQuantityTypeIdentifierStepCount",
|
|
9
|
+
distance: "HKQuantityTypeIdentifierDistanceWalkingRunning",
|
|
10
|
+
activeCalories: "HKQuantityTypeIdentifierActiveEnergyBurned",
|
|
11
|
+
exercise: "HKQuantityTypeIdentifierAppleExerciseTime",
|
|
12
|
+
heartRate: "HKQuantityTypeIdentifierHeartRate",
|
|
13
|
+
restingHr: "HKQuantityTypeIdentifierRestingHeartRate",
|
|
14
|
+
hrv: "HKQuantityTypeIdentifierHeartRateVariabilitySDNN",
|
|
15
|
+
sleep: "HKCategoryTypeIdentifierSleepAnalysis",
|
|
16
|
+
workouts: "HKWorkoutTypeIdentifier",
|
|
17
|
+
weight: "HKQuantityTypeIdentifierBodyMass",
|
|
18
|
+
vo2Max: "HKQuantityTypeIdentifierVO2Max",
|
|
19
|
+
spo2: "HKQuantityTypeIdentifierOxygenSaturation",
|
|
20
|
+
respiratoryRate: "HKQuantityTypeIdentifierRespiratoryRate"
|
|
21
|
+
};
|
|
22
|
+
const TO_READ = Object.values(READ_TYPES);
|
|
23
|
+
const HR_CHUNK_MS = 864e5;
|
|
24
|
+
async function attempt(type, unreadable, run) {
|
|
25
|
+
try {
|
|
26
|
+
return await run();
|
|
27
|
+
} catch (e) {
|
|
28
|
+
unreadable.add(type);
|
|
29
|
+
return void 0;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function createHealthKitReader() {
|
|
33
|
+
return {
|
|
34
|
+
source: "apple-health",
|
|
35
|
+
storeName: "Apple Health",
|
|
36
|
+
async availability() {
|
|
37
|
+
try {
|
|
38
|
+
return await isHealthDataAvailableAsync() ? {
|
|
39
|
+
status: "available"
|
|
40
|
+
} : {
|
|
41
|
+
status: "unsupported",
|
|
42
|
+
reason: "Apple Health is not available on this device."
|
|
43
|
+
};
|
|
44
|
+
} catch (e) {
|
|
45
|
+
return {
|
|
46
|
+
status: "unsupported",
|
|
47
|
+
reason: "Apple Health is not available in this build of the app."
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
async requestAccess() {
|
|
52
|
+
await requestAuthorization({
|
|
53
|
+
toRead: TO_READ
|
|
54
|
+
});
|
|
55
|
+
return null;
|
|
56
|
+
},
|
|
57
|
+
async grantedTypes() {
|
|
58
|
+
return null;
|
|
59
|
+
},
|
|
60
|
+
async read(range, clock) {
|
|
61
|
+
var _a;
|
|
62
|
+
const status = await getRequestStatusForAuthorization({
|
|
63
|
+
toRead: TO_READ
|
|
64
|
+
});
|
|
65
|
+
if (status === AuthorizationRequestStatus.shouldRequest) throw new HealthAccessNeededError();
|
|
66
|
+
const unreadable = /* @__PURE__ */ new Set();
|
|
67
|
+
const raw = emptyRawHealthData("sdnn");
|
|
68
|
+
const startDate = new Date(range.start);
|
|
69
|
+
const endDate = new Date(range.end);
|
|
70
|
+
const date = {
|
|
71
|
+
startDate,
|
|
72
|
+
endDate
|
|
73
|
+
};
|
|
74
|
+
const samples = (type, id, unit, from = startDate, to = endDate) => attempt(type, unreadable, () => queryQuantitySamples(id, {
|
|
75
|
+
limit: 0,
|
|
76
|
+
ascending: true,
|
|
77
|
+
unit,
|
|
78
|
+
filter: {
|
|
79
|
+
date: {
|
|
80
|
+
startDate: from,
|
|
81
|
+
endDate: to
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}));
|
|
85
|
+
const firstDay = clock.dateOf(range.start + 12 * 36e5);
|
|
86
|
+
const anchor = new Date(clock.startOfDay(firstDay));
|
|
87
|
+
const statsRange = {
|
|
88
|
+
date: {
|
|
89
|
+
startDate: anchor,
|
|
90
|
+
endDate
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const daily = (type, id, unit) => attempt(type, unreadable, () => queryStatisticsCollectionForQuantity(id, ["cumulativeSum"], anchor, {
|
|
94
|
+
day: 1
|
|
95
|
+
}, {
|
|
96
|
+
unit,
|
|
97
|
+
filter: statsRange
|
|
98
|
+
}));
|
|
99
|
+
const [steps, activeCalories, distance, exercise] = await Promise.all([daily("steps", "HKQuantityTypeIdentifierStepCount", "count"), daily("activeCalories", "HKQuantityTypeIdentifierActiveEnergyBurned", "kcal"), daily("distance", "HKQuantityTypeIdentifierDistanceWalkingRunning", "m"), daily("exercise", "HKQuantityTypeIdentifierAppleExerciseTime", "min")]);
|
|
100
|
+
raw.dailyTotals = hkDailyTotals({
|
|
101
|
+
steps,
|
|
102
|
+
activeCalories,
|
|
103
|
+
distanceMeters: distance,
|
|
104
|
+
activeMinutes: exercise
|
|
105
|
+
}, clock);
|
|
106
|
+
for (let t = range.start; t < range.end; t += HR_CHUNK_MS) {
|
|
107
|
+
const chunk = await samples("heartRate", "HKQuantityTypeIdentifierHeartRate", "count/min", new Date(t), new Date(Math.min(range.end, t + HR_CHUNK_MS)));
|
|
108
|
+
if (chunk) raw.heartRate.push(...hkValues(chunk));
|
|
109
|
+
}
|
|
110
|
+
const [rhr, hrv, weight, vo2, spo2, resp, sleep] = await Promise.all([samples("restingHr", "HKQuantityTypeIdentifierRestingHeartRate", "count/min"), samples("hrv", "HKQuantityTypeIdentifierHeartRateVariabilitySDNN", "ms"), samples("weight", "HKQuantityTypeIdentifierBodyMass", "kg"), samples("vo2Max", "HKQuantityTypeIdentifierVO2Max", "ml/(kg*min)"), samples("spo2", "HKQuantityTypeIdentifierOxygenSaturation", "%"), samples("respiratoryRate", "HKQuantityTypeIdentifierRespiratoryRate", "count/min"), attempt("sleep", unreadable, () => queryCategorySamples("HKCategoryTypeIdentifierSleepAnalysis", {
|
|
111
|
+
limit: 0,
|
|
112
|
+
ascending: true,
|
|
113
|
+
filter: {
|
|
114
|
+
date
|
|
115
|
+
}
|
|
116
|
+
}))]);
|
|
117
|
+
raw.restingHr = hkValues(rhr != null ? rhr : []);
|
|
118
|
+
raw.hrv = hkValues(hrv != null ? hrv : []);
|
|
119
|
+
raw.weightKg = hkValues(weight != null ? weight : []);
|
|
120
|
+
raw.vo2Max = hkValues(vo2 != null ? vo2 : []);
|
|
121
|
+
raw.spo2 = hkSpo2Values(spo2 != null ? spo2 : []);
|
|
122
|
+
raw.respiratoryRate = hkValues(resp != null ? resp : []);
|
|
123
|
+
raw.sleep = hkSleepSegments(sleep != null ? sleep : []);
|
|
124
|
+
const workouts = await attempt("workouts", unreadable, () => queryWorkoutSamples({
|
|
125
|
+
limit: 0,
|
|
126
|
+
ascending: true,
|
|
127
|
+
filter: {
|
|
128
|
+
date
|
|
129
|
+
}
|
|
130
|
+
}));
|
|
131
|
+
for (const w of workouts != null ? workouts : []) {
|
|
132
|
+
try {
|
|
133
|
+
const stats = {};
|
|
134
|
+
const [energy, hr] = await Promise.all([w.getStatistic("HKQuantityTypeIdentifierActiveEnergyBurned", "kcal").catch(() => void 0), w.getStatistic("HKQuantityTypeIdentifierHeartRate", "count/min").catch(() => void 0)]);
|
|
135
|
+
if (energy == null ? void 0 : energy.sumQuantity) stats.calories = energy.sumQuantity.quantity;
|
|
136
|
+
if (hr == null ? void 0 : hr.averageQuantity) stats.avgHr = hr.averageQuantity.quantity;
|
|
137
|
+
if (hr == null ? void 0 : hr.maximumQuantity) stats.maxHr = hr.maximumQuantity.quantity;
|
|
138
|
+
raw.workouts.push(hkWorkout(w, stats));
|
|
139
|
+
} finally {
|
|
140
|
+
(_a = w.dispose) == null ? void 0 : _a.call(w);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
raw,
|
|
145
|
+
unreadable: [...unreadable]
|
|
146
|
+
};
|
|
147
|
+
},
|
|
148
|
+
async revoke() {
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}export{HealthAccessNeededError,createHealthKitReader};//# sourceMappingURL=healthkitReader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"healthkitReader.js","sources":["../../../src/features/health/healthkitReader.ts"],"sourcesContent":["/**\n * Apple Health (HealthKit) reader, iOS only. Read access only: Yantra never\n * writes to Health.\n *\n * - Daily totals use HealthKit's statistics collection (one bucket per local\n * day), which merges iPhone + Apple Watch without double counting.\n * - Heart rate, HRV, sleep and the body measurements are read as samples.\n * - HealthKit never tells an app which read types were allowed, and a denied\n * type simply returns no samples; the screen says so instead of guessing.\n * - HealthKit must have been asked before anything is queried (the library\n * crashes otherwise), so a read first checks the request status and stops\n * with HealthAccessNeededError when the sheet still has to be shown.\n */\nimport {\n getRequestStatusForAuthorization,\n isHealthDataAvailableAsync,\n queryCategorySamples,\n queryQuantitySamples,\n queryStatisticsCollectionForQuantity,\n queryWorkoutSamples,\n requestAuthorization,\n AuthorizationRequestStatus,\n type ObjectTypeIdentifier,\n type QuantityTypeIdentifier,\n type UnitForIdentifier,\n} from '@kingstinct/react-native-healthkit';\nimport {\n hkDailyTotals,\n hkSleepSegments,\n hkSpo2Values,\n hkValues,\n hkWorkout,\n type HKWorkoutStats,\n} from './healthkitMapping';\nimport { emptyRawHealthData } from './model';\nimport type { HealthDataType, HealthReader, ReadResult } from './reader';\nimport type { ZoneClock } from './time';\n\nexport class HealthAccessNeededError extends Error {\n constructor() {\n super('Yantra needs to ask for access to Apple Health again.');\n this.name = 'HealthAccessNeededError';\n }\n}\n\nconst READ_TYPES: Record<HealthDataType, ObjectTypeIdentifier> = {\n steps: 'HKQuantityTypeIdentifierStepCount',\n distance: 'HKQuantityTypeIdentifierDistanceWalkingRunning',\n activeCalories: 'HKQuantityTypeIdentifierActiveEnergyBurned',\n exercise: 'HKQuantityTypeIdentifierAppleExerciseTime',\n heartRate: 'HKQuantityTypeIdentifierHeartRate',\n restingHr: 'HKQuantityTypeIdentifierRestingHeartRate',\n hrv: 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN',\n sleep: 'HKCategoryTypeIdentifierSleepAnalysis',\n workouts: 'HKWorkoutTypeIdentifier',\n weight: 'HKQuantityTypeIdentifierBodyMass',\n vo2Max: 'HKQuantityTypeIdentifierVO2Max',\n spo2: 'HKQuantityTypeIdentifierOxygenSaturation',\n respiratoryRate: 'HKQuantityTypeIdentifierRespiratoryRate',\n};\n\nconst TO_READ = Object.values(READ_TYPES);\n\n/** Heart rate is read one day at a time: a workout day is thousands of samples. */\nconst HR_CHUNK_MS = 86_400_000;\n\nasync function attempt<T>(\n type: HealthDataType,\n unreadable: Set<HealthDataType>,\n run: () => Promise<T>,\n): Promise<T | undefined> {\n try {\n return await run();\n } catch {\n unreadable.add(type);\n return undefined;\n }\n}\n\nexport function createHealthKitReader(): HealthReader {\n return {\n source: 'apple-health',\n storeName: 'Apple Health',\n\n async availability() {\n try {\n return (await isHealthDataAvailableAsync())\n ? { status: 'available' }\n : { status: 'unsupported', reason: 'Apple Health is not available on this device.' };\n } catch {\n return { status: 'unsupported', reason: 'Apple Health is not available in this build of the app.' };\n }\n },\n\n async requestAccess() {\n await requestAuthorization({ toRead: TO_READ });\n return null;\n },\n\n async grantedTypes() {\n return null;\n },\n\n async read(range, clock: ZoneClock): Promise<ReadResult> {\n const status = await getRequestStatusForAuthorization({ toRead: TO_READ });\n if (status === AuthorizationRequestStatus.shouldRequest) throw new HealthAccessNeededError();\n\n const unreadable = new Set<HealthDataType>();\n const raw = emptyRawHealthData('sdnn');\n const startDate = new Date(range.start);\n const endDate = new Date(range.end);\n const date = { startDate, endDate };\n\n const samples = <T extends QuantityTypeIdentifier>(\n type: HealthDataType,\n id: T,\n unit: UnitForIdentifier<T>,\n from = startDate,\n to = endDate,\n ) =>\n attempt(type, unreadable, () =>\n queryQuantitySamples(id, {\n limit: 0,\n ascending: true,\n unit,\n filter: { date: { startDate: from, endDate: to } },\n }),\n );\n\n // Daily totals: buckets start at the local midnight of the first full day.\n const firstDay = clock.dateOf(range.start + 12 * 3_600_000);\n const anchor = new Date(clock.startOfDay(firstDay));\n const statsRange = { date: { startDate: anchor, endDate } };\n const daily = <T extends QuantityTypeIdentifier>(type: HealthDataType, id: T, unit: UnitForIdentifier<T>) =>\n attempt(type, unreadable, () =>\n queryStatisticsCollectionForQuantity(\n id,\n ['cumulativeSum'],\n anchor,\n { day: 1 },\n { unit, filter: statsRange },\n ),\n );\n const [steps, activeCalories, distance, exercise] = await Promise.all([\n daily('steps', 'HKQuantityTypeIdentifierStepCount', 'count'),\n daily('activeCalories', 'HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal'),\n daily('distance', 'HKQuantityTypeIdentifierDistanceWalkingRunning', 'm'),\n daily('exercise', 'HKQuantityTypeIdentifierAppleExerciseTime', 'min'),\n ]);\n raw.dailyTotals = hkDailyTotals(\n { steps, activeCalories, distanceMeters: distance, activeMinutes: exercise },\n clock,\n );\n\n for (let t = range.start; t < range.end; t += HR_CHUNK_MS) {\n const chunk = await samples(\n 'heartRate',\n 'HKQuantityTypeIdentifierHeartRate',\n 'count/min',\n new Date(t),\n new Date(Math.min(range.end, t + HR_CHUNK_MS)),\n );\n if (chunk) raw.heartRate.push(...hkValues(chunk));\n }\n\n const [rhr, hrv, weight, vo2, spo2, resp, sleep] = await Promise.all([\n samples('restingHr', 'HKQuantityTypeIdentifierRestingHeartRate', 'count/min'),\n samples('hrv', 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN', 'ms'),\n samples('weight', 'HKQuantityTypeIdentifierBodyMass', 'kg'),\n samples('vo2Max', 'HKQuantityTypeIdentifierVO2Max', 'ml/(kg*min)'),\n samples('spo2', 'HKQuantityTypeIdentifierOxygenSaturation', '%'),\n samples('respiratoryRate', 'HKQuantityTypeIdentifierRespiratoryRate', 'count/min'),\n attempt('sleep', unreadable, () =>\n queryCategorySamples('HKCategoryTypeIdentifierSleepAnalysis', {\n limit: 0,\n ascending: true,\n filter: { date },\n }),\n ),\n ]);\n raw.restingHr = hkValues(rhr ?? []);\n raw.hrv = hkValues(hrv ?? []);\n raw.weightKg = hkValues(weight ?? []);\n raw.vo2Max = hkValues(vo2 ?? []);\n raw.spo2 = hkSpo2Values(spo2 ?? []);\n raw.respiratoryRate = hkValues(resp ?? []);\n raw.sleep = hkSleepSegments(sleep ?? []);\n\n const workouts = await attempt('workouts', unreadable, () =>\n queryWorkoutSamples({ limit: 0, ascending: true, filter: { date } }),\n );\n for (const w of workouts ?? []) {\n try {\n const stats: HKWorkoutStats = {};\n const [energy, hr] = await Promise.all([\n w.getStatistic('HKQuantityTypeIdentifierActiveEnergyBurned', 'kcal').catch(() => undefined),\n w.getStatistic('HKQuantityTypeIdentifierHeartRate', 'count/min').catch(() => undefined),\n ]);\n if (energy?.sumQuantity) stats.calories = energy.sumQuantity.quantity;\n if (hr?.averageQuantity) stats.avgHr = hr.averageQuantity.quantity;\n if (hr?.maximumQuantity) stats.maxHr = hr.maximumQuantity.quantity;\n raw.workouts.push(hkWorkout(w, stats));\n } finally {\n w.dispose?.();\n }\n }\n\n return { raw, unreadable: [...unreadable] };\n },\n\n async revoke() {\n // iOS has no API to give read access back; the person turns it\n // off in the Health app. Stopping sync is handled by the caller.\n },\n };\n}\n"],"names":[],"mappings":"8YAkBO,MAAM,gCAAgC,KAA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AC1D,UAAA,IAAI,EAAI,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,eAAA,EAAuB,KAAA,CAAA,KAAA,GAAQ,GAAG,eAAgB,CAAA,QAAA;AAC1D,UAAA,GAAA,CAAI,QAAS,CAAA,IAAA,CAAK,SAAU,CAAA,CAAA,EAAG,KAAK,CAAC,CAAA;AAAA,SACrC,SAAA;AACA,UAAA,CAAA,EAAA,GAAA,CAAA,CAAE,OAAF,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,CAAA,CAAA,CAAA;AAAA;AACF;AAEF,MAAO,OAAA;AAAA,QACL,GAAA;AAAA,QACA,UAAA,EAAY,CAAC,GAAG,UAAU;AAAA,OAC5B;AAAA,KACF;AAAA,IACA,MAAM,MAAS,GAAA;AAAA;AAGf,GACF;AACF"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
function emptyRawHealthData(hrvMethod) {
|
|
2
|
+
return {
|
|
3
|
+
dailyTotals: [],
|
|
4
|
+
heartRate: [],
|
|
5
|
+
restingHr: [],
|
|
6
|
+
hrv: [],
|
|
7
|
+
hrvMethod,
|
|
8
|
+
sleep: [],
|
|
9
|
+
workouts: [],
|
|
10
|
+
weightKg: [],
|
|
11
|
+
vo2Max: [],
|
|
12
|
+
spo2: [],
|
|
13
|
+
respiratoryRate: []
|
|
14
|
+
};
|
|
15
|
+
}export{emptyRawHealthData};//# sourceMappingURL=model.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.js","sources":["../../../src/features/health/model.ts"],"sourcesContent":["/**\n * What a platform reader hands the day builder: one neutral shape for HealthKit\n * and Health Connect, so the bucketing (days, nights, zones, ranges) is written\n * and tested once. The `fromHealthKit` / `fromHealthConnect` mappers turn each\n * library's records into this; the readers only fetch.\n *\n * Instants are epoch milliseconds.\n */\n\n/** Totals the platform already de-duplicated across sources (phone + watch), per local day. */\nexport interface DailyTotals {\n date: string;\n steps?: number;\n activeCalories?: number;\n distanceMeters?: number;\n activeMinutes?: number;\n}\n\nexport interface TimedValue {\n t: number;\n value: number;\n}\n\nexport type SleepStage = 'inBed' | 'asleep' | 'light' | 'deep' | 'rem' | 'awake' | 'outOfBed';\n\nexport interface SleepSegment {\n start: number;\n end: number;\n stage: SleepStage;\n /**\n * Which writer recorded it (HealthKit bundle id, Health Connect data\n * origin). A night is taken from ONE writer so a watch and a phone\n * tracking the same night are never added together.\n */\n sourceKey: string;\n}\n\nexport interface RawWorkout {\n id: string;\n start: number;\n end: number;\n /** Already normalized (see workoutTypes.ts). */\n type: string;\n /** Active time without pauses, when the source knows it. */\n durationMin?: number;\n calories?: number;\n distanceMeters?: number;\n /** From the source's own workout statistics; else derived from heart-rate samples. */\n avgHr?: number;\n maxHr?: number;\n}\n\nexport interface RawHealthData {\n dailyTotals: DailyTotals[];\n heartRate: TimedValue[];\n restingHr: TimedValue[];\n hrv: TimedValue[];\n hrvMethod: 'rmssd' | 'sdnn';\n sleep: SleepSegment[];\n workouts: RawWorkout[];\n weightKg: TimedValue[];\n vo2Max: TimedValue[];\n /** Percent, 0-100. */\n spo2: TimedValue[];\n respiratoryRate: TimedValue[];\n}\n\nexport function emptyRawHealthData(hrvMethod: 'rmssd' | 'sdnn'): RawHealthData {\n return {\n dailyTotals: [],\n heartRate: [],\n restingHr: [],\n hrv: [],\n hrvMethod,\n sleep: [],\n workouts: [],\n weightKg: [],\n vo2Max: [],\n spo2: [],\n respiratoryRate: [],\n };\n}\n"],"names":[],"mappings":"AA6DO,SAAS,mBAAmB,SAA4C,EAAA;AAC7E,EAAO,OAAA;AAAA,IACL,aAAa,EAAC;AAAA,IACd,WAAW,EAAC;AAAA,IACZ,WAAW,EAAC;AAAA,IACZ,KAAK,EAAC;AAAA,IACN,SAAA;AAAA,IACA,OAAO,EAAC;AAAA,IACR,UAAU,EAAC;AAAA,IACX,UAAU,EAAC;AAAA,IACX,QAAQ,EAAC;AAAA,IACT,MAAM,EAAC;AAAA,IACP,iBAAiB;AAAC,GACpB;AACF"}
|