@nativesquare/soma 0.3.0 → 0.4.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.
Files changed (101) hide show
  1. package/dist/client/index.d.ts +167 -0
  2. package/dist/client/index.d.ts.map +1 -1
  3. package/dist/client/index.js +150 -0
  4. package/dist/client/index.js.map +1 -1
  5. package/dist/component/_generated/api.d.ts +2 -0
  6. package/dist/component/_generated/api.d.ts.map +1 -1
  7. package/dist/component/_generated/api.js.map +1 -1
  8. package/dist/component/_generated/component.d.ts +56 -0
  9. package/dist/component/_generated/component.d.ts.map +1 -1
  10. package/dist/component/garmin.d.ts +110 -0
  11. package/dist/component/garmin.d.ts.map +1 -0
  12. package/dist/component/garmin.js +454 -0
  13. package/dist/component/garmin.js.map +1 -0
  14. package/dist/component/public.d.ts +761 -761
  15. package/dist/component/schema.d.ts +390 -388
  16. package/dist/component/schema.d.ts.map +1 -1
  17. package/dist/component/schema.js +3 -2
  18. package/dist/component/schema.js.map +1 -1
  19. package/dist/component/strava.d.ts +5 -4
  20. package/dist/component/strava.d.ts.map +1 -1
  21. package/dist/component/strava.js +18 -1
  22. package/dist/component/strava.js.map +1 -1
  23. package/dist/component/validators/activity.d.ts +42 -42
  24. package/dist/component/validators/body.d.ts +47 -47
  25. package/dist/component/validators/daily.d.ts +17 -17
  26. package/dist/component/validators/plannedWorkout.d.ts +5 -5
  27. package/dist/component/validators/samples.d.ts +2 -2
  28. package/dist/component/validators/shared.d.ts +17 -17
  29. package/dist/component/validators/sleep.d.ts +17 -17
  30. package/dist/garmin/activity.d.ts +101 -0
  31. package/dist/garmin/activity.d.ts.map +1 -0
  32. package/dist/garmin/activity.js +207 -0
  33. package/dist/garmin/activity.js.map +1 -0
  34. package/dist/garmin/auth.d.ts +65 -0
  35. package/dist/garmin/auth.d.ts.map +1 -0
  36. package/dist/garmin/auth.js +155 -0
  37. package/dist/garmin/auth.js.map +1 -0
  38. package/dist/garmin/body.d.ts +26 -0
  39. package/dist/garmin/body.d.ts.map +1 -0
  40. package/dist/garmin/body.js +44 -0
  41. package/dist/garmin/body.js.map +1 -0
  42. package/dist/garmin/client.d.ts +99 -0
  43. package/dist/garmin/client.d.ts.map +1 -0
  44. package/dist/garmin/client.js +153 -0
  45. package/dist/garmin/client.js.map +1 -0
  46. package/dist/garmin/daily.d.ts +74 -0
  47. package/dist/garmin/daily.d.ts.map +1 -0
  48. package/dist/garmin/daily.js +143 -0
  49. package/dist/garmin/daily.js.map +1 -0
  50. package/dist/garmin/index.d.ts +20 -0
  51. package/dist/garmin/index.d.ts.map +1 -0
  52. package/dist/garmin/index.js +21 -0
  53. package/dist/garmin/index.js.map +1 -0
  54. package/dist/garmin/maps/activity-type.d.ts +7 -0
  55. package/dist/garmin/maps/activity-type.d.ts.map +1 -0
  56. package/dist/garmin/maps/activity-type.js +98 -0
  57. package/dist/garmin/maps/activity-type.js.map +1 -0
  58. package/dist/garmin/maps/sleep-level.d.ts +6 -0
  59. package/dist/garmin/maps/sleep-level.d.ts.map +1 -0
  60. package/dist/garmin/maps/sleep-level.js +21 -0
  61. package/dist/garmin/maps/sleep-level.js.map +1 -0
  62. package/dist/garmin/menstruation.d.ts +23 -0
  63. package/dist/garmin/menstruation.d.ts.map +1 -0
  64. package/dist/garmin/menstruation.js +34 -0
  65. package/dist/garmin/menstruation.js.map +1 -0
  66. package/dist/garmin/sleep.d.ts +62 -0
  67. package/dist/garmin/sleep.d.ts.map +1 -0
  68. package/dist/garmin/sleep.js +125 -0
  69. package/dist/garmin/sleep.js.map +1 -0
  70. package/dist/garmin/sync.d.ts +39 -0
  71. package/dist/garmin/sync.d.ts.map +1 -0
  72. package/dist/garmin/sync.js +175 -0
  73. package/dist/garmin/sync.js.map +1 -0
  74. package/dist/garmin/types.d.ts +212 -0
  75. package/dist/garmin/types.d.ts.map +1 -0
  76. package/dist/garmin/types.js +8 -0
  77. package/dist/garmin/types.js.map +1 -0
  78. package/dist/validators.d.ts +331 -331
  79. package/package.json +5 -1
  80. package/src/client/index.ts +194 -1
  81. package/src/component/_generated/api.ts +2 -0
  82. package/src/component/_generated/component.ts +62 -0
  83. package/src/component/garmin.ts +534 -0
  84. package/src/component/schema.ts +3 -2
  85. package/src/component/strava.ts +23 -1
  86. package/src/garmin/activity.test.ts +178 -0
  87. package/src/garmin/activity.ts +272 -0
  88. package/src/garmin/auth.test.ts +128 -0
  89. package/src/garmin/auth.ts +249 -0
  90. package/src/garmin/body.ts +59 -0
  91. package/src/garmin/client.ts +254 -0
  92. package/src/garmin/daily.ts +211 -0
  93. package/src/garmin/index.ts +76 -0
  94. package/src/garmin/maps/activity-type.test.ts +78 -0
  95. package/src/garmin/maps/activity-type.ts +116 -0
  96. package/src/garmin/maps/sleep-level.ts +22 -0
  97. package/src/garmin/menstruation.ts +42 -0
  98. package/src/garmin/sleep.test.ts +110 -0
  99. package/src/garmin/sleep.ts +170 -0
  100. package/src/garmin/sync.ts +223 -0
  101. package/src/garmin/types.ts +338 -0
