@nativesquare/soma 0.10.2 → 0.11.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/dist/client/index.d.ts +22 -98
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +37 -105
- package/dist/client/index.js.map +1 -1
- package/dist/component/_generated/component.d.ts +20 -8
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/garmin/public.d.ts +26 -82
- package/dist/component/garmin/public.d.ts.map +1 -1
- package/dist/component/garmin/public.js +205 -500
- package/dist/component/garmin/public.js.map +1 -1
- package/package.json +1 -1
- package/src/client/index.ts +70 -116
- package/src/component/_generated/component.ts +32 -8
- package/src/component/garmin/public.ts +278 -500
|
@@ -18,10 +18,14 @@ import {
|
|
|
18
18
|
createWellnessClient,
|
|
19
19
|
createTrainingClient,
|
|
20
20
|
} from "./client.js";
|
|
21
|
-
import { buildTimeRangeQuery
|
|
21
|
+
import { buildTimeRangeQuery } from "./utils.js";
|
|
22
22
|
import {
|
|
23
23
|
createWorkoutV2 as sdkCreateWorkoutV2,
|
|
24
24
|
createWorkoutSchedule as sdkCreateWorkoutSchedule,
|
|
25
|
+
updateWorkoutV2 as sdkUpdateWorkoutV2,
|
|
26
|
+
updateWorkoutSchedule as sdkUpdateWorkoutSchedule,
|
|
27
|
+
deleteWorkoutV2 as sdkDeleteWorkoutV2,
|
|
28
|
+
deleteWorkoutSchedule as sdkDeleteWorkoutSchedule,
|
|
25
29
|
} from "./types/trainingApiWorkouts/sdk.gen";
|
|
26
30
|
import {
|
|
27
31
|
userId as sdkUserId,
|
|
@@ -54,21 +58,8 @@ import { transformRespiration } from "./transform/respiration.js";
|
|
|
54
58
|
import { transformPlannedWorkoutToGarmin } from "./transform/plannedWorkout.js";
|
|
55
59
|
import { api, internal } from "../_generated/api";
|
|
56
60
|
|
|
57
|
-
// Default sync window: last 30 days
|
|
58
|
-
const DEFAULT_SYNC_DAYS = 30;
|
|
59
|
-
|
|
60
|
-
// Refresh buffer: refresh tokens 10 minutes before expiry
|
|
61
|
-
const REFRESH_BUFFER_SECONDS = 600;
|
|
62
|
-
|
|
63
61
|
// ─── OAuth ──────────────────────────────────────────────────────────────────
|
|
64
62
|
|
|
65
|
-
/**
|
|
66
|
-
* Generate a Garmin OAuth 2.0 authorization URL with PKCE.
|
|
67
|
-
*
|
|
68
|
-
* The PKCE code verifier and state are stored in the component's
|
|
69
|
-
* `pendingOAuth` table so that `completeGarminOAuth` can look them up
|
|
70
|
-
* automatically when the callback fires via `registerRoutes`.
|
|
71
|
-
*/
|
|
72
63
|
export const getGarminAuthUrl = action({
|
|
73
64
|
args: {
|
|
74
65
|
clientId: v.string(),
|
|
@@ -98,17 +89,6 @@ export const getGarminAuthUrl = action({
|
|
|
98
89
|
},
|
|
99
90
|
});
|
|
100
91
|
|
|
101
|
-
/**
|
|
102
|
-
* Complete a Garmin OAuth 2.0 flow using stored pending state.
|
|
103
|
-
*
|
|
104
|
-
* Called internally by `registerRoutes` — the callback handler calls
|
|
105
|
-
* this with the `code` and `state` from the redirect. The action looks
|
|
106
|
-
* up the pending state (codeVerifier, userId) stored during
|
|
107
|
-
* `getGarminAuthUrl`, exchanges for tokens, creates the connection,
|
|
108
|
-
* stores tokens, and cleans up the pending entry.
|
|
109
|
-
*
|
|
110
|
-
* The host app is responsible for calling `syncGarmin` afterwards.
|
|
111
|
-
*/
|
|
112
92
|
export const completeGarminOAuth = action({
|
|
113
93
|
args: {
|
|
114
94
|
code: v.string(),
|
|
@@ -181,12 +161,6 @@ export const completeGarminOAuth = action({
|
|
|
181
161
|
},
|
|
182
162
|
});
|
|
183
163
|
|
|
184
|
-
/**
|
|
185
|
-
* Disconnect a user from Garmin.
|
|
186
|
-
*
|
|
187
|
-
* Deregisters the user via the Garmin API (best-effort), deletes stored
|
|
188
|
-
* tokens, and sets the connection to inactive.
|
|
189
|
-
*/
|
|
190
164
|
export const disconnectGarmin = action({
|
|
191
165
|
args: {
|
|
192
166
|
userId: v.string(),
|
|
@@ -796,479 +770,10 @@ export const pullAll = action({
|
|
|
796
770
|
return { synced, errors };
|
|
797
771
|
},
|
|
798
772
|
});
|
|
799
|
-
/**
|
|
800
|
-
* Incremental Garmin sync for an already-connected user.
|
|
801
|
-
*
|
|
802
|
-
* Looks up the stored tokens, refreshes if expired, and syncs all data
|
|
803
|
-
* types for the specified time range (defaults to last 30 days).
|
|
804
|
-
*/
|
|
805
|
-
|
|
806
|
-
export const syncGarmin = action({
|
|
807
|
-
args: {
|
|
808
|
-
userId: v.string(),
|
|
809
|
-
clientId: v.string(),
|
|
810
|
-
clientSecret: v.string(),
|
|
811
|
-
startTimeInSeconds: v.optional(v.number()),
|
|
812
|
-
endTimeInSeconds: v.optional(v.number()),
|
|
813
|
-
},
|
|
814
|
-
handler: async (ctx, args): Promise<{
|
|
815
|
-
synced: Record<string, number>;
|
|
816
|
-
errors: Array<{ type: string; id: string; error: string }>;
|
|
817
|
-
}> => {
|
|
818
|
-
const connection: Doc<"connections"> | null = await ctx.runQuery(
|
|
819
|
-
internal.private.getConnectionByProvider,
|
|
820
|
-
{ userId: args.userId, provider: "GARMIN" },
|
|
821
|
-
);
|
|
822
|
-
if (!connection) {
|
|
823
|
-
throw new Error(
|
|
824
|
-
`No Garmin connection found for user "${args.userId}". ` +
|
|
825
|
-
"Connect to Garmin first via getGarminAuthUrl.",
|
|
826
|
-
);
|
|
827
|
-
}
|
|
828
|
-
if (!connection.active) {
|
|
829
|
-
throw new Error(
|
|
830
|
-
`Garmin connection for user "${args.userId}" is inactive. Reconnect first.`,
|
|
831
|
-
);
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
const connectionId = connection._id;
|
|
835
|
-
|
|
836
|
-
const tokenDoc: Doc<"providerTokens"> | null = await ctx.runQuery(internal.garmin.private.getTokens, {
|
|
837
|
-
connectionId,
|
|
838
|
-
});
|
|
839
|
-
if (!tokenDoc) {
|
|
840
|
-
throw new Error(
|
|
841
|
-
"No Garmin tokens found for this connection. " +
|
|
842
|
-
"The connection may have been created before token storage was available.",
|
|
843
|
-
);
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
let accessToken = tokenDoc.accessToken;
|
|
847
|
-
|
|
848
|
-
// Refresh the token if it's expired or about to expire
|
|
849
|
-
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
850
|
-
if (
|
|
851
|
-
tokenDoc.expiresAt &&
|
|
852
|
-
tokenDoc.refreshToken &&
|
|
853
|
-
nowSeconds >= tokenDoc.expiresAt - REFRESH_BUFFER_SECONDS
|
|
854
|
-
) {
|
|
855
|
-
const refreshed = await refreshToken({
|
|
856
|
-
clientId: args.clientId,
|
|
857
|
-
clientSecret: args.clientSecret,
|
|
858
|
-
refreshToken: tokenDoc.refreshToken,
|
|
859
|
-
});
|
|
860
|
-
|
|
861
|
-
accessToken = refreshed.access_token;
|
|
862
|
-
const newExpiresAt = nowSeconds + refreshed.expires_in;
|
|
863
|
-
const _refreshed: null = await ctx.runMutation(internal.garmin.private.storeTokens, {
|
|
864
|
-
connectionId,
|
|
865
|
-
accessToken: refreshed.access_token,
|
|
866
|
-
refreshToken: refreshed.refresh_token,
|
|
867
|
-
expiresAt: newExpiresAt,
|
|
868
|
-
});
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
// Lazy backfill: resolve Garmin user ID if missing (for webhook mapping)
|
|
872
|
-
if (!connection.providerUserId) {
|
|
873
|
-
const wellnessClient = createWellnessClient(accessToken);
|
|
874
|
-
const { data: userIdData } = await sdkUserId({ client: wellnessClient });
|
|
875
|
-
const garminUserId = userIdData?.userId ?? null;
|
|
876
|
-
if (garminUserId) {
|
|
877
|
-
const _updated: null = await ctx.runMutation(api.public.updateConnection, {
|
|
878
|
-
connectionId,
|
|
879
|
-
providerUserId: garminUserId,
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
const now = Math.floor(Date.now() / 1000);
|
|
885
|
-
const timeRange = {
|
|
886
|
-
uploadStartTimeInSeconds:
|
|
887
|
-
args.startTimeInSeconds ?? now - DEFAULT_SYNC_DAYS * 86400,
|
|
888
|
-
uploadEndTimeInSeconds: args.endTimeInSeconds ?? now,
|
|
889
|
-
};
|
|
890
|
-
|
|
891
|
-
const result = await ctx.runAction(api.garmin.public.syncAllTypes, {
|
|
892
|
-
accessToken,
|
|
893
|
-
connectionId,
|
|
894
|
-
userId: args.userId,
|
|
895
|
-
uploadStartTimeInSeconds: timeRange.uploadStartTimeInSeconds,
|
|
896
|
-
uploadEndTimeInSeconds: timeRange.uploadEndTimeInSeconds,
|
|
897
|
-
});
|
|
898
|
-
|
|
899
|
-
const _updated: null = await ctx.runMutation(api.public.updateConnection, {
|
|
900
|
-
connectionId,
|
|
901
|
-
lastDataUpdate: new Date().toISOString(),
|
|
902
|
-
});
|
|
903
|
-
|
|
904
|
-
return result;
|
|
905
|
-
},
|
|
906
|
-
});
|
|
907
|
-
|
|
908
|
-
/**
|
|
909
|
-
* Fetch and ingest all Garmin wellness data types for a time range.
|
|
910
|
-
*
|
|
911
|
-
* Called by syncGarmin after obtaining a valid access token.
|
|
912
|
-
* after obtaining a valid access token.
|
|
913
|
-
*/
|
|
914
|
-
export const syncAllTypes = action({
|
|
915
|
-
args: {
|
|
916
|
-
accessToken: v.string(),
|
|
917
|
-
connectionId: v.id("connections"),
|
|
918
|
-
userId: v.string(),
|
|
919
|
-
uploadStartTimeInSeconds: v.number(),
|
|
920
|
-
uploadEndTimeInSeconds: v.number(),
|
|
921
|
-
},
|
|
922
|
-
handler: async (ctx, args) => {
|
|
923
|
-
const { accessToken, connectionId, userId } = args;
|
|
924
|
-
const timeRange = {
|
|
925
|
-
uploadStartTimeInSeconds: args.uploadStartTimeInSeconds,
|
|
926
|
-
uploadEndTimeInSeconds: args.uploadEndTimeInSeconds,
|
|
927
|
-
};
|
|
928
|
-
const wellnessClient = createWellnessClient(accessToken);
|
|
929
|
-
const query = timeRangeQuery(timeRange, accessToken);
|
|
930
|
-
|
|
931
|
-
const synced = {
|
|
932
|
-
activities: 0, dailies: 0, sleep: 0, body: 0, menstruation: 0,
|
|
933
|
-
bloodPressures: 0, skinTemp: 0, userMetrics: 0,
|
|
934
|
-
hrv: 0, stressDetails: 0, pulseOx: 0, respiration: 0,
|
|
935
|
-
};
|
|
936
|
-
const errors: Array<{ type: string; id: string; error: string }> = [];
|
|
937
|
-
|
|
938
|
-
// ── Activities ──────────────────────────────────────────────────────────
|
|
939
|
-
try {
|
|
940
|
-
const { data: activities, error } = await getActivities({ client: wellnessClient, query });
|
|
941
|
-
if (error || !activities) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
942
|
-
for (const activity of activities) {
|
|
943
|
-
try {
|
|
944
|
-
const data = transformActivity(activity);
|
|
945
|
-
await ctx.runMutation(api.public.ingestActivity, {
|
|
946
|
-
connectionId,
|
|
947
|
-
userId,
|
|
948
|
-
...data,
|
|
949
|
-
} as never);
|
|
950
|
-
synced.activities++;
|
|
951
|
-
} catch (err) {
|
|
952
|
-
errors.push({
|
|
953
|
-
type: "activity",
|
|
954
|
-
id: activity.summaryId ?? String(activity.activityId),
|
|
955
|
-
error: err instanceof Error ? err.message : String(err),
|
|
956
|
-
});
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
} catch (err) {
|
|
960
|
-
errors.push({
|
|
961
|
-
type: "activity",
|
|
962
|
-
id: "fetch",
|
|
963
|
-
error: err instanceof Error ? err.message : String(err),
|
|
964
|
-
});
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
// ── Dailies ─────────────────────────────────────────────────────────────
|
|
968
|
-
try {
|
|
969
|
-
const { data: dailies, error } = await getDailies({ client: wellnessClient, query });
|
|
970
|
-
if (error || !dailies) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
971
|
-
for (const daily of dailies) {
|
|
972
|
-
try {
|
|
973
|
-
const data = transformDailies(daily);
|
|
974
|
-
if (!data) continue;
|
|
975
|
-
await ctx.runMutation(api.public.ingestDaily, {
|
|
976
|
-
connectionId,
|
|
977
|
-
userId,
|
|
978
|
-
...data,
|
|
979
|
-
} as never);
|
|
980
|
-
synced.dailies++;
|
|
981
|
-
} catch (err) {
|
|
982
|
-
errors.push({
|
|
983
|
-
type: "daily",
|
|
984
|
-
id: daily.summaryId ?? daily.calendarDate ?? "unknown",
|
|
985
|
-
error: err instanceof Error ? err.message : String(err),
|
|
986
|
-
});
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
} catch (err) {
|
|
990
|
-
errors.push({
|
|
991
|
-
type: "daily",
|
|
992
|
-
id: "fetch",
|
|
993
|
-
error: err instanceof Error ? err.message : String(err),
|
|
994
|
-
});
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
// ── Sleep ───────────────────────────────────────────────────────────────
|
|
998
|
-
try {
|
|
999
|
-
const { data: sleeps, error } = await getSleeps({ client: wellnessClient, query });
|
|
1000
|
-
if (error || !sleeps) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1001
|
-
for (const sleep of sleeps) {
|
|
1002
|
-
try {
|
|
1003
|
-
const data = transformSleeps(sleep);
|
|
1004
|
-
await ctx.runMutation(api.public.ingestSleep, {
|
|
1005
|
-
connectionId,
|
|
1006
|
-
userId,
|
|
1007
|
-
...data,
|
|
1008
|
-
} as never);
|
|
1009
|
-
synced.sleep++;
|
|
1010
|
-
} catch (err) {
|
|
1011
|
-
errors.push({
|
|
1012
|
-
type: "sleep",
|
|
1013
|
-
id: sleep.summaryId ?? sleep.calendarDate ?? "unknown",
|
|
1014
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1015
|
-
});
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
} catch (err) {
|
|
1019
|
-
errors.push({
|
|
1020
|
-
type: "sleep",
|
|
1021
|
-
id: "fetch",
|
|
1022
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1023
|
-
});
|
|
1024
|
-
}
|
|
1025
773
|
|
|
1026
|
-
// ── Body ────────────────────────────────────────────────────────────────
|
|
1027
|
-
try {
|
|
1028
|
-
const { data: bodyComps, error } = await getBodyComps({ client: wellnessClient, query });
|
|
1029
|
-
if (error || !bodyComps) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1030
|
-
for (const body of bodyComps) {
|
|
1031
|
-
try {
|
|
1032
|
-
const data = transformBodyComposition(body);
|
|
1033
|
-
if (!data) continue;
|
|
1034
|
-
await ctx.runMutation(api.public.ingestBody, {
|
|
1035
|
-
connectionId,
|
|
1036
|
-
userId,
|
|
1037
|
-
...data,
|
|
1038
|
-
} as never);
|
|
1039
|
-
synced.body++;
|
|
1040
|
-
} catch (err) {
|
|
1041
|
-
errors.push({
|
|
1042
|
-
type: "body",
|
|
1043
|
-
id: body.summaryId ?? String(body.measurementTimeInSeconds),
|
|
1044
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1045
|
-
});
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
} catch (err) {
|
|
1049
|
-
errors.push({
|
|
1050
|
-
type: "body",
|
|
1051
|
-
id: "fetch",
|
|
1052
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1053
|
-
});
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
// ── Menstruation ────────────────────────────────────────────────────────
|
|
1057
|
-
try {
|
|
1058
|
-
const { data: records, error } = await getMct({ client: wellnessClient, query });
|
|
1059
|
-
if (error || !records) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1060
|
-
for (const record of records) {
|
|
1061
|
-
try {
|
|
1062
|
-
const data = transformMenstrualCycleTracking(record);
|
|
1063
|
-
await ctx.runMutation(api.public.ingestMenstruation, {
|
|
1064
|
-
connectionId,
|
|
1065
|
-
userId,
|
|
1066
|
-
...data,
|
|
1067
|
-
} as never);
|
|
1068
|
-
synced.menstruation++;
|
|
1069
|
-
} catch (err) {
|
|
1070
|
-
errors.push({
|
|
1071
|
-
type: "menstruation",
|
|
1072
|
-
id: record.summaryId ?? record.periodStartDate ?? "unknown",
|
|
1073
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1074
|
-
});
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
} catch (err) {
|
|
1078
|
-
errors.push({
|
|
1079
|
-
type: "menstruation",
|
|
1080
|
-
id: "fetch",
|
|
1081
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
|
|
1085
|
-
// ── Blood Pressures (→ body) ───────────────────────────────────────────
|
|
1086
|
-
try {
|
|
1087
|
-
const { data: bpRecords, error } = await getBloodPressures({ client: wellnessClient, query });
|
|
1088
|
-
if (error || !bpRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1089
|
-
for (const bp of bpRecords) {
|
|
1090
|
-
try {
|
|
1091
|
-
const data = transformBloodPressure(bp);
|
|
1092
|
-
if (!data) continue;
|
|
1093
|
-
await ctx.runMutation(api.public.ingestBody, {
|
|
1094
|
-
connectionId, userId, ...data,
|
|
1095
|
-
} as never);
|
|
1096
|
-
synced.bloodPressures++;
|
|
1097
|
-
} catch (err) {
|
|
1098
|
-
errors.push({
|
|
1099
|
-
type: "bloodPressure",
|
|
1100
|
-
id: bp.summaryId ?? String(bp.measurementTimeInSeconds),
|
|
1101
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1102
|
-
});
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
} catch (err) {
|
|
1106
|
-
errors.push({ type: "bloodPressure", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
// ── Skin Temperature (→ body) ──────────────────────────────────────────
|
|
1110
|
-
try {
|
|
1111
|
-
const { data: skinRecords, error } = await getSkinTemp({ client: wellnessClient, query });
|
|
1112
|
-
if (error || !skinRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1113
|
-
for (const skin of skinRecords) {
|
|
1114
|
-
try {
|
|
1115
|
-
const data = transformSkinTemperature(skin);
|
|
1116
|
-
if (!data) continue;
|
|
1117
|
-
await ctx.runMutation(api.public.ingestBody, {
|
|
1118
|
-
connectionId, userId, ...data,
|
|
1119
|
-
} as never);
|
|
1120
|
-
synced.skinTemp++;
|
|
1121
|
-
} catch (err) {
|
|
1122
|
-
errors.push({
|
|
1123
|
-
type: "skinTemp",
|
|
1124
|
-
id: skin.summaryId ?? skin.calendarDate ?? "unknown",
|
|
1125
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1126
|
-
});
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
} catch (err) {
|
|
1130
|
-
errors.push({ type: "skinTemp", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
// ── User Metrics (→ body) ──────────────────────────────────────────────
|
|
1134
|
-
try {
|
|
1135
|
-
const { data: metricsRecords, error } = await getUserMetrics({ client: wellnessClient, query });
|
|
1136
|
-
if (error || !metricsRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1137
|
-
for (const metrics of metricsRecords) {
|
|
1138
|
-
try {
|
|
1139
|
-
const data = transformUserMetrics(metrics);
|
|
1140
|
-
if (!data) continue;
|
|
1141
|
-
await ctx.runMutation(api.public.ingestBody, {
|
|
1142
|
-
connectionId, userId, ...data,
|
|
1143
|
-
} as never);
|
|
1144
|
-
synced.userMetrics++;
|
|
1145
|
-
} catch (err) {
|
|
1146
|
-
errors.push({
|
|
1147
|
-
type: "userMetrics",
|
|
1148
|
-
id: metrics.summaryId ?? metrics.calendarDate ?? "unknown",
|
|
1149
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1150
|
-
});
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
} catch (err) {
|
|
1154
|
-
errors.push({ type: "userMetrics", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
// ── HRV (enriches daily) ──────────────────────────────────────────────
|
|
1158
|
-
try {
|
|
1159
|
-
const { data: hrvRecords, error } = await getHrv({ client: wellnessClient, query });
|
|
1160
|
-
if (error || !hrvRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1161
|
-
for (const hrv of hrvRecords) {
|
|
1162
|
-
try {
|
|
1163
|
-
const data = transformHRVSummary(hrv);
|
|
1164
|
-
if (data) {
|
|
1165
|
-
await ctx.runMutation(api.public.ingestDaily, {
|
|
1166
|
-
connectionId, userId, ...data,
|
|
1167
|
-
} as never);
|
|
1168
|
-
synced.hrv++;
|
|
1169
|
-
}
|
|
1170
|
-
} catch (err) {
|
|
1171
|
-
errors.push({
|
|
1172
|
-
type: "hrv",
|
|
1173
|
-
id: hrv.summaryId ?? hrv.calendarDate ?? "unknown",
|
|
1174
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1175
|
-
});
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1178
|
-
} catch (err) {
|
|
1179
|
-
errors.push({ type: "hrv", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
// ── Stress Details (enriches daily) ────────────────────────────────────
|
|
1183
|
-
try {
|
|
1184
|
-
const { data: stressRecords, error } = await getStressDetails({ client: wellnessClient, query });
|
|
1185
|
-
if (error || !stressRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1186
|
-
for (const stress of stressRecords) {
|
|
1187
|
-
try {
|
|
1188
|
-
const data = transformStress(stress);
|
|
1189
|
-
if (data) {
|
|
1190
|
-
await ctx.runMutation(api.public.ingestDaily, {
|
|
1191
|
-
connectionId, userId, ...data,
|
|
1192
|
-
} as never);
|
|
1193
|
-
synced.stressDetails++;
|
|
1194
|
-
}
|
|
1195
|
-
} catch (err) {
|
|
1196
|
-
errors.push({
|
|
1197
|
-
type: "stressDetails",
|
|
1198
|
-
id: stress.summaryId ?? stress.calendarDate ?? "unknown",
|
|
1199
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1200
|
-
});
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
} catch (err) {
|
|
1204
|
-
errors.push({ type: "stressDetails", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
// ── Pulse Ox (enriches daily) ──────────────────────────────────────────
|
|
1208
|
-
try {
|
|
1209
|
-
const { data: pulseOxRecords, error } = await getPulseox({ client: wellnessClient, query });
|
|
1210
|
-
if (error || !pulseOxRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1211
|
-
for (const po of pulseOxRecords) {
|
|
1212
|
-
try {
|
|
1213
|
-
const data = transformPulseOx(po);
|
|
1214
|
-
if (data) {
|
|
1215
|
-
await ctx.runMutation(api.public.ingestDaily, {
|
|
1216
|
-
connectionId, userId, ...data,
|
|
1217
|
-
} as never);
|
|
1218
|
-
synced.pulseOx++;
|
|
1219
|
-
}
|
|
1220
|
-
} catch (err) {
|
|
1221
|
-
errors.push({
|
|
1222
|
-
type: "pulseOx",
|
|
1223
|
-
id: po.summaryId ?? po.calendarDate ?? "unknown",
|
|
1224
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1225
|
-
});
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
} catch (err) {
|
|
1229
|
-
errors.push({ type: "pulseOx", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1230
|
-
}
|
|
1231
|
-
|
|
1232
|
-
// ── Respiration (enriches daily) ───────────────────────────────────────
|
|
1233
|
-
try {
|
|
1234
|
-
const { data: respRecords, error } = await getRespiration({ client: wellnessClient, query });
|
|
1235
|
-
if (error || !respRecords) throw new Error(error ? JSON.stringify(error) : "No data");
|
|
1236
|
-
for (const resp of respRecords) {
|
|
1237
|
-
try {
|
|
1238
|
-
const data = transformRespiration(resp);
|
|
1239
|
-
if (data) {
|
|
1240
|
-
await ctx.runMutation(api.public.ingestDaily, {
|
|
1241
|
-
connectionId, userId, ...data,
|
|
1242
|
-
} as never);
|
|
1243
|
-
synced.respiration++;
|
|
1244
|
-
}
|
|
1245
|
-
} catch (err) {
|
|
1246
|
-
errors.push({
|
|
1247
|
-
type: "respiration",
|
|
1248
|
-
id: resp.summaryId ?? "unknown",
|
|
1249
|
-
error: err instanceof Error ? err.message : String(err),
|
|
1250
|
-
});
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
} catch (err) {
|
|
1254
|
-
errors.push({ type: "respiration", id: "fetch", error: err instanceof Error ? err.message : String(err) });
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
return { synced, errors };
|
|
1258
|
-
},
|
|
1259
|
-
});
|
|
1260
774
|
|
|
1261
775
|
// ─── Push ───────────────────────────────────────────────────────────────────
|
|
1262
776
|
|
|
1263
|
-
/**
|
|
1264
|
-
* Push a planned workout from Soma's DB to Garmin Connect.
|
|
1265
|
-
*
|
|
1266
|
-
* Reads the planned workout document, transforms it to Garmin Training API V2
|
|
1267
|
-
* format, creates the workout at Garmin, and optionally schedules it if a
|
|
1268
|
-
* `planned_date` is set in the metadata.
|
|
1269
|
-
*
|
|
1270
|
-
* Returns the Garmin workout ID and schedule ID (if scheduled).
|
|
1271
|
-
*/
|
|
1272
777
|
export const pushPlannedWorkout = action({
|
|
1273
778
|
args: {
|
|
1274
779
|
userId: v.string(),
|
|
@@ -1404,3 +909,276 @@ export const pushPlannedWorkout = action({
|
|
|
1404
909
|
},
|
|
1405
910
|
});
|
|
1406
911
|
|
|
912
|
+
export const pushWorkout = action({
|
|
913
|
+
args: {
|
|
914
|
+
userId: v.string(),
|
|
915
|
+
clientId: v.string(),
|
|
916
|
+
clientSecret: v.string(),
|
|
917
|
+
plannedWorkoutId: v.string(),
|
|
918
|
+
workoutProvider: v.optional(v.string()),
|
|
919
|
+
},
|
|
920
|
+
handler: async (ctx, args): Promise<{ garminWorkoutId: number }> => {
|
|
921
|
+
const { connectionId, accessToken } = await ctx.runAction(
|
|
922
|
+
internal.garmin.private.resolveConnectionAndAccessToken,
|
|
923
|
+
{ userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret },
|
|
924
|
+
);
|
|
925
|
+
|
|
926
|
+
const plannedWorkout: Doc<"plannedWorkouts"> | null = await ctx.runQuery(
|
|
927
|
+
api.public.getPlannedWorkout,
|
|
928
|
+
{ plannedWorkoutId: args.plannedWorkoutId as never },
|
|
929
|
+
);
|
|
930
|
+
if (!plannedWorkout) {
|
|
931
|
+
throw new Error(`Planned workout "${args.plannedWorkoutId}" not found.`);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
const providerName = args.workoutProvider ?? "Soma";
|
|
935
|
+
const garminWorkout = transformPlannedWorkoutToGarmin(plannedWorkout, providerName);
|
|
936
|
+
|
|
937
|
+
const trainingClient = createTrainingClient(accessToken);
|
|
938
|
+
|
|
939
|
+
const existingWorkoutId = plannedWorkout.metadata?.provider_workout_id;
|
|
940
|
+
let workoutId: number;
|
|
941
|
+
|
|
942
|
+
if (existingWorkoutId) {
|
|
943
|
+
// Update existing workout on Garmin
|
|
944
|
+
const numericId = Number(existingWorkoutId);
|
|
945
|
+
garminWorkout.workoutId = numericId;
|
|
946
|
+
const { error: updateError } = await sdkUpdateWorkoutV2({
|
|
947
|
+
client: trainingClient,
|
|
948
|
+
body: garminWorkout,
|
|
949
|
+
path: { workoutId: numericId },
|
|
950
|
+
});
|
|
951
|
+
if (updateError) {
|
|
952
|
+
throw new Error(
|
|
953
|
+
`Garmin API error updating workout: ${JSON.stringify(updateError)}`,
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
workoutId = numericId;
|
|
957
|
+
} else {
|
|
958
|
+
// Create new workout on Garmin
|
|
959
|
+
const { data: created, error: createError } = await sdkCreateWorkoutV2({
|
|
960
|
+
client: trainingClient,
|
|
961
|
+
body: garminWorkout,
|
|
962
|
+
});
|
|
963
|
+
if (createError || !created) {
|
|
964
|
+
throw new Error(
|
|
965
|
+
`Garmin API error creating workout: ${createError ? JSON.stringify(createError) : "No data"}`,
|
|
966
|
+
);
|
|
967
|
+
}
|
|
968
|
+
if (!created.workoutId) {
|
|
969
|
+
throw new Error("Garmin API did not return a workoutId after creation.");
|
|
970
|
+
}
|
|
971
|
+
workoutId = created.workoutId;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// Persist the Garmin workout ID back on the planned workout
|
|
975
|
+
const _ingested: Id<"plannedWorkouts"> = await ctx.runMutation(api.public.ingestPlannedWorkout, {
|
|
976
|
+
...plannedWorkout,
|
|
977
|
+
_id: undefined,
|
|
978
|
+
_creationTime: undefined,
|
|
979
|
+
metadata: {
|
|
980
|
+
...plannedWorkout.metadata,
|
|
981
|
+
provider_workout_id: String(workoutId),
|
|
982
|
+
},
|
|
983
|
+
} as never);
|
|
984
|
+
|
|
985
|
+
return { garminWorkoutId: workoutId };
|
|
986
|
+
},
|
|
987
|
+
});
|
|
988
|
+
|
|
989
|
+
export const pushSchedule = action({
|
|
990
|
+
args: {
|
|
991
|
+
userId: v.string(),
|
|
992
|
+
clientId: v.string(),
|
|
993
|
+
clientSecret: v.string(),
|
|
994
|
+
plannedWorkoutId: v.string(),
|
|
995
|
+
date: v.optional(v.string()),
|
|
996
|
+
},
|
|
997
|
+
handler: async (ctx, args): Promise<{ garminScheduleId: number }> => {
|
|
998
|
+
const { connectionId, accessToken } = await ctx.runAction(
|
|
999
|
+
internal.garmin.private.resolveConnectionAndAccessToken,
|
|
1000
|
+
{ userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret },
|
|
1001
|
+
);
|
|
1002
|
+
|
|
1003
|
+
const plannedWorkout: Doc<"plannedWorkouts"> | null = await ctx.runQuery(
|
|
1004
|
+
api.public.getPlannedWorkout,
|
|
1005
|
+
{ plannedWorkoutId: args.plannedWorkoutId as never },
|
|
1006
|
+
);
|
|
1007
|
+
if (!plannedWorkout) {
|
|
1008
|
+
throw new Error(`Planned workout "${args.plannedWorkoutId}" not found.`);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
const providerWorkoutId = plannedWorkout.metadata?.provider_workout_id;
|
|
1012
|
+
if (!providerWorkoutId) {
|
|
1013
|
+
throw new Error(
|
|
1014
|
+
"No Garmin workout ID found on this planned workout. Push the workout first via pushWorkout.",
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
const scheduleDate = args.date ?? plannedWorkout.metadata?.planned_date;
|
|
1019
|
+
if (!scheduleDate) {
|
|
1020
|
+
throw new Error(
|
|
1021
|
+
"No date provided and no planned_date on the workout. Provide a date argument.",
|
|
1022
|
+
);
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
const trainingClient = createTrainingClient(accessToken);
|
|
1026
|
+
|
|
1027
|
+
const existingScheduleId = plannedWorkout.metadata?.provider_schedule_id;
|
|
1028
|
+
let scheduleId: number;
|
|
1029
|
+
|
|
1030
|
+
if (existingScheduleId) {
|
|
1031
|
+
// Update existing schedule on Garmin
|
|
1032
|
+
const numericScheduleId = Number(existingScheduleId);
|
|
1033
|
+
const { error: updateError } = await sdkUpdateWorkoutSchedule({
|
|
1034
|
+
client: trainingClient,
|
|
1035
|
+
body: { workoutId: Number(providerWorkoutId), date: scheduleDate },
|
|
1036
|
+
path: { workoutScheduleId: numericScheduleId },
|
|
1037
|
+
});
|
|
1038
|
+
if (updateError) {
|
|
1039
|
+
throw new Error(
|
|
1040
|
+
`Garmin API error updating schedule: ${JSON.stringify(updateError)}`,
|
|
1041
|
+
);
|
|
1042
|
+
}
|
|
1043
|
+
scheduleId = numericScheduleId;
|
|
1044
|
+
} else {
|
|
1045
|
+
// Create new schedule on Garmin
|
|
1046
|
+
const { data: createdScheduleId, error: scheduleError } = await sdkCreateWorkoutSchedule({
|
|
1047
|
+
client: trainingClient,
|
|
1048
|
+
body: { workoutId: Number(providerWorkoutId), date: scheduleDate },
|
|
1049
|
+
});
|
|
1050
|
+
if (scheduleError) {
|
|
1051
|
+
throw new Error(
|
|
1052
|
+
`Garmin API error creating schedule: ${JSON.stringify(scheduleError)}`,
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
if (createdScheduleId == null) {
|
|
1056
|
+
throw new Error("Garmin API did not return a scheduleId after creation.");
|
|
1057
|
+
}
|
|
1058
|
+
scheduleId = createdScheduleId;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// Persist the Garmin schedule ID back on the planned workout
|
|
1062
|
+
const _ingested: Id<"plannedWorkouts"> = await ctx.runMutation(api.public.ingestPlannedWorkout, {
|
|
1063
|
+
...plannedWorkout,
|
|
1064
|
+
_id: undefined,
|
|
1065
|
+
_creationTime: undefined,
|
|
1066
|
+
metadata: {
|
|
1067
|
+
...plannedWorkout.metadata,
|
|
1068
|
+
provider_schedule_id: String(scheduleId),
|
|
1069
|
+
},
|
|
1070
|
+
} as never);
|
|
1071
|
+
|
|
1072
|
+
return { garminScheduleId: scheduleId };
|
|
1073
|
+
},
|
|
1074
|
+
});
|
|
1075
|
+
|
|
1076
|
+
// ─── Delete ───────────────────────────────────────────────────────────────────
|
|
1077
|
+
|
|
1078
|
+
export const deleteWorkout = action({
|
|
1079
|
+
args: {
|
|
1080
|
+
userId: v.string(),
|
|
1081
|
+
clientId: v.string(),
|
|
1082
|
+
clientSecret: v.string(),
|
|
1083
|
+
plannedWorkoutId: v.string(),
|
|
1084
|
+
},
|
|
1085
|
+
handler: async (ctx, args): Promise<null> => {
|
|
1086
|
+
const { connectionId, accessToken } = await ctx.runAction(
|
|
1087
|
+
internal.garmin.private.resolveConnectionAndAccessToken,
|
|
1088
|
+
{ userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret },
|
|
1089
|
+
);
|
|
1090
|
+
|
|
1091
|
+
const plannedWorkout: Doc<"plannedWorkouts"> | null = await ctx.runQuery(
|
|
1092
|
+
api.public.getPlannedWorkout,
|
|
1093
|
+
{ plannedWorkoutId: args.plannedWorkoutId as never },
|
|
1094
|
+
);
|
|
1095
|
+
if (!plannedWorkout) {
|
|
1096
|
+
throw new Error(`Planned workout "${args.plannedWorkoutId}" not found.`);
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
const providerWorkoutId = plannedWorkout.metadata?.provider_workout_id;
|
|
1100
|
+
if (!providerWorkoutId) {
|
|
1101
|
+
throw new Error("No Garmin workout ID found on this planned workout. Nothing to delete.");
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
const trainingClient = createTrainingClient(accessToken);
|
|
1105
|
+
|
|
1106
|
+
const { error: deleteError } = await sdkDeleteWorkoutV2({
|
|
1107
|
+
client: trainingClient,
|
|
1108
|
+
path: { workoutId: Number(providerWorkoutId) },
|
|
1109
|
+
});
|
|
1110
|
+
if (deleteError) {
|
|
1111
|
+
throw new Error(
|
|
1112
|
+
`Garmin API error deleting workout: ${JSON.stringify(deleteError)}`,
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// Clear both provider IDs — deleting a workout on Garmin cascades to its schedules
|
|
1117
|
+
const _ingested: Id<"plannedWorkouts"> = await ctx.runMutation(api.public.ingestPlannedWorkout, {
|
|
1118
|
+
...plannedWorkout,
|
|
1119
|
+
_id: undefined,
|
|
1120
|
+
_creationTime: undefined,
|
|
1121
|
+
metadata: {
|
|
1122
|
+
...plannedWorkout.metadata,
|
|
1123
|
+
provider_workout_id: undefined,
|
|
1124
|
+
provider_schedule_id: undefined,
|
|
1125
|
+
},
|
|
1126
|
+
} as never);
|
|
1127
|
+
|
|
1128
|
+
return null;
|
|
1129
|
+
},
|
|
1130
|
+
});
|
|
1131
|
+
|
|
1132
|
+
export const deleteSchedule = action({
|
|
1133
|
+
args: {
|
|
1134
|
+
userId: v.string(),
|
|
1135
|
+
clientId: v.string(),
|
|
1136
|
+
clientSecret: v.string(),
|
|
1137
|
+
plannedWorkoutId: v.string(),
|
|
1138
|
+
},
|
|
1139
|
+
handler: async (ctx, args): Promise<null> => {
|
|
1140
|
+
const { connectionId, accessToken } = await ctx.runAction(
|
|
1141
|
+
internal.garmin.private.resolveConnectionAndAccessToken,
|
|
1142
|
+
{ userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret },
|
|
1143
|
+
);
|
|
1144
|
+
|
|
1145
|
+
const plannedWorkout: Doc<"plannedWorkouts"> | null = await ctx.runQuery(
|
|
1146
|
+
api.public.getPlannedWorkout,
|
|
1147
|
+
{ plannedWorkoutId: args.plannedWorkoutId as never },
|
|
1148
|
+
);
|
|
1149
|
+
if (!plannedWorkout) {
|
|
1150
|
+
throw new Error(`Planned workout "${args.plannedWorkoutId}" not found.`);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
const providerScheduleId = plannedWorkout.metadata?.provider_schedule_id;
|
|
1154
|
+
if (!providerScheduleId) {
|
|
1155
|
+
throw new Error("No Garmin schedule ID found on this planned workout. Nothing to delete.");
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
const trainingClient = createTrainingClient(accessToken);
|
|
1159
|
+
|
|
1160
|
+
const { error: deleteError } = await sdkDeleteWorkoutSchedule({
|
|
1161
|
+
client: trainingClient,
|
|
1162
|
+
path: { workoutScheduleId: Number(providerScheduleId) },
|
|
1163
|
+
});
|
|
1164
|
+
if (deleteError) {
|
|
1165
|
+
throw new Error(
|
|
1166
|
+
`Garmin API error deleting schedule: ${JSON.stringify(deleteError)}`,
|
|
1167
|
+
);
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// Clear only the schedule ID — the workout still exists on Garmin
|
|
1171
|
+
const _ingested: Id<"plannedWorkouts"> = await ctx.runMutation(api.public.ingestPlannedWorkout, {
|
|
1172
|
+
...plannedWorkout,
|
|
1173
|
+
_id: undefined,
|
|
1174
|
+
_creationTime: undefined,
|
|
1175
|
+
metadata: {
|
|
1176
|
+
...plannedWorkout.metadata,
|
|
1177
|
+
provider_schedule_id: undefined,
|
|
1178
|
+
},
|
|
1179
|
+
} as never);
|
|
1180
|
+
|
|
1181
|
+
return null;
|
|
1182
|
+
},
|
|
1183
|
+
});
|
|
1184
|
+
|