@contractspec/integration.providers-impls 2.8.0 → 2.10.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.
@@ -0,0 +1,495 @@
1
+ // @bun
2
+ // src/impls/health/base-health-provider.ts
3
+ class BaseHealthProvider {
4
+ providerKey;
5
+ transport;
6
+ apiBaseUrl;
7
+ mcpUrl;
8
+ apiKey;
9
+ accessToken;
10
+ mcpAccessToken;
11
+ webhookSecret;
12
+ fetchFn;
13
+ mcpRequestId = 0;
14
+ constructor(options) {
15
+ this.providerKey = options.providerKey;
16
+ this.transport = options.transport;
17
+ this.apiBaseUrl = options.apiBaseUrl ?? "https://api.example-health.local";
18
+ this.mcpUrl = options.mcpUrl;
19
+ this.apiKey = options.apiKey;
20
+ this.accessToken = options.accessToken;
21
+ this.mcpAccessToken = options.mcpAccessToken;
22
+ this.webhookSecret = options.webhookSecret;
23
+ this.fetchFn = options.fetchFn ?? fetch;
24
+ }
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
+ };
33
+ }
34
+ async listWorkouts(params) {
35
+ const result = await this.fetchList("workouts", params);
36
+ return {
37
+ workouts: result.items,
38
+ nextCursor: result.nextCursor,
39
+ hasMore: result.hasMore,
40
+ source: this.currentSource()
41
+ };
42
+ }
43
+ async listSleep(params) {
44
+ const result = await this.fetchList("sleep", params);
45
+ return {
46
+ sleep: result.items,
47
+ nextCursor: result.nextCursor,
48
+ hasMore: result.hasMore,
49
+ source: this.currentSource()
50
+ };
51
+ }
52
+ async listBiometrics(params) {
53
+ const result = await this.fetchList("biometrics", params);
54
+ return {
55
+ biometrics: result.items,
56
+ nextCursor: result.nextCursor,
57
+ hasMore: result.hasMore,
58
+ source: this.currentSource()
59
+ };
60
+ }
61
+ async listNutrition(params) {
62
+ const result = await this.fetchList("nutrition", params);
63
+ return {
64
+ nutrition: result.items,
65
+ nextCursor: result.nextCursor,
66
+ hasMore: result.hasMore,
67
+ source: this.currentSource()
68
+ };
69
+ }
70
+ async getConnectionStatus(params) {
71
+ const payload = await this.fetchRecord("connection/status", params);
72
+ const status = readString(payload, "status") ?? "healthy";
73
+ 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)
82
+ };
83
+ }
84
+ async syncActivities(params) {
85
+ return this.sync("activities", params);
86
+ }
87
+ async syncWorkouts(params) {
88
+ return this.sync("workouts", params);
89
+ }
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);
102
+ return {
103
+ 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
110
+ };
111
+ }
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;
118
+ }
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) ?? [];
122
+ return {
123
+ items,
124
+ nextCursor: readString(payload, "nextCursor") ?? readString(payload, "cursor"),
125
+ hasMore: readBoolean(payload, "hasMore")
126
+ };
127
+ }
128
+ async sync(resource, params) {
129
+ const payload = await this.fetchRecord(`sync/${resource}`, params, "POST");
130
+ 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()
136
+ };
137
+ }
138
+ async fetchRecord(resource, params, method = "GET") {
139
+ if (this.transport.endsWith("mcp")) {
140
+ return this.callMcpTool(resource, params);
141
+ }
142
+ const url = new URL(`${this.apiBaseUrl.replace(/\/$/, "")}/${resource}`);
143
+ if (method === "GET") {
144
+ for (const [key, value] of Object.entries(params)) {
145
+ if (value == null)
146
+ continue;
147
+ if (Array.isArray(value)) {
148
+ value.forEach((item) => {
149
+ url.searchParams.append(key, String(item));
150
+ });
151
+ continue;
152
+ }
153
+ url.searchParams.set(key, String(value));
154
+ }
155
+ }
156
+ const response = await this.fetchFn(url, {
157
+ 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
163
+ });
164
+ if (!response.ok) {
165
+ const errorBody = await safeResponseText(response);
166
+ throw new Error(`${this.providerKey} ${resource} failed (${response.status}): ${errorBody}`);
167
+ }
168
+ const data = await response.json();
169
+ return asRecord(data) ?? {};
170
+ }
171
+ async callMcpTool(resource, params) {
172
+ if (!this.mcpUrl) {
173
+ return {};
174
+ }
175
+ const response = await this.fetchFn(this.mcpUrl, {
176
+ method: "POST",
177
+ headers: {
178
+ "Content-Type": "application/json",
179
+ ...this.mcpAccessToken ? { Authorization: `Bearer ${this.mcpAccessToken}` } : {}
180
+ },
181
+ body: JSON.stringify({
182
+ jsonrpc: "2.0",
183
+ id: ++this.mcpRequestId,
184
+ method: "tools/call",
185
+ params: {
186
+ name: `${this.providerKey.replace("health.", "")}_${resource.replace(/\//g, "_")}`,
187
+ arguments: params
188
+ }
189
+ })
190
+ });
191
+ if (!response.ok) {
192
+ const errorBody = await safeResponseText(response);
193
+ throw new Error(`${this.providerKey} MCP ${resource} failed (${response.status}): ${errorBody}`);
194
+ }
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;
205
+ }
206
+ currentSource() {
207
+ return {
208
+ providerKey: this.providerKey,
209
+ transport: this.transport,
210
+ route: "primary"
211
+ };
212
+ }
213
+ }
214
+ function safeJsonParse(raw) {
215
+ try {
216
+ return JSON.parse(raw);
217
+ } catch {
218
+ return { rawBody: raw };
219
+ }
220
+ }
221
+ function readHeader(headers, key) {
222
+ const match = Object.entries(headers).find(([headerKey]) => headerKey.toLowerCase() === key.toLowerCase());
223
+ if (!match)
224
+ return;
225
+ const value = match[1];
226
+ return Array.isArray(value) ? value[0] : value;
227
+ }
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;
239
+ }
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;
248
+ }
249
+ function readBoolean(record, key) {
250
+ const value = record?.[key];
251
+ return typeof value === "boolean" ? value : undefined;
252
+ }
253
+ function readNumber(record, key) {
254
+ const value = record?.[key];
255
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
256
+ }
257
+ async function safeResponseText(response) {
258
+ try {
259
+ return await response.text();
260
+ } catch {
261
+ return response.statusText;
262
+ }
263
+ }
264
+
265
+ // src/impls/health/providers.ts
266
+ function createProviderOptions(options, fallbackTransport) {
267
+ return {
268
+ ...options,
269
+ transport: options.transport ?? fallbackTransport
270
+ };
271
+ }
272
+
273
+ class OpenWearablesHealthProvider extends BaseHealthProvider {
274
+ constructor(options) {
275
+ super({
276
+ providerKey: "health.openwearables",
277
+ ...createProviderOptions(options, "aggregator-api")
278
+ });
279
+ }
280
+ }
281
+
282
+ class WhoopHealthProvider extends BaseHealthProvider {
283
+ constructor(options) {
284
+ super({
285
+ providerKey: "health.whoop",
286
+ ...createProviderOptions(options, "official-api")
287
+ });
288
+ }
289
+ }
290
+
291
+ class AppleHealthBridgeProvider extends BaseHealthProvider {
292
+ constructor(options) {
293
+ super({
294
+ providerKey: "health.apple-health",
295
+ ...createProviderOptions(options, "aggregator-api")
296
+ });
297
+ }
298
+ }
299
+
300
+ class OuraHealthProvider extends BaseHealthProvider {
301
+ constructor(options) {
302
+ super({
303
+ providerKey: "health.oura",
304
+ ...createProviderOptions(options, "official-api")
305
+ });
306
+ }
307
+ }
308
+
309
+ class StravaHealthProvider extends BaseHealthProvider {
310
+ constructor(options) {
311
+ super({
312
+ providerKey: "health.strava",
313
+ ...createProviderOptions(options, "official-api")
314
+ });
315
+ }
316
+ }
317
+
318
+ class GarminHealthProvider extends BaseHealthProvider {
319
+ constructor(options) {
320
+ super({
321
+ providerKey: "health.garmin",
322
+ ...createProviderOptions(options, "official-api")
323
+ });
324
+ }
325
+ }
326
+
327
+ class FitbitHealthProvider extends BaseHealthProvider {
328
+ constructor(options) {
329
+ super({
330
+ providerKey: "health.fitbit",
331
+ ...createProviderOptions(options, "official-api")
332
+ });
333
+ }
334
+ }
335
+
336
+ class MyFitnessPalHealthProvider extends BaseHealthProvider {
337
+ constructor(options) {
338
+ super({
339
+ providerKey: "health.myfitnesspal",
340
+ ...createProviderOptions(options, "official-api")
341
+ });
342
+ }
343
+ }
344
+
345
+ class EightSleepHealthProvider extends BaseHealthProvider {
346
+ constructor(options) {
347
+ super({
348
+ providerKey: "health.eightsleep",
349
+ ...createProviderOptions(options, "official-api")
350
+ });
351
+ }
352
+ }
353
+
354
+ class PelotonHealthProvider extends BaseHealthProvider {
355
+ constructor(options) {
356
+ super({
357
+ providerKey: "health.peloton",
358
+ ...createProviderOptions(options, "official-api")
359
+ });
360
+ }
361
+ }
362
+
363
+ class UnofficialHealthAutomationProvider extends BaseHealthProvider {
364
+ constructor(options) {
365
+ super({
366
+ ...createProviderOptions(options, "unofficial"),
367
+ providerKey: options.providerKey
368
+ });
369
+ }
370
+ }
371
+
372
+ // src/impls/health-provider-factory.ts
373
+ import {
374
+ isUnofficialHealthProviderAllowed,
375
+ resolveHealthStrategyOrder
376
+ } from "@contractspec/integration.runtime/runtime";
377
+ function createHealthProviderFromContext(context, secrets) {
378
+ const providerKey = context.spec.meta.key;
379
+ const config = toFactoryConfig(context.config);
380
+ const strategyOrder = buildStrategyOrder(config);
381
+ const errors = [];
382
+ for (const strategy of strategyOrder) {
383
+ const provider = createHealthProviderForStrategy(providerKey, strategy, config, secrets);
384
+ if (provider) {
385
+ return provider;
386
+ }
387
+ errors.push(`${strategy}: not available`);
388
+ }
389
+ throw new Error(`Unable to resolve health provider for ${providerKey}. Strategies attempted: ${errors.join(", ")}.`);
390
+ }
391
+ function createHealthProviderForStrategy(providerKey, strategy, config, secrets) {
392
+ const options = {
393
+ transport: strategy,
394
+ apiBaseUrl: config.apiBaseUrl,
395
+ mcpUrl: config.mcpUrl,
396
+ apiKey: getSecretString(secrets, "apiKey"),
397
+ accessToken: getSecretString(secrets, "accessToken"),
398
+ mcpAccessToken: getSecretString(secrets, "mcpAccessToken"),
399
+ webhookSecret: getSecretString(secrets, "webhookSecret")
400
+ };
401
+ if (strategy === "aggregator-api" || strategy === "aggregator-mcp") {
402
+ return new OpenWearablesHealthProvider(options);
403
+ }
404
+ if (strategy === "unofficial") {
405
+ if (!isUnofficialHealthProviderAllowed(providerKey, config)) {
406
+ return;
407
+ }
408
+ if (providerKey !== "health.myfitnesspal" && providerKey !== "health.eightsleep" && providerKey !== "health.peloton" && providerKey !== "health.garmin") {
409
+ return;
410
+ }
411
+ return new UnofficialHealthAutomationProvider({
412
+ ...options,
413
+ providerKey
414
+ });
415
+ }
416
+ if (strategy === "official-mcp") {
417
+ return createOfficialProvider(providerKey, {
418
+ ...options,
419
+ transport: "official-mcp"
420
+ });
421
+ }
422
+ return createOfficialProvider(providerKey, options);
423
+ }
424
+ function createOfficialProvider(providerKey, options) {
425
+ switch (providerKey) {
426
+ case "health.openwearables":
427
+ return new OpenWearablesHealthProvider(options);
428
+ case "health.whoop":
429
+ return new WhoopHealthProvider(options);
430
+ case "health.apple-health":
431
+ return new AppleHealthBridgeProvider(options);
432
+ case "health.oura":
433
+ return new OuraHealthProvider(options);
434
+ case "health.strava":
435
+ return new StravaHealthProvider(options);
436
+ case "health.garmin":
437
+ return new GarminHealthProvider(options);
438
+ case "health.fitbit":
439
+ return new FitbitHealthProvider(options);
440
+ case "health.myfitnesspal":
441
+ return new MyFitnessPalHealthProvider(options);
442
+ case "health.eightsleep":
443
+ return new EightSleepHealthProvider(options);
444
+ case "health.peloton":
445
+ return new PelotonHealthProvider(options);
446
+ default:
447
+ throw new Error(`Unsupported health provider key: ${providerKey}`);
448
+ }
449
+ }
450
+ function toFactoryConfig(config) {
451
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
452
+ return {};
453
+ }
454
+ const record = config;
455
+ return {
456
+ apiBaseUrl: asString(record.apiBaseUrl),
457
+ mcpUrl: asString(record.mcpUrl),
458
+ defaultTransport: normalizeTransport(record.defaultTransport),
459
+ strategyOrder: normalizeTransportArray(record.strategyOrder),
460
+ allowUnofficial: typeof record.allowUnofficial === "boolean" ? record.allowUnofficial : false,
461
+ unofficialAllowList: Array.isArray(record.unofficialAllowList) ? record.unofficialAllowList.map((item) => typeof item === "string" ? item : undefined).filter((item) => Boolean(item)) : undefined
462
+ };
463
+ }
464
+ function buildStrategyOrder(config) {
465
+ const order = resolveHealthStrategyOrder(config);
466
+ if (!config.defaultTransport) {
467
+ return order;
468
+ }
469
+ const withoutDefault = order.filter((item) => item !== config.defaultTransport);
470
+ return [config.defaultTransport, ...withoutDefault];
471
+ }
472
+ function normalizeTransport(value) {
473
+ if (typeof value !== "string")
474
+ return;
475
+ if (value === "official-api" || value === "official-mcp" || value === "aggregator-api" || value === "aggregator-mcp" || value === "unofficial") {
476
+ return value;
477
+ }
478
+ return;
479
+ }
480
+ function normalizeTransportArray(value) {
481
+ if (!Array.isArray(value))
482
+ return;
483
+ const transports = value.map((item) => normalizeTransport(item)).filter((item) => Boolean(item));
484
+ return transports.length > 0 ? transports : undefined;
485
+ }
486
+ function getSecretString(secrets, key) {
487
+ const value = secrets[key];
488
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
489
+ }
490
+ function asString(value) {
491
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
492
+ }
493
+ export {
494
+ createHealthProviderFromContext
495
+ };
@@ -24,4 +24,6 @@ export * from './granola-meeting-recorder';
24
24
  export * from './tldv-meeting-recorder';
25
25
  export * from './fireflies-meeting-recorder';
26
26
  export * from './fathom-meeting-recorder';
27
+ export * from './health-provider-factory';
28
+ export * from './health/providers';
27
29
  export * from './provider-factory';