@contractspec/integration.providers-impls 2.10.0 → 3.0.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 (57) hide show
  1. package/README.md +7 -1
  2. package/dist/impls/async-event-queue.d.ts +8 -0
  3. package/dist/impls/async-event-queue.js +47 -0
  4. package/dist/impls/health/base-health-provider.d.ts +64 -13
  5. package/dist/impls/health/base-health-provider.js +506 -156
  6. package/dist/impls/health/hybrid-health-providers.d.ts +34 -0
  7. package/dist/impls/health/hybrid-health-providers.js +1088 -0
  8. package/dist/impls/health/official-health-providers.d.ts +78 -0
  9. package/dist/impls/health/official-health-providers.js +968 -0
  10. package/dist/impls/health/provider-normalizers.d.ts +28 -0
  11. package/dist/impls/health/provider-normalizers.js +287 -0
  12. package/dist/impls/health/providers.d.ts +2 -39
  13. package/dist/impls/health/providers.js +895 -184
  14. package/dist/impls/health-provider-factory.js +1009 -196
  15. package/dist/impls/index.d.ts +6 -0
  16. package/dist/impls/index.js +1950 -278
  17. package/dist/impls/messaging-github.d.ts +17 -0
  18. package/dist/impls/messaging-github.js +110 -0
  19. package/dist/impls/messaging-slack.d.ts +14 -0
  20. package/dist/impls/messaging-slack.js +80 -0
  21. package/dist/impls/messaging-whatsapp-meta.d.ts +13 -0
  22. package/dist/impls/messaging-whatsapp-meta.js +52 -0
  23. package/dist/impls/messaging-whatsapp-twilio.d.ts +13 -0
  24. package/dist/impls/messaging-whatsapp-twilio.js +82 -0
  25. package/dist/impls/mistral-conversational.d.ts +23 -0
  26. package/dist/impls/mistral-conversational.js +476 -0
  27. package/dist/impls/mistral-conversational.session.d.ts +32 -0
  28. package/dist/impls/mistral-conversational.session.js +206 -0
  29. package/dist/impls/mistral-stt.d.ts +17 -0
  30. package/dist/impls/mistral-stt.js +167 -0
  31. package/dist/impls/provider-factory.d.ts +5 -1
  32. package/dist/impls/provider-factory.js +1943 -277
  33. package/dist/impls/stripe-payments.js +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1953 -278
  36. package/dist/messaging.d.ts +1 -0
  37. package/dist/messaging.js +3 -0
  38. package/dist/node/impls/async-event-queue.js +46 -0
  39. package/dist/node/impls/health/base-health-provider.js +506 -156
  40. package/dist/node/impls/health/hybrid-health-providers.js +1087 -0
  41. package/dist/node/impls/health/official-health-providers.js +967 -0
  42. package/dist/node/impls/health/provider-normalizers.js +286 -0
  43. package/dist/node/impls/health/providers.js +895 -184
  44. package/dist/node/impls/health-provider-factory.js +1009 -196
  45. package/dist/node/impls/index.js +1950 -278
  46. package/dist/node/impls/messaging-github.js +109 -0
  47. package/dist/node/impls/messaging-slack.js +79 -0
  48. package/dist/node/impls/messaging-whatsapp-meta.js +51 -0
  49. package/dist/node/impls/messaging-whatsapp-twilio.js +81 -0
  50. package/dist/node/impls/mistral-conversational.js +475 -0
  51. package/dist/node/impls/mistral-conversational.session.js +205 -0
  52. package/dist/node/impls/mistral-stt.js +166 -0
  53. package/dist/node/impls/provider-factory.js +1943 -277
  54. package/dist/node/impls/stripe-payments.js +1 -1
  55. package/dist/node/index.js +1953 -278
  56. package/dist/node/messaging.js +2 -0
  57. package/package.json +156 -12
@@ -1,5 +1,284 @@
1
1
  // @bun