@@ -0,0 +1,534 @@
1
+ // ─── Garmin Component Actions ────────────────────────────────────────────────
2
+ // Public actions that handle the full Garmin OAuth + sync lifecycle.
3
+ // The host app calls these through the Soma class, which threads the
4
+ // credentials automatically from env vars or constructor config.
5
+ //
6
+ // Internal mutations manage the providerTokens table (token CRUD).
7
+
8
+ import { v } from "convex/values";
9
+ import { anyApi } from "convex/server";
10
+ import {
11
+ action,
12
+ internalMutation,
13
+ internalQuery,
14
+ } from "./_generated/server.js";
15
+ import { getRequestToken, getAccessToken } from "../garmin/auth.js";
16
+ import { GarminClient } from "../garmin/client.js";
17
+ import { transformActivity } from "../garmin/activity.js";
18
+ import { transformDaily } from "../garmin/daily.js";
19
+ import { transformSleep } from "../garmin/sleep.js";
20
+ import { transformBody } from "../garmin/body.js";
21
+ import { transformMenstruation } from "../garmin/menstruation.js";
22
+
23
+ // Use anyApi to avoid circular type references between this file and _generated/api.ts.
24
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
+ const publicApi: any = anyApi;
26
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
+ const internalApi: any = anyApi;
28
+
29
+ // Default sync window: last 30 days
30
+ const DEFAULT_SYNC_DAYS = 30;
31
+
32
+ // ─── Internal Token CRUD ─────────────────────────────────────────────────────
33
+
34
+ /**
35
+ * Store OAuth 1.0a tokens for a Garmin connection.
36
+ * Upserts by connectionId — one token record per connection.
37
+ */
38
+ export const storeTokens = internalMutation({
39
+ args: {
40
+ connectionId: v.id("connections"),
41
+ accessToken: v.string(),
42
+ tokenSecret: v.string(),
43
+ },
44
+ returns: v.null(),
45
+ handler: async (ctx, args) => {
46
+ const existing = await ctx.db
47
+ .query("providerTokens")
48
+ .withIndex("by_connectionId", (q) =>
49
+ q.eq("connectionId", args.connectionId),
50
+ )
51
+ .first();
52
+
53
+ if (existing) {
54
+ await ctx.db.patch(existing._id, {
55
+ accessToken: args.accessToken,
56
+ tokenSecret: args.tokenSecret,
57
+ });
58
+ return null;
59
+ }
60
+
61
+ await ctx.db.insert("providerTokens", {
62
+ connectionId: args.connectionId,
63
+ accessToken: args.accessToken,
64
+ tokenSecret: args.tokenSecret,
65
+ });
66
+ return null;
67
+ },
68
+ });
69
+
70
+ /**
71
+ * Get stored tokens for a connection.
72
+ */
73
+ export const getTokens = internalQuery({
74
+ args: { connectionId: v.id("connections") },
75
+ returns: v.union(
76
+ v.object({
77
+ _id: v.id("providerTokens"),
78
+ _creationTime: v.number(),
79
+ connectionId: v.id("connections"),
80
+ accessToken: v.string(),
81
+ refreshToken: v.optional(v.string()),
82
+ tokenSecret: v.optional(v.string()),
83
+ expiresAt: v.optional(v.number()),
84
+ }),
85
+ v.null(),
86
+ ),
87
+ handler: async (ctx, args) => {
88
+ return await ctx.db
89
+ .query("providerTokens")
90
+ .withIndex("by_connectionId", (q) =>
91
+ q.eq("connectionId", args.connectionId),
92
+ )
93
+ .first();
94
+ },
95
+ });
96
+
97
+ /**
98
+ * Delete stored tokens for a connection.
99
+ */
100
+ export const deleteTokens = internalMutation({
101
+ args: { connectionId: v.id("connections") },
102
+ returns: v.null(),
103
+ handler: async (ctx, args) => {
104
+ const existing = await ctx.db
105
+ .query("providerTokens")
106
+ .withIndex("by_connectionId", (q) =>
107
+ q.eq("connectionId", args.connectionId),
108
+ )
109
+ .first();
110
+
111
+ if (existing) {
112
+ await ctx.db.delete(existing._id);
113
+ }
114
+ return null;
115
+ },
116
+ });
117
+
118
+ // ─── Public Actions ──────────────────────────────────────────────────────────
119
+
120
+ /**
121
+ * Step 1 of OAuth: obtain a request token and return the authorization URL.
122
+ *
123
+ * The host app must temporarily store the returned `token` and `tokenSecret`,
124
+ * then redirect the user to `authUrl`. After the user authorizes, Garmin
125
+ * redirects back with an `oauth_verifier` which is passed to `connectGarmin`.
126
+ */
127
+ export const getGarminRequestToken = action({
128
+ args: {
129
+ consumerKey: v.string(),
130
+ consumerSecret: v.string(),
131
+ callbackUrl: v.optional(v.string()),
132
+ },
133
+ returns: v.object({
134
+ token: v.string(),
135
+ tokenSecret: v.string(),
136
+ authUrl: v.string(),
137
+ }),
138
+ handler: async (_ctx, args) => {
139
+ const result = await getRequestToken({
140
+ consumerKey: args.consumerKey,
141
+ consumerSecret: args.consumerSecret,
142
+ callbackUrl: args.callbackUrl,
143
+ });
144
+
145
+ return {
146
+ token: result.oauthToken,
147
+ tokenSecret: result.oauthTokenSecret,
148
+ authUrl: result.authUrl,
149
+ };
150
+ },
151
+ });
152
+
153
+ /**
154
+ * Step 3 of OAuth + initial sync.
155
+ *
156
+ * Exchanges the request token + verifier for permanent access tokens,
157
+ * creates/reactivates the Soma connection, stores tokens, and syncs
158
+ * the last 30 days of all data types.
159
+ */
160
+ export const connectGarmin = action({
161
+ args: {
162
+ userId: v.string(),
163
+ consumerKey: v.string(),
164
+ consumerSecret: v.string(),
165
+ token: v.string(),
166
+ tokenSecret: v.string(),
167
+ verifier: v.string(),
168
+ },
169
+ returns: v.object({
170
+ connectionId: v.string(),
171
+ synced: v.object({
172
+ activities: v.number(),
173
+ dailies: v.number(),
174
+ sleep: v.number(),
175
+ body: v.number(),
176
+ menstruation: v.number(),
177
+ }),
178
+ errors: v.array(
179
+ v.object({ type: v.string(), id: v.string(), error: v.string() }),
180
+ ),
181
+ }),
182
+ handler: async (ctx, args) => {
183
+ // 1. Exchange request token for permanent access token
184
+ const accessTokenResult = await getAccessToken({
185
+ consumerKey: args.consumerKey,
186
+ consumerSecret: args.consumerSecret,
187
+ token: args.token,
188
+ tokenSecret: args.tokenSecret,
189
+ verifier: args.verifier,
190
+ });
191
+
192
+ // 2. Create/reactivate the Soma connection
193
+ const connectionId = await ctx.runMutation(publicApi.public.connect, {
194
+ userId: args.userId,
195
+ provider: "GARMIN",
196
+ });
197
+
198
+ // 3. Store permanent OAuth tokens
199
+ await ctx.runMutation(internalApi.garmin.storeTokens, {
200
+ connectionId,
201
+ accessToken: accessTokenResult.oauthToken,
202
+ tokenSecret: accessTokenResult.oauthTokenSecret,
203
+ });
204
+
205
+ // 4. Sync last 30 days of all data types
206
+ const client = new GarminClient({
207
+ consumerKey: args.consumerKey,
208
+ consumerSecret: args.consumerSecret,
209
+ accessToken: accessTokenResult.oauthToken,
210
+ tokenSecret: accessTokenResult.oauthTokenSecret,
211
+ });
212
+
213
+ const now = Math.floor(Date.now() / 1000);
214
+ const thirtyDaysAgo = now - DEFAULT_SYNC_DAYS * 86400;
215
+ const timeRange = {
216
+ uploadStartTimeInSeconds: thirtyDaysAgo,
217
+ uploadEndTimeInSeconds: now,
218
+ };
219
+
220
+ const result = await syncAllTypes(ctx, client, {
221
+ connectionId,
222
+ userId: args.userId,
223
+ consumerKey: args.consumerKey,
224
+ consumerSecret: args.consumerSecret,
225
+ timeRange,
226
+ });
227
+
228
+ // 5. Update lastDataUpdate timestamp
229
+ await ctx.runMutation(publicApi.public.updateConnection, {
230
+ connectionId,
231
+ lastDataUpdate: new Date().toISOString(),
232
+ });
233
+
234
+ return {
235
+ connectionId,
236
+ synced: result.synced,
237
+ errors: result.errors,
238
+ };
239
+ },
240
+ });
241
+
242
+ /**
243
+ * Incremental Garmin sync for an already-connected user.
244
+ *
245
+ * Looks up the stored tokens and syncs all data types for the specified
246
+ * time range (defaults to last 30 days).
247
+ */
248
+ export const syncGarmin = action({
249
+ args: {
250
+ userId: v.string(),
251
+ consumerKey: v.string(),
252
+ consumerSecret: v.string(),
253
+ startTimeInSeconds: v.optional(v.number()),
254
+ endTimeInSeconds: v.optional(v.number()),
255
+ },
256
+ returns: v.object({
257
+ synced: v.object({
258
+ activities: v.number(),
259
+ dailies: v.number(),
260
+ sleep: v.number(),
261
+ body: v.number(),
262
+ menstruation: v.number(),
263
+ }),
264
+ errors: v.array(
265
+ v.object({ type: v.string(), id: v.string(), error: v.string() }),
266
+ ),
267
+ }),
268
+ handler: async (ctx, args) => {
269
+ // 1. Look up connection
270
+ const connection = await ctx.runQuery(
271
+ internalApi.private.getConnectionByProvider,
272
+ { userId: args.userId, provider: "GARMIN" },
273
+ );
274
+ if (!connection) {
275
+ throw new Error(
276
+ `No Garmin connection found for user "${args.userId}". ` +
277
+ "Call connectGarmin first.",
278
+ );
279
+ }
280
+ if (!connection.active) {
281
+ throw new Error(
282
+ `Garmin connection for user "${args.userId}" is inactive. Reconnect first.`,
283
+ );
284
+ }
285
+
286
+ const connectionId = connection._id;
287
+
288
+ // 2. Get stored tokens
289
+ const tokenDoc = await ctx.runQuery(internalApi.garmin.getTokens, {
290
+ connectionId,
291
+ });
292
+ if (!tokenDoc || !tokenDoc.tokenSecret) {
293
+ throw new Error(
294
+ "No Garmin tokens found for this connection. " +
295
+ "The connection may have been created before token storage was available.",
296
+ );
297
+ }
298
+
299
+ // 3. Create client and sync
300
+ const client = new GarminClient({
301
+ consumerKey: args.consumerKey,
302
+ consumerSecret: args.consumerSecret,
303
+ accessToken: tokenDoc.accessToken,
304
+ tokenSecret: tokenDoc.tokenSecret,
305
+ });
306
+
307
+ const now = Math.floor(Date.now() / 1000);
308
+ const timeRange = {
309
+ uploadStartTimeInSeconds:
310
+ args.startTimeInSeconds ?? now - DEFAULT_SYNC_DAYS * 86400,
311
+ uploadEndTimeInSeconds: args.endTimeInSeconds ?? now,
312
+ };
313
+
314
+ const result = await syncAllTypes(ctx, client, {
315
+ connectionId,
316
+ userId: args.userId,
317
+ consumerKey: args.consumerKey,
318
+ consumerSecret: args.consumerSecret,
319
+ timeRange,
320
+ });
321
+
322
+ // 4. Update lastDataUpdate timestamp
323
+ await ctx.runMutation(publicApi.public.updateConnection, {
324
+ connectionId,
325
+ lastDataUpdate: new Date().toISOString(),
326
+ });
327
+
328
+ return result;
329
+ },
330
+ });
331
+
332
+ /**
333
+ * Disconnect a user from Garmin.
334
+ *
335
+ * Deletes stored tokens and sets the connection to inactive.
336
+ * Garmin OAuth 1.0a tokens can't be revoked via API, so we just clean up locally.
337
+ */
338
+ export const disconnectGarmin = action({
339
+ args: {
340
+ userId: v.string(),
341
+ },
342
+ returns: v.null(),
343
+ handler: async (ctx, args) => {
344
+ // 1. Look up connection
345
+ const connection = await ctx.runQuery(
346
+ internalApi.private.getConnectionByProvider,
347
+ { userId: args.userId, provider: "GARMIN" },
348
+ );
349
+ if (!connection) {
350
+ throw new Error(
351
+ `No Garmin connection found for user "${args.userId}".`,
352
+ );
353
+ }
354
+
355
+ const connectionId = connection._id;
356
+
357
+ // 2. Delete stored tokens
358
+ await ctx.runMutation(internalApi.garmin.deleteTokens, { connectionId });
359
+
360
+ // 3. Set connection inactive
361
+ await ctx.runMutation(publicApi.public.disconnect, {
362
+ userId: args.userId,
363
+ provider: "GARMIN",
364
+ });
365
+
366
+ return null;
367
+ },
368
+ });
369
+
370
+ // ─── Internal Helpers ────────────────────────────────────────────────────────
371
+
372
+ interface SyncAllConfig {
373
+ connectionId: string;
374
+ userId: string;
375
+ consumerKey: string;
376
+ consumerSecret: string;
377
+ timeRange: { uploadStartTimeInSeconds: number; uploadEndTimeInSeconds: number };
378
+ }
379
+
380
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
381
+ type ActionContext = { runMutation: (ref: any, args: any) => Promise<any> };
382
+
383
+ async function syncAllTypes(
384
+ ctx: ActionContext,
385
+ client: GarminClient,
386
+ config: SyncAllConfig,
387
+ ) {
388
+ const { connectionId, userId, timeRange } = config;
389
+
390
+ const synced = { activities: 0, dailies: 0, sleep: 0, body: 0, menstruation: 0 };
391
+ const errors: Array<{ type: string; id: string; error: string }> = [];
392
+
393
+ // ── Activities ──────────────────────────────────────────────────────────
394
+ try {
395
+ const activities = await client.getActivities(timeRange);
396
+ for (const activity of activities) {
397
+ try {
398
+ const data = transformActivity(activity);
399
+ await ctx.runMutation(publicApi.public.ingestActivity, {
400
+ connectionId,
401
+ userId,
402
+ ...data,
403
+ } as never);
404
+ synced.activities++;
405
+ } catch (err) {
406
+ errors.push({
407
+ type: "activity",
408
+ id: activity.summaryId ?? String(activity.activityId),
409
+ error: err instanceof Error ? err.message : String(err),
410
+ });
411
+ }
412
+ }
413
+ } catch (err) {
414
+ errors.push({
415
+ type: "activity",
416
+ id: "fetch",
417
+ error: err instanceof Error ? err.message : String(err),
418
+ });
419
+ }
420
+
421
+ // ── Dailies ─────────────────────────────────────────────────────────────
422
+ try {
423
+ const dailies = await client.getDailies(timeRange);
424
+ for (const daily of dailies) {
425
+ try {
426
+ const data = transformDaily(daily);
427
+ await ctx.runMutation(publicApi.public.ingestDaily, {
428
+ connectionId,
429
+ userId,
430
+ ...data,
431
+ } as never);
432
+ synced.dailies++;
433
+ } catch (err) {
434
+ errors.push({
435
+ type: "daily",
436
+ id: daily.summaryId ?? daily.calendarDate,
437
+ error: err instanceof Error ? err.message : String(err),
438
+ });
439
+ }
440
+ }
441
+ } catch (err) {
442
+ errors.push({
443
+ type: "daily",
444
+ id: "fetch",
445
+ error: err instanceof Error ? err.message : String(err),
446
+ });
447
+ }
448
+
449
+ // ── Sleep ───────────────────────────────────────────────────────────────
450
+ try {
451
+ const sleeps = await client.getSleeps(timeRange);
452
+ for (const sleep of sleeps) {
453
+ try {
454
+ const data = transformSleep(sleep);
455
+ await ctx.runMutation(publicApi.public.ingestSleep, {
456
+ connectionId,
457
+ userId,
458
+ ...data,
459
+ } as never);
460
+ synced.sleep++;
461
+ } catch (err) {
462
+ errors.push({
463
+ type: "sleep",
464
+ id: sleep.summaryId ?? sleep.calendarDate,
465
+ error: err instanceof Error ? err.message : String(err),
466
+ });
467
+ }
468
+ }
469
+ } catch (err) {
470
+ errors.push({
471
+ type: "sleep",
472
+ id: "fetch",
473
+ error: err instanceof Error ? err.message : String(err),
474
+ });
475
+ }
476
+
477
+ // ── Body ────────────────────────────────────────────────────────────────
478
+ try {
479
+ const bodyComps = await client.getBodyCompositions(timeRange);
480
+ for (const body of bodyComps) {
481
+ try {
482
+ const data = transformBody(body);
483
+ await ctx.runMutation(publicApi.public.ingestBody, {
484
+ connectionId,
485
+ userId,
486
+ ...data,
487
+ } as never);
488
+ synced.body++;
489
+ } catch (err) {
490
+ errors.push({
491
+ type: "body",
492
+ id: body.summaryId ?? String(body.measurementTimeInSeconds),
493
+ error: err instanceof Error ? err.message : String(err),
494
+ });
495
+ }
496
+ }
497
+ } catch (err) {
498
+ errors.push({
499
+ type: "body",
500
+ id: "fetch",
501
+ error: err instanceof Error ? err.message : String(err),
502
+ });
503
+ }
504
+
505
+ // ── Menstruation ────────────────────────────────────────────────────────
506
+ try {
507
+ const records = await client.getMenstrualCycleData(timeRange);
508
+ for (const record of records) {
509
+ try {
510
+ const data = transformMenstruation(record);
511
+ await ctx.runMutation(publicApi.public.ingestMenstruation, {
512
+ connectionId,
513
+ userId,
514
+ ...data,
515
+ } as never);
516
+ synced.menstruation++;
517
+ } catch (err) {
518
+ errors.push({
519
+ type: "menstruation",
520
+ id: record.summaryId ?? record.calendarDate,
521
+ error: err instanceof Error ? err.message : String(err),
522
+ });
523
+ }
524
+ }
525
+ } catch (err) {
526
+ errors.push({
527
+ type: "menstruation",
528
+ id: "fetch",
529
+ error: err instanceof Error ? err.message : String(err),
530
+ });
531
+ }
532
+
533
+ return { synced, errors };
534
+ }
@@ -121,7 +121,8 @@ export default defineSchema({
121
121
  providerTokens: defineTable({
122
122
  connectionId: v.id("connections"),
123
123
  accessToken: v.string(),
124
- refreshToken: v.string(),
125
- expiresAt: v.number(), // Unix epoch seconds
124
+ refreshToken: v.optional(v.string()), // OAuth 2.0 providers (Strava)
125
+ tokenSecret: v.optional(v.string()), // OAuth 1.0a providers (Garmin)
126
+ expiresAt: v.optional(v.number()), // Unix epoch seconds; absent for permanent tokens
126
127
  }).index("by_connectionId", ["connectionId"]),
127
128
  });