2
+ // src/impls/health/provider-normalizers.ts
3
+ var DEFAULT_LIST_KEYS = [
4
+ "items",
5
+ "data",
6
+ "records",
7
+ "activities",
8
+ "workouts",
9
+ "sleep",
10
+ "biometrics",
11
+ "nutrition"
12
+ ];
13
+ function asRecord(value) {
14
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
15
+ return;
16
+ }
17
+ return value;
18
+ }
19
+ function asArray(value) {
20
+ return Array.isArray(value) ? value : undefined;
21
+ }
22
+ function readString(record, keys) {
23
+ if (!record)
24
+ return;
25
+ for (const key of keys) {
26
+ const value = record[key];
27
+ if (typeof value === "string" && value.trim().length > 0) {
28
+ return value;
29
+ }
30
+ }
31
+ return;
32
+ }
33
+ function readNumber(record, keys) {
34
+ if (!record)
35
+ return;
36
+ for (const key of keys) {
37
+ const value = record[key];
38
+ if (typeof value === "number" && Number.isFinite(value)) {
39
+ return value;
40
+ }
41
+ if (typeof value === "string" && value.trim().length > 0) {
42
+ const parsed = Number(value);
43
+ if (Number.isFinite(parsed)) {
44
+ return parsed;
45
+ }
46
+ }
47
+ }
48
+ return;
49
+ }
50
+ function readBoolean(record, keys) {
51
+ if (!record)
52
+ return;
53
+ for (const key of keys) {
54
+ const value = record[key];
55
+ if (typeof value === "boolean") {
56
+ return value;
57
+ }
58
+ }
59
+ return;
60
+ }
61
+ function extractList(payload, listKeys = DEFAULT_LIST_KEYS) {
62
+ const root = asRecord(payload);
63
+ if (!root) {
64
+ return asArray(payload)?.map((item) => asRecord(item)).filter((item) => Boolean(item)) ?? [];
65
+ }
66
+ for (const key of listKeys) {
67
+ const arrayValue = asArray(root[key]);
68
+ if (!arrayValue)
69
+ continue;
70
+ return arrayValue.map((item) => asRecord(item)).filter((item) => Boolean(item));
71
+ }
72
+ return [];
73
+ }
74
+ function extractPagination(payload) {
75
+ const root = asRecord(payload);
76
+ const nestedPagination = asRecord(root?.pagination);
77
+ const nextCursor = readString(nestedPagination, ["nextCursor", "next_cursor"]) ?? readString(root, [
78
+ "nextCursor",
79
+ "next_cursor",
80
+ "cursor",
81
+ "next_page_token"
82
+ ]);
83
+ const hasMore = readBoolean(nestedPagination, ["hasMore", "has_more"]) ?? readBoolean(root, ["hasMore", "has_more"]);
84
+ return {
85
+ nextCursor,
86
+ hasMore: hasMore ?? Boolean(nextCursor)
87
+ };
88
+ }
89
+ function toHealthActivity(item, context, fallbackType = "activity") {
90
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:${fallbackType}`;
91
+ const id = readString(item, ["id", "uuid", "workout_id"]) ?? `${context.providerKey}:activity:${externalId}`;
92
+ return {
93
+ id,
94
+ externalId,
95
+ tenantId: context.tenantId,
96
+ connectionId: context.connectionId ?? "unknown",
97
+ userId: readString(item, ["user_id", "userId", "athlete_id"]),
98
+ providerKey: context.providerKey,
99
+ activityType: readString(item, ["activity_type", "type", "sport_type", "sport"]) ?? fallbackType,
100
+ startedAt: readIsoDate(item, [
101
+ "started_at",
102
+ "start_time",
103
+ "start_date",
104
+ "created_at"
105
+ ]),
106
+ endedAt: readIsoDate(item, ["ended_at", "end_time"]),
107
+ durationSeconds: readNumber(item, [
108
+ "duration_seconds",
109
+ "duration",
110
+ "elapsed_time"
111
+ ]),
112
+ distanceMeters: readNumber(item, ["distance_meters", "distance"]),
113
+ caloriesKcal: readNumber(item, [
114
+ "calories_kcal",
115
+ "calories",
116
+ "active_kilocalories"
117
+ ]),
118
+ steps: readNumber(item, ["steps"])?.valueOf(),
119
+ metadata: item
120
+ };
121
+ }
122
+ function toHealthWorkout(item, context, fallbackType = "workout") {
123
+ const activity = toHealthActivity(item, context, fallbackType);
124
+ return {
125
+ id: activity.id,
126
+ externalId: activity.externalId,
127
+ tenantId: activity.tenantId,
128
+ connectionId: activity.connectionId,
129
+ userId: activity.userId,
130
+ providerKey: activity.providerKey,
131
+ workoutType: readString(item, [
132
+ "workout_type",
133
+ "sport_type",
134
+ "type",
135
+ "activity_type"
136
+ ]) ?? fallbackType,
137
+ startedAt: activity.startedAt,
138
+ endedAt: activity.endedAt,
139
+ durationSeconds: activity.durationSeconds,
140
+ distanceMeters: activity.distanceMeters,
141
+ caloriesKcal: activity.caloriesKcal,
142
+ averageHeartRateBpm: readNumber(item, [
143
+ "average_heart_rate",
144
+ "avg_hr",
145
+ "average_heart_rate_bpm"
146
+ ]),
147
+ maxHeartRateBpm: readNumber(item, [
148
+ "max_heart_rate",
149
+ "max_hr",
150
+ "max_heart_rate_bpm"
151
+ ]),
152
+ metadata: item
153
+ };
154
+ }
155
+ function toHealthSleep(item, context) {
156
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:sleep`;
157
+ const id = readString(item, ["id", "uuid"]) ?? `${context.providerKey}:sleep:${externalId}`;
158
+ const startedAt = readIsoDate(item, ["started_at", "start_time", "bedtime_start", "start"]) ?? new Date(0).toISOString();
159
+ const endedAt = readIsoDate(item, ["ended_at", "end_time", "bedtime_end", "end"]) ?? startedAt;
160
+ return {
161
+ id,
162
+ externalId,
163
+ tenantId: context.tenantId,
164
+ connectionId: context.connectionId ?? "unknown",
165
+ userId: readString(item, ["user_id", "userId"]),
166
+ providerKey: context.providerKey,
167
+ startedAt,
168
+ endedAt,
169
+ durationSeconds: readNumber(item, [
170
+ "duration_seconds",
171
+ "duration",
172
+ "total_sleep_duration"
173
+ ]),
174
+ deepSleepSeconds: readNumber(item, [
175
+ "deep_sleep_seconds",
176
+ "deep_sleep_duration"
177
+ ]),
178
+ lightSleepSeconds: readNumber(item, [
179
+ "light_sleep_seconds",
180
+ "light_sleep_duration"
181
+ ]),
182
+ remSleepSeconds: readNumber(item, [
183
+ "rem_sleep_seconds",
184
+ "rem_sleep_duration"
185
+ ]),
186
+ awakeSeconds: readNumber(item, ["awake_seconds", "awake_time"]),
187
+ sleepScore: readNumber(item, ["sleep_score", "score"]),
188
+ metadata: item
189
+ };
190
+ }
191
+ function toHealthBiometric(item, context, metricTypeFallback = "metric") {
192
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:biometric`;
193
+ const id = readString(item, ["id", "uuid"]) ?? `${context.providerKey}:biometric:${externalId}`;
194
+ return {
195
+ id,
196
+ externalId,
197
+ tenantId: context.tenantId,
198
+ connectionId: context.connectionId ?? "unknown",
199
+ userId: readString(item, ["user_id", "userId"]),
200
+ providerKey: context.providerKey,
201
+ metricType: readString(item, ["metric_type", "metric", "type", "name"]) ?? metricTypeFallback,
202
+ value: readNumber(item, ["value", "score", "measurement"]) ?? 0,
203
+ unit: readString(item, ["unit"]),
204
+ measuredAt: readIsoDate(item, ["measured_at", "timestamp", "created_at"]) ?? new Date().toISOString(),
205
+ metadata: item
206
+ };
207
+ }
208
+ function toHealthNutrition(item, context) {
209
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:nutrition`;
210
+ const id = readString(item, ["id", "uuid"]) ?? `${context.providerKey}:nutrition:${externalId}`;
211
+ return {
212
+ id,
213
+ externalId,
214
+ tenantId: context.tenantId,
215
+ connectionId: context.connectionId ?? "unknown",
216
+ userId: readString(item, ["user_id", "userId"]),
217
+ providerKey: context.providerKey,
218
+ loggedAt: readIsoDate(item, ["logged_at", "created_at", "date", "timestamp"]) ?? new Date().toISOString(),
219
+ caloriesKcal: readNumber(item, ["calories_kcal", "calories"]),
220
+ proteinGrams: readNumber(item, ["protein_grams", "protein"]),
221
+ carbsGrams: readNumber(item, ["carbs_grams", "carbs"]),
222
+ fatGrams: readNumber(item, ["fat_grams", "fat"]),
223
+ fiberGrams: readNumber(item, ["fiber_grams", "fiber"]),
224
+ hydrationMl: readNumber(item, ["hydration_ml", "water_ml", "water"]),
225
+ metadata: item
226
+ };
227
+ }
228
+ function toHealthConnectionStatus(payload, params, source) {
229
+ const record = asRecord(payload);
230
+ const rawStatus = readString(record, ["status", "connection_status", "health"]) ?? "healthy";
231
+ return {
232
+ tenantId: params.tenantId,
233
+ connectionId: params.connectionId,
234
+ status: rawStatus === "healthy" || rawStatus === "degraded" || rawStatus === "error" || rawStatus === "disconnected" ? rawStatus : "healthy",
235
+ source,
236
+ lastCheckedAt: readIsoDate(record, ["last_checked_at", "lastCheckedAt"]) ?? new Date().toISOString(),
237
+ errorCode: readString(record, ["error_code", "errorCode"]),
238
+ errorMessage: readString(record, ["error_message", "errorMessage"]),
239
+ metadata: asRecord(record?.metadata)
240
+ };
241
+ }
242
+ function toHealthWebhookEvent(payload, providerKey, verified) {
243
+ const record = asRecord(payload);
244
+ const entityType = readString(record, ["entity_type", "entityType", "type"]);
245
+ const normalizedEntityType = entityType === "activity" || entityType === "workout" || entityType === "sleep" || entityType === "biometric" || entityType === "nutrition" ? entityType : undefined;
246
+ return {
247
+ providerKey,
248
+ eventType: readString(record, ["event_type", "eventType", "event"]),
249
+ externalEntityId: readString(record, [
250
+ "external_entity_id",
251
+ "externalEntityId",
252
+ "entity_id",
253
+ "entityId",
254
+ "id"
255
+ ]),
256
+ entityType: normalizedEntityType,
257
+ receivedAt: new Date().toISOString(),
258
+ verified,
259
+ payload,
260
+ metadata: asRecord(record?.metadata)
261
+ };
262
+ }
263
+ function readIsoDate(record, keys) {
264
+ const value = readString(record, keys);
265
+ if (!value)
266
+ return;
267
+ const parsed = new Date(value);
268
+ if (Number.isNaN(parsed.getTime()))
269
+ return;
270
+ return parsed.toISOString();
271
+ }
272
+
2
273
  // src/impls/health/base-health-provider.ts
274
+ class HealthProviderCapabilityError extends Error {
275
+ code = "NOT_SUPPORTED";
276
+ constructor(message) {
277
+ super(message);
278
+ this.name = "HealthProviderCapabilityError";
279
+ }
280
+ }
281
+
3
282
  class BaseHealthProvider {
4
283
  providerKey;
5
284
  transport;
@@ -7,146 +286,191 @@ class BaseHealthProvider {
7
286
  mcpUrl;
8
287
  apiKey;
9
288
  accessToken;
289
+ refreshToken;
10
290
  mcpAccessToken;
11
291
  webhookSecret;
292
+ webhookSignatureHeader;
293
+ route;
294
+ aggregatorKey;
295
+ oauth;
12
296
  fetchFn;
13
297
  mcpRequestId = 0;
14
298
  constructor(options) {
15
299
  this.providerKey = options.providerKey;
16
300
  this.transport = options.transport;
17
- this.apiBaseUrl = options.apiBaseUrl ?? "https://api.example-health.local";
301
+ this.apiBaseUrl = options.apiBaseUrl;
18
302
  this.mcpUrl = options.mcpUrl;
19
303
  this.apiKey = options.apiKey;
20
304
  this.accessToken = options.accessToken;
305
+ this.refreshToken = options.oauth?.refreshToken;
21
306
  this.mcpAccessToken = options.mcpAccessToken;
22
307
  this.webhookSecret = options.webhookSecret;
308
+ this.webhookSignatureHeader = options.webhookSignatureHeader ?? "x-webhook-signature";
309
+ this.route = options.route ?? "primary";
310
+ this.aggregatorKey = options.aggregatorKey;
311
+ this.oauth = options.oauth ?? {};
23
312
  this.fetchFn = options.fetchFn ?? fetch;
24
313
  }
25
- async listActivities(params) {
26
- const result = await this.fetchList("activities", params);
27
- return {
28
- activities: result.items,
29
- nextCursor: result.nextCursor,
30
- hasMore: result.hasMore,
31
- source: this.currentSource()
32
- };
314
+ async listActivities(_params) {
315
+ throw this.unsupported("activities");
316
+ }
317
+ async listWorkouts(_params) {
318
+ throw this.unsupported("workouts");
319
+ }
320
+ async listSleep(_params) {
321
+ throw this.unsupported("sleep");
322
+ }
323
+ async listBiometrics(_params) {
324
+ throw this.unsupported("biometrics");
325
+ }
326
+ async listNutrition(_params) {
327
+ throw this.unsupported("nutrition");
328
+ }
329
+ async getConnectionStatus(params) {
330
+ return this.fetchConnectionStatus(params, {
331
+ mcpTool: `${this.providerSlug()}_connection_status`
332
+ });
333
+ }
334
+ async syncActivities(params) {
335
+ return this.syncFromList(() => this.listActivities(params));
33
336
  }
34
- async listWorkouts(params) {
35
- const result = await this.fetchList("workouts", params);
337
+ async syncWorkouts(params) {
338
+ return this.syncFromList(() => this.listWorkouts(params));
339
+ }
340
+ async syncSleep(params) {
341
+ return this.syncFromList(() => this.listSleep(params));
342
+ }
343
+ async syncBiometrics(params) {
344
+ return this.syncFromList(() => this.listBiometrics(params));
345
+ }
346
+ async syncNutrition(params) {
347
+ return this.syncFromList(() => this.listNutrition(params));
348
+ }
349
+ async parseWebhook(request) {
350
+ const payload = request.parsedBody ?? safeJsonParse(request.rawBody);
351
+ const verified = await this.verifyWebhook(request);
352
+ return toHealthWebhookEvent(payload, this.providerKey, verified);
353
+ }
354
+ async verifyWebhook(request) {
355
+ if (!this.webhookSecret)
356
+ return true;
357
+ const signature = readHeader(request.headers, this.webhookSignatureHeader);
358
+ return signature === this.webhookSecret;
359
+ }
360
+ async fetchActivities(params, config) {
361
+ const response = await this.fetchList(params, config);
36
362
  return {
37
- workouts: result.items,
38
- nextCursor: result.nextCursor,
39
- hasMore: result.hasMore,
363
+ activities: response.items,
364
+ nextCursor: response.nextCursor,
365
+ hasMore: response.hasMore,
40
366
  source: this.currentSource()
41
367
  };
42
368
  }
43
- async listSleep(params) {
44
- const result = await this.fetchList("sleep", params);
369
+ async fetchWorkouts(params, config) {
370
+ const response = await this.fetchList(params, config);
45
371
  return {
46
- sleep: result.items,
47
- nextCursor: result.nextCursor,
48
- hasMore: result.hasMore,
372
+ workouts: response.items,
373
+ nextCursor: response.nextCursor,
374
+ hasMore: response.hasMore,
49
375
  source: this.currentSource()
50
376
  };
51
377
  }
52
- async listBiometrics(params) {
53
- const result = await this.fetchList("biometrics", params);
378
+ async fetchSleep(params, config) {
379
+ const response = await this.fetchList(params, config);
54
380
  return {
55
- biometrics: result.items,
56
- nextCursor: result.nextCursor,
57
- hasMore: result.hasMore,
381
+ sleep: response.items,
382
+ nextCursor: response.nextCursor,
383
+ hasMore: response.hasMore,
58
384
  source: this.currentSource()
59
385
  };
60
386
  }
61
- async listNutrition(params) {
62
- const result = await this.fetchList("nutrition", params);
387
+ async fetchBiometrics(params, config) {
388
+ const response = await this.fetchList(params, config);
63
389
  return {
64
- nutrition: result.items,
65
- nextCursor: result.nextCursor,
66
- hasMore: result.hasMore,
390
+ biometrics: response.items,
391
+ nextCursor: response.nextCursor,
392
+ hasMore: response.hasMore,
67
393
  source: this.currentSource()
68
394
  };
69
395
  }
70
- async getConnectionStatus(params) {
71
- const payload = await this.fetchRecord("connection/status", params);
72
- const status = readString(payload, "status") ?? "healthy";
396
+ async fetchNutrition(params, config) {
397
+ const response = await this.fetchList(params, config);
73
398
  return {
74
- tenantId: params.tenantId,
75
- connectionId: params.connectionId,
76
- status: status === "healthy" || status === "degraded" || status === "error" || status === "disconnected" ? status : "healthy",
77
- source: this.currentSource(),
78
- lastCheckedAt: readString(payload, "lastCheckedAt") ?? new Date().toISOString(),
79
- errorCode: readString(payload, "errorCode"),
80
- errorMessage: readString(payload, "errorMessage"),
81
- metadata: asRecord(payload.metadata)
399
+ nutrition: response.items,
400
+ nextCursor: response.nextCursor,
401
+ hasMore: response.hasMore,
402
+ source: this.currentSource()
82
403
  };
83
404
  }
84
- async syncActivities(params) {
85
- return this.sync("activities", params);
86
- }
87
- async syncWorkouts(params) {
88
- return this.sync("workouts", params);
405
+ async fetchConnectionStatus(params, config) {
406
+ const payload = await this.fetchPayload(config, params);
407
+ return toHealthConnectionStatus(payload, params, this.currentSource());
89
408
  }
90
- async syncSleep(params) {
91
- return this.sync("sleep", params);
92
- }
93
- async syncBiometrics(params) {
94
- return this.sync("biometrics", params);
95
- }
96
- async syncNutrition(params) {
97
- return this.sync("nutrition", params);
98
- }
99
- async parseWebhook(request) {
100
- const payload = request.parsedBody ?? safeJsonParse(request.rawBody);
101
- const body = asRecord(payload);
409
+ currentSource() {
102
410
  return {
103
411
  providerKey: this.providerKey,
104
- eventType: readString(body, "eventType") ?? readString(body, "event"),
105
- externalEntityId: readString(body, "externalEntityId") ?? readString(body, "entityId"),
106
- entityType: normalizeEntityType(readString(body, "entityType") ?? readString(body, "type")),
107
- receivedAt: new Date().toISOString(),
108
- verified: await this.verifyWebhook(request),
109
- payload
412
+ transport: this.transport,
413
+ route: this.route,
414
+ aggregatorKey: this.aggregatorKey
110
415
  };
111
416
  }
112
- async verifyWebhook(request) {
113
- if (!this.webhookSecret) {
114
- return true;
115
- }
116
- const signature = readHeader(request.headers, "x-webhook-signature");
117
- return signature === this.webhookSecret;
417
+ providerSlug() {
418
+ return this.providerKey.replace("health.", "").replace(/-/g, "_");
118
419
  }
119
- async fetchList(resource, params) {
120
- const payload = await this.fetchRecord(resource, params);
121
- const items = asArray(payload.items) ?? asArray(payload[resource]) ?? asArray(payload.records) ?? [];
420
+ unsupported(capability) {
421
+ return new HealthProviderCapabilityError(`${this.providerKey} does not support ${capability}`);
422
+ }
423
+ async syncFromList(executor) {
424
+ const result = await executor();
425
+ const records = countResultRecords(result);
122
426
  return {
123
- items,
124
- nextCursor: readString(payload, "nextCursor") ?? readString(payload, "cursor"),
125
- hasMore: readBoolean(payload, "hasMore")
427
+ synced: records,
428
+ failed: 0,
429
+ nextCursor: undefined,
430
+ source: result.source
126
431
  };
127
432
  }
128
- async sync(resource, params) {
129
- const payload = await this.fetchRecord(`sync/${resource}`, params, "POST");
433
+ async fetchList(params, config) {
434
+ const payload = await this.fetchPayload(config, params);
435
+ const items = extractList(payload, config.listKeys).map((item) => config.mapItem(item, params)).filter((item) => Boolean(item));
436
+ const pagination = extractPagination(payload);
130
437
  return {
131
- synced: readNumber(payload, "synced") ?? 0,
132
- failed: readNumber(payload, "failed") ?? 0,
133
- nextCursor: readString(payload, "nextCursor"),
134
- errors: asArray(payload.errors)?.map((item) => String(item)),
135
- source: this.currentSource()
438
+ items,
439
+ nextCursor: pagination.nextCursor,
440
+ hasMore: pagination.hasMore
136
441
  };
137
442
  }
138
- async fetchRecord(resource, params, method = "GET") {
139
- if (this.transport.endsWith("mcp")) {
140
- return this.callMcpTool(resource, params);
443
+ async fetchPayload(config, params) {
444
+ const method = config.method ?? "GET";
445
+ const query = config.buildQuery?.(params);
446
+ const body = config.buildBody?.(params);
447
+ if (this.isMcpTransport()) {
448
+ return this.callMcpTool(config.mcpTool, {
449
+ ...query ?? {},
450
+ ...body ?? {}
451
+ });
452
+ }
453
+ if (!config.apiPath || !this.apiBaseUrl) {
454
+ throw new Error(`${this.providerKey} transport is missing an API path.`);
141
455
  }
142
- const url = new URL(`${this.apiBaseUrl.replace(/\/$/, "")}/${resource}`);
143
- if (method === "GET") {
144
- for (const [key, value] of Object.entries(params)) {
456
+ if (method === "POST") {
457
+ return this.requestApi(config.apiPath, "POST", undefined, body);
458
+ }
459
+ return this.requestApi(config.apiPath, "GET", query, undefined);
460
+ }
461
+ isMcpTransport() {
462
+ return this.transport.endsWith("mcp") || this.transport === "unofficial";
463
+ }
464
+ async requestApi(path, method, query, body) {
465
+ const url = new URL(path, ensureTrailingSlash(this.apiBaseUrl ?? ""));
466
+ if (query) {
467
+ for (const [key, value] of Object.entries(query)) {
145
468
  if (value == null)
146
469
  continue;
147
470
  if (Array.isArray(value)) {
148
- value.forEach((item) => {
149
- url.searchParams.append(key, String(item));
471
+ value.forEach((entry) => {
472
+ if (entry != null)
473
+ url.searchParams.append(key, String(entry));
150
474
  });
151
475
  continue;
152
476
  }
@@ -155,22 +479,22 @@ class BaseHealthProvider {
155
479
  }
156
480
  const response = await this.fetchFn(url, {
157
481
  method,
158
- headers: {
159
- "Content-Type": "application/json",
160
- ...this.accessToken || this.apiKey ? { Authorization: `Bearer ${this.accessToken ?? this.apiKey}` } : {}
161
- },
162
- body: method === "POST" ? JSON.stringify(params) : undefined
482
+ headers: this.authorizationHeaders(),
483
+ body: method === "POST" ? JSON.stringify(body ?? {}) : undefined
163
484
  });
164
- if (!response.ok) {
165
- const errorBody = await safeResponseText(response);
166
- throw new Error(`${this.providerKey} ${resource} failed (${response.status}): ${errorBody}`);
485
+ if (response.status === 401 && await this.refreshAccessToken()) {
486
+ const retryResponse = await this.fetchFn(url, {
487
+ method,
488
+ headers: this.authorizationHeaders(),
489
+ body: method === "POST" ? JSON.stringify(body ?? {}) : undefined
490
+ });
491
+ return this.readResponsePayload(retryResponse, path);
167
492
  }
168
- const data = await response.json();
169
- return asRecord(data) ?? {};
493
+ return this.readResponsePayload(response, path);
170
494
  }
171
- async callMcpTool(resource, params) {
495
+ async callMcpTool(toolName, args) {
172
496
  if (!this.mcpUrl) {
173
- return {};
497
+ throw new Error(`${this.providerKey} MCP URL is not configured.`);
174
498
  }
175
499
  const response = await this.fetchFn(this.mcpUrl, {
176
500
  method: "POST",
@@ -183,78 +507,103 @@ class BaseHealthProvider {
183
507
  id: ++this.mcpRequestId,
184
508
  method: "tools/call",
185
509
  params: {
186
- name: `${this.providerKey.replace("health.", "")}_${resource.replace(/\//g, "_")}`,
187
- arguments: params
510
+ name: toolName,
511
+ arguments: args
188
512
  }
189
513
  })
190
514
  });
191
- if (!response.ok) {
192
- const errorBody = await safeResponseText(response);
193
- throw new Error(`${this.providerKey} MCP ${resource} failed (${response.status}): ${errorBody}`);
515
+ const payload = await this.readResponsePayload(response, toolName);
516
+ const rpcEnvelope = asRecord(payload);
517
+ if (!rpcEnvelope)
518
+ return payload;
519
+ const rpcResult = asRecord(rpcEnvelope.result);
520
+ if (rpcResult) {
521
+ return rpcResult.structuredContent ?? rpcResult.data ?? rpcResult;
194
522
  }
195
- const rpcPayload = await response.json();
196
- const rpc = asRecord(rpcPayload);
197
- const result = asRecord(rpc?.result) ?? {};
198
- const structured = asRecord(result.structuredContent);
199
- if (structured)
200
- return structured;
201
- const data = asRecord(result.data);
202
- if (data)
203
- return data;
204
- return result;
523
+ return rpcEnvelope.structuredContent ?? rpcEnvelope.data ?? rpcEnvelope;
205
524
  }
206
- currentSource() {
525
+ authorizationHeaders() {
526
+ const token = this.accessToken ?? this.apiKey;
207
527
  return {
208
- providerKey: this.providerKey,
209
- transport: this.transport,
210
- route: "primary"
528
+ "Content-Type": "application/json",
529
+ ...token ? { Authorization: `Bearer ${token}` } : {}
211
530
  };
212
531
  }
213
- }
214
- function safeJsonParse(raw) {
215
- try {
216
- return JSON.parse(raw);
217
- } catch {
218
- return { rawBody: raw };
532
+ async refreshAccessToken() {
533
+ if (!this.oauth.tokenUrl || !this.refreshToken) {
534
+ return false;
535
+ }
536
+ const tokenUrl = new URL(this.oauth.tokenUrl);
537
+ const body = new URLSearchParams({
538
+ grant_type: "refresh_token",
539
+ refresh_token: this.refreshToken,
540
+ ...this.oauth.clientId ? { client_id: this.oauth.clientId } : {},
541
+ ...this.oauth.clientSecret ? { client_secret: this.oauth.clientSecret } : {}
542
+ });
543
+ const response = await this.fetchFn(tokenUrl, {
544
+ method: "POST",
545
+ headers: {
546
+ "Content-Type": "application/x-www-form-urlencoded"
547
+ },
548
+ body: body.toString()
549
+ });
550
+ if (!response.ok) {
551
+ return false;
552
+ }
553
+ const payload = await response.json();
554
+ this.accessToken = payload.access_token;
555
+ this.refreshToken = payload.refresh_token ?? this.refreshToken;
556
+ if (typeof payload.expires_in === "number") {
557
+ this.oauth.tokenExpiresAt = new Date(Date.now() + payload.expires_in * 1000).toISOString();
558
+ }
559
+ return Boolean(this.accessToken);
560
+ }
561
+ async readResponsePayload(response, context) {
562
+ if (!response.ok) {
563
+ const message = await safeReadText(response);
564
+ throw new Error(`${this.providerKey} request ${context} failed (${response.status}): ${message}`);
565
+ }
566
+ if (response.status === 204) {
567
+ return {};
568
+ }
569
+ return response.json();
219
570
  }
220
571
  }
221
572
  function readHeader(headers, key) {
222
- const match = Object.entries(headers).find(([headerKey]) => headerKey.toLowerCase() === key.toLowerCase());
223
- if (!match)
573
+ const target = key.toLowerCase();
574
+ const entry = Object.entries(headers).find(([headerKey]) => headerKey.toLowerCase() === target);
575
+ if (!entry)
224
576
  return;
225
- const value = match[1];
577
+ const value = entry[1];
226
578
  return Array.isArray(value) ? value[0] : value;
227
579
  }
228
- function normalizeEntityType(value) {
229
- if (!value)
230
- return;
231
- if (value === "activity" || value === "workout" || value === "sleep" || value === "biometric" || value === "nutrition") {
232
- return value;
233
- }
234
- return;
235
- }
236
- function asRecord(value) {
237
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
238
- return;
580
+ function countResultRecords(result) {
581
+ const listKeys = [
582
+ "activities",
583
+ "workouts",
584
+ "sleep",
585
+ "biometrics",
586
+ "nutrition"
587
+ ];
588
+ for (const key of listKeys) {
589
+ const value = result[key];
590
+ if (Array.isArray(value)) {
591
+ return value.length;
592
+ }
239
593
  }
240
- return value;
241
- }
242
- function asArray(value) {
243
- return Array.isArray(value) ? value : undefined;
244
- }
245
- function readString(record, key) {
246
- const value = record?.[key];
247
- return typeof value === "string" ? value : undefined;
594
+ return 0;
248
595
  }
249
- function readBoolean(record, key) {
250
- const value = record?.[key];
251
- return typeof value === "boolean" ? value : undefined;
596
+ function ensureTrailingSlash(value) {
597
+ return value.endsWith("/") ? value : `${value}/`;
252
598
  }
253
- function readNumber(record, key) {
254
- const value = record?.[key];
255
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
599
+ function safeJsonParse(raw) {
600
+ try {
601
+ return JSON.parse(raw);
602
+ } catch {
603
+ return { rawBody: raw };
604
+ }
256
605
  }
257
- async function safeResponseText(response) {
606
+ async function safeReadText(response) {
258
607
  try {
259
608
  return await response.text();
260
609
  } catch {
@@ -262,5 +611,6 @@ async function safeResponseText(response) {
262
611
  }
263
612
  }
264
613
  export {
614
+ HealthProviderCapabilityError,
265
615
  BaseHealthProvider
266
616
  };