@@ -40,6 +40,7 @@ export const storeTokens = internalMutation({
40
40
  refreshToken: v.string(),
41
41
  expiresAt: v.number(),
42
42
  },
43
+ returns: v.null(),
43
44
  handler: async (ctx, args) => {
44
45
  const existing = await ctx.db
45
46
  .query("providerTokens")
@@ -54,10 +55,11 @@ export const storeTokens = internalMutation({
54
55
  refreshToken: args.refreshToken,
55
56
  expiresAt: args.expiresAt,
56
57
  });
57
- return;
58
+ return null;
58
59
  }
59
60
 
60
61
  await ctx.db.insert("providerTokens", args);
62
+ return null;
61
63
  },
62
64
  });
63
65
 
@@ -66,6 +68,18 @@ export const storeTokens = internalMutation({
66
68
  */
67
69
  export const getTokens = internalQuery({
68
70
  args: { connectionId: v.id("connections") },
71
+ returns: v.union(
72
+ v.object({
73
+ _id: v.id("providerTokens"),
74
+ _creationTime: v.number(),
75
+ connectionId: v.id("connections"),
76
+ accessToken: v.string(),
77
+ refreshToken: v.optional(v.string()),
78
+ tokenSecret: v.optional(v.string()),
79
+ expiresAt: v.optional(v.number()),
80
+ }),
81
+ v.null(),
82
+ ),
69
83
  handler: async (ctx, args) => {
70
84
  return await ctx.db
71
85
  .query("providerTokens")
@@ -81,6 +95,7 @@ export const getTokens = internalQuery({
81
95
  */
82
96
  export const deleteTokens = internalMutation({
83
97
  args: { connectionId: v.id("connections") },
98
+ returns: v.null(),
84
99
  handler: async (ctx, args) => {
85
100
  const existing = await ctx.db
86
101
  .query("providerTokens")
@@ -92,6 +107,7 @@ export const deleteTokens = internalMutation({
92
107
  if (existing) {
93
108
  await ctx.db.delete(existing._id);
94
109
  }
110
+ return null;
95
111
  },
96
112
  });
97
113
 
@@ -252,6 +268,12 @@ export const syncStrava = action({
252
268
  // 3. Auto-refresh if token is expired or expiring within 5 minutes
253
269
  let accessToken = tokenDoc.accessToken;
254
270
  const now = Math.floor(Date.now() / 1000);
271
+ if (!tokenDoc.refreshToken || !tokenDoc.expiresAt) {
272
+ throw new Error(
273
+ "Strava tokens are missing refreshToken or expiresAt. " +
274
+ "This connection may have been created with an incompatible version.",
275
+ );
276
+ }
255
277
  if (tokenDoc.expiresAt < now + 300) {
256
278
  const refreshed = await refreshStravaToken({
257
279
  clientId: args.clientId,