@contractspec/example.integration-hub 3.8.9 → 3.8.10

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 (89) hide show
  1. package/dist/connection/connection.enum.js +1 -29
  2. package/dist/connection/connection.operation.js +1 -124
  3. package/dist/connection/connection.presentation.js +1 -125
  4. package/dist/connection/connection.schema.js +1 -71
  5. package/dist/connection/index.js +1 -127
  6. package/dist/docs/index.js +5 -49
  7. package/dist/docs/integration-hub.docblock.js +5 -49
  8. package/dist/events.js +1 -211
  9. package/dist/example.js +1 -42
  10. package/dist/handlers/index.js +5 -292
  11. package/dist/handlers/integration.handlers.js +5 -292
  12. package/dist/index.js +8 -2355
  13. package/dist/integration/index.js +1 -92
  14. package/dist/integration/integration.enum.js +1 -12
  15. package/dist/integration/integration.operations.js +1 -89
  16. package/dist/integration/integration.presentation.js +1 -120
  17. package/dist/integration/integration.schema.js +1 -42
  18. package/dist/integration-hub.capability.js +1 -43
  19. package/dist/integration-hub.feature.js +1 -330
  20. package/dist/mcp-example.js +1 -154
  21. package/dist/node/connection/connection.enum.js +1 -29
  22. package/dist/node/connection/connection.operation.js +1 -124
  23. package/dist/node/connection/connection.presentation.js +1 -125
  24. package/dist/node/connection/connection.schema.js +1 -71
  25. package/dist/node/connection/index.js +1 -127
  26. package/dist/node/docs/index.js +5 -49
  27. package/dist/node/docs/integration-hub.docblock.js +5 -49
  28. package/dist/node/events.js +1 -211
  29. package/dist/node/example.js +1 -42
  30. package/dist/node/handlers/index.js +5 -292
  31. package/dist/node/handlers/integration.handlers.js +5 -292
  32. package/dist/node/index.js +8 -2355
  33. package/dist/node/integration/index.js +1 -92
  34. package/dist/node/integration/integration.enum.js +1 -12
  35. package/dist/node/integration/integration.operations.js +1 -89
  36. package/dist/node/integration/integration.presentation.js +1 -120
  37. package/dist/node/integration/integration.schema.js +1 -42
  38. package/dist/node/integration-hub.capability.js +1 -43
  39. package/dist/node/integration-hub.feature.js +1 -330
  40. package/dist/node/mcp-example.js +1 -154
  41. package/dist/node/run-mcp.js +1 -159
  42. package/dist/node/seeders/index.js +6 -60
  43. package/dist/node/sync/index.js +1 -332
  44. package/dist/node/sync/sync.enum.js +1 -26
  45. package/dist/node/sync/sync.operations.js +1 -321
  46. package/dist/node/sync/sync.presentation.js +1 -301
  47. package/dist/node/sync/sync.schema.js +1 -154
  48. package/dist/node/sync-engine/index.js +1 -186
  49. package/dist/node/tests/operations.test-spec.js +1 -85
  50. package/dist/node/ui/IntegrationDashboard.js +1 -886
  51. package/dist/node/ui/IntegrationDashboard.visualizations.js +1 -250
  52. package/dist/node/ui/IntegrationHubChat.js +1 -34
  53. package/dist/node/ui/hooks/index.js +1 -57
  54. package/dist/node/ui/hooks/useIntegrationData.js +1 -54
  55. package/dist/node/ui/index.js +4 -1173
  56. package/dist/node/ui/renderers/index.js +4 -484
  57. package/dist/node/ui/renderers/integration.markdown.js +4 -484
  58. package/dist/node/ui/tables/ConnectionsTable.js +1 -211
  59. package/dist/node/ui/tables/IntegrationTables.js +1 -361
  60. package/dist/node/ui/tables/SyncConfigsTable.js +1 -230
  61. package/dist/node/ui/tables/integration-table.shared.js +1 -84
  62. package/dist/node/visualizations/catalog.js +1 -137
  63. package/dist/node/visualizations/index.js +1 -211
  64. package/dist/node/visualizations/selectors.js +1 -204
  65. package/dist/run-mcp.js +1 -159
  66. package/dist/seeders/index.js +6 -60
  67. package/dist/sync/index.js +1 -332
  68. package/dist/sync/sync.enum.js +1 -26
  69. package/dist/sync/sync.operations.js +1 -321
  70. package/dist/sync/sync.presentation.js +1 -301
  71. package/dist/sync/sync.schema.js +1 -154
  72. package/dist/sync-engine/index.js +1 -186
  73. package/dist/tests/operations.test-spec.js +1 -85
  74. package/dist/ui/IntegrationDashboard.js +1 -886
  75. package/dist/ui/IntegrationDashboard.visualizations.js +1 -250
  76. package/dist/ui/IntegrationHubChat.js +1 -34
  77. package/dist/ui/hooks/index.js +1 -57
  78. package/dist/ui/hooks/useIntegrationData.js +1 -54
  79. package/dist/ui/index.js +4 -1173
  80. package/dist/ui/renderers/index.js +4 -484
  81. package/dist/ui/renderers/integration.markdown.js +4 -484
  82. package/dist/ui/tables/ConnectionsTable.js +1 -211
  83. package/dist/ui/tables/IntegrationTables.js +1 -361
  84. package/dist/ui/tables/SyncConfigsTable.js +1 -230
  85. package/dist/ui/tables/integration-table.shared.js +1 -84
  86. package/dist/visualizations/catalog.js +1 -137
  87. package/dist/visualizations/index.js +1 -211
  88. package/dist/visualizations/selectors.js +1 -204
  89. package/package.json +11 -11
@@ -1,2355 +1,8 @@
1
- // src/connection/connection.enum.ts
2
- import { defineEnum } from "@contractspec/lib.schema";
3
- var ConnectionStatusEnum = defineEnum("ConnectionStatus", [
4
- "PENDING",
5
- "CONNECTED",
6
- "DISCONNECTED",
7
- "ERROR",
8
- "EXPIRED"
9
- ]);
10
- var AuthTypeEnum = defineEnum("AuthType", [
11
- "api_key",
12
- "oauth2",
13
- "bearer",
14
- "header",
15
- "basic",
16
- "webhook_signing",
17
- "service_account"
18
- ]);
19
- var TransportTypeEnum = defineEnum("TransportType", [
20
- "rest",
21
- "mcp",
22
- "webhook",
23
- "sdk"
24
- ]);
25
-
26
- // src/connection/connection.schema.ts
27
- import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
28
- var ConnectionModel = defineSchemaModel({
29
- name: "ConnectionModel",
30
- fields: {
31
- id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
32
- integrationId: {
33
- type: ScalarTypeEnum.String_unsecure(),
34
- isOptional: false
35
- },
36
- name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
37
- status: { type: ConnectionStatusEnum, isOptional: false },
38
- authType: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
39
- externalAccountName: {
40
- type: ScalarTypeEnum.String_unsecure(),
41
- isOptional: true
42
- },
43
- connectedAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
44
- lastHealthCheck: { type: ScalarTypeEnum.DateTime(), isOptional: true },
45
- healthStatus: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
46
- transport: { type: TransportTypeEnum, isOptional: true },
47
- authMethod: { type: AuthTypeEnum, isOptional: true },
48
- apiVersion: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
49
- ownershipMode: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
50
- }
51
- });
52
- var CreateConnectionInputModel = defineSchemaModel({
53
- name: "CreateConnectionInput",
54
- fields: {
55
- integrationId: {
56
- type: ScalarTypeEnum.String_unsecure(),
57
- isOptional: false
58
- },
59
- name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
60
- authType: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
61
- credentials: { type: ScalarTypeEnum.JSON(), isOptional: true },
62
- transport: { type: TransportTypeEnum, isOptional: true },
63
- authMethod: { type: AuthTypeEnum, isOptional: true },
64
- apiVersion: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
65
- ownershipMode: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
66
- }
67
- });
68
-
69
- // src/connection/connection.operation.ts
70
- import { defineCommand } from "@contractspec/lib.contracts-spec/operations";
71
- var OWNERS = ["@example.integration-hub"];
72
- var CreateConnectionContract = defineCommand({
73
- meta: {
74
- key: "integration.connection.create",
75
- version: "1.0.0",
76
- stability: "stable",
77
- owners: [...OWNERS],
78
- tags: ["integration", "connection", "create"],
79
- description: "Create a connection to an external system.",
80
- goal: "Authenticate with external systems.",
81
- context: "Connection setup."
82
- },
83
- io: { input: CreateConnectionInputModel, output: ConnectionModel },
84
- policy: { auth: "user" },
85
- sideEffects: {
86
- emits: [
87
- {
88
- key: "integration.connection.created",
89
- version: "1.0.0",
90
- when: "Connection created",
91
- payload: ConnectionModel
92
- }
93
- ],
94
- audit: ["integration.connection.created"]
95
- },
96
- acceptance: {
97
- scenarios: [
98
- {
99
- key: "create-connection-happy-path",
100
- given: ["User is authenticated"],
101
- when: ["User creates connection with valid credentials"],
102
- then: ["Connection is created", "ConnectionCreated event is emitted"]
103
- }
104
- ],
105
- examples: [
106
- {
107
- key: "connect-crm",
108
- input: {
109
- name: "Salesforce Prod",
110
- integrationId: "salesforce",
111
- credentials: { clientId: "xxx" }
112
- },
113
- output: {
114
- id: "conn-123",
115
- status: "connected",
116
- connectedAt: "2025-01-01T12:00:00Z"
117
- }
118
- }
119
- ]
120
- }
121
- });
122
- // src/handlers/integration.handlers.ts
123
- import { web } from "@contractspec/lib.runtime-sandbox";
124
- var { generateId } = web;
125
- function rowToIntegration(row) {
126
- return {
127
- id: row.id,
128
- projectId: row.projectId,
129
- organizationId: row.organizationId,
130
- name: row.name,
131
- description: row.description ?? undefined,
132
- type: row.type,
133
- status: row.status,
134
- iconUrl: row.iconUrl ?? undefined,
135
- createdAt: new Date(row.createdAt),
136
- updatedAt: new Date(row.updatedAt)
137
- };
138
- }
139
- function rowToConnection(row) {
140
- return {
141
- id: row.id,
142
- integrationId: row.integrationId,
143
- name: row.name,
144
- status: row.status,
145
- credentials: row.credentials ? JSON.parse(row.credentials) : undefined,
146
- config: row.config ? JSON.parse(row.config) : undefined,
147
- lastSyncAt: row.lastSyncAt ? new Date(row.lastSyncAt) : undefined,
148
- errorMessage: row.errorMessage ?? undefined,
149
- createdAt: new Date(row.createdAt),
150
- updatedAt: new Date(row.updatedAt)
151
- };
152
- }
153
- function rowToSyncConfig(row) {
154
- return {
155
- id: row.id,
156
- connectionId: row.connectionId,
157
- name: row.name,
158
- sourceEntity: row.sourceEntity,
159
- targetEntity: row.targetEntity,
160
- frequency: row.frequency,
161
- status: row.status,
162
- lastRunAt: row.lastRunAt ? new Date(row.lastRunAt) : undefined,
163
- lastRunStatus: row.lastRunStatus ?? undefined,
164
- recordsSynced: row.recordsSynced,
165
- createdAt: new Date(row.createdAt),
166
- updatedAt: new Date(row.updatedAt)
167
- };
168
- }
169
- function rowToFieldMapping(row) {
170
- return {
171
- id: row.id,
172
- syncConfigId: row.syncConfigId,
173
- sourceField: row.sourceField,
174
- targetField: row.targetField,
175
- transformType: row.transformType ?? undefined,
176
- transformConfig: row.transformConfig ? JSON.parse(row.transformConfig) : undefined,
177
- createdAt: new Date(row.createdAt)
178
- };
179
- }
180
- function createIntegrationHandlers(db) {
181
- async function listIntegrations(input) {
182
- const { projectId, type, status, search, limit = 20, offset = 0 } = input;
183
- let whereClause = "WHERE projectId = ?";
184
- const params = [projectId];
185
- if (type && type !== "all") {
186
- whereClause += " AND type = ?";
187
- params.push(type);
188
- }
189
- if (status && status !== "all") {
190
- whereClause += " AND status = ?";
191
- params.push(status);
192
- }
193
- if (search) {
194
- whereClause += " AND name LIKE ?";
195
- params.push(`%${search}%`);
196
- }
197
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM integration ${whereClause}`, params)).rows;
198
- const total = countResult[0]?.count ?? 0;
199
- const rows = (await db.query(`SELECT * FROM integration ${whereClause} ORDER BY name LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
200
- return {
201
- integrations: rows.map(rowToIntegration),
202
- total
203
- };
204
- }
205
- async function createIntegration(input, context) {
206
- const id = generateId("integ");
207
- const now = new Date().toISOString();
208
- await db.execute(`INSERT INTO integration (id, projectId, organizationId, name, description, type, status, iconUrl, createdAt, updatedAt)
209
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
210
- id,
211
- context.projectId,
212
- context.organizationId,
213
- input.name,
214
- input.description ?? null,
215
- input.type,
216
- "INACTIVE",
217
- input.iconUrl ?? null,
218
- now,
219
- now
220
- ]);
221
- const rows = (await db.query(`SELECT * FROM integration WHERE id = ?`, [id])).rows;
222
- return rowToIntegration(rows[0]);
223
- }
224
- async function listConnections(input) {
225
- const { integrationId, status, limit = 20, offset = 0 } = input;
226
- let whereClause = "WHERE 1=1";
227
- const params = [];
228
- if (integrationId) {
229
- whereClause += " AND integrationId = ?";
230
- params.push(integrationId);
231
- }
232
- if (status && status !== "all") {
233
- whereClause += " AND status = ?";
234
- params.push(status);
235
- }
236
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM integration_connection ${whereClause}`, params)).rows;
237
- const total = countResult[0]?.count ?? 0;
238
- const rows = (await db.query(`SELECT * FROM integration_connection ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
239
- return {
240
- connections: rows.map(rowToConnection),
241
- total
242
- };
243
- }
244
- async function connectService(input) {
245
- const id = generateId("conn");
246
- const now = new Date().toISOString();
247
- await db.execute(`INSERT INTO integration_connection (id, integrationId, name, status, credentials, config, createdAt, updatedAt)
248
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
249
- id,
250
- input.integrationId,
251
- input.name,
252
- "PENDING",
253
- input.credentials ? JSON.stringify(input.credentials) : null,
254
- input.config ? JSON.stringify(input.config) : null,
255
- now,
256
- now
257
- ]);
258
- await db.execute(`UPDATE integration_connection SET status = 'CONNECTED', updatedAt = ? WHERE id = ?`, [now, id]);
259
- await db.execute(`UPDATE integration SET status = 'ACTIVE', updatedAt = ? WHERE id = ?`, [now, input.integrationId]);
260
- const rows = (await db.query(`SELECT * FROM integration_connection WHERE id = ?`, [id])).rows;
261
- return rowToConnection(rows[0]);
262
- }
263
- async function disconnectService(connectionId) {
264
- const now = new Date().toISOString();
265
- await db.execute(`UPDATE integration_connection SET status = 'DISCONNECTED', updatedAt = ? WHERE id = ?`, [now, connectionId]);
266
- const rows = (await db.query(`SELECT * FROM integration_connection WHERE id = ?`, [
267
- connectionId
268
- ])).rows;
269
- return rowToConnection(rows[0]);
270
- }
271
- async function listSyncConfigs(input) {
272
- const { connectionId, status, limit = 20, offset = 0 } = input;
273
- let whereClause = "WHERE 1=1";
274
- const params = [];
275
- if (connectionId) {
276
- whereClause += " AND connectionId = ?";
277
- params.push(connectionId);
278
- }
279
- if (status && status !== "all") {
280
- whereClause += " AND status = ?";
281
- params.push(status);
282
- }
283
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM integration_sync_config ${whereClause}`, params)).rows;
284
- const total = countResult[0]?.count ?? 0;
285
- const rows = (await db.query(`SELECT * FROM integration_sync_config ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
286
- return {
287
- configs: rows.map(rowToSyncConfig),
288
- total
289
- };
290
- }
291
- async function configureSync(input) {
292
- const id = generateId("sync");
293
- const now = new Date().toISOString();
294
- await db.execute(`INSERT INTO integration_sync_config (id, connectionId, name, sourceEntity, targetEntity, frequency, status, recordsSynced, createdAt, updatedAt)
295
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
296
- id,
297
- input.connectionId,
298
- input.name,
299
- input.sourceEntity,
300
- input.targetEntity,
301
- input.frequency ?? "DAILY",
302
- "ACTIVE",
303
- 0,
304
- now,
305
- now
306
- ]);
307
- const rows = (await db.query(`SELECT * FROM integration_sync_config WHERE id = ?`, [id])).rows;
308
- return rowToSyncConfig(rows[0]);
309
- }
310
- async function mapFields(input) {
311
- const now = new Date().toISOString();
312
- const mappings = [];
313
- await db.execute(`DELETE FROM integration_field_mapping WHERE syncConfigId = ?`, [input.syncConfigId]);
314
- for (const mapping of input.mappings) {
315
- const id = generateId("fmap");
316
- await db.execute(`INSERT INTO integration_field_mapping (id, syncConfigId, sourceField, targetField, transformType, transformConfig, createdAt)
317
- VALUES (?, ?, ?, ?, ?, ?, ?)`, [
318
- id,
319
- input.syncConfigId,
320
- mapping.sourceField,
321
- mapping.targetField,
322
- mapping.transformType ?? null,
323
- mapping.transformConfig ? JSON.stringify(mapping.transformConfig) : null,
324
- now
325
- ]);
326
- const rows = (await db.query(`SELECT * FROM integration_field_mapping WHERE id = ?`, [
327
- id
328
- ])).rows;
329
- mappings.push(rowToFieldMapping(rows[0]));
330
- }
331
- return mappings;
332
- }
333
- async function getFieldMappings(syncConfigId) {
334
- const rows = (await db.query(`SELECT * FROM integration_field_mapping WHERE syncConfigId = ?`, [syncConfigId])).rows;
335
- return rows.map(rowToFieldMapping);
336
- }
337
- async function runSync(syncConfigId) {
338
- const now = new Date().toISOString();
339
- const recordsSynced = Math.floor(Math.random() * 1000) + 50;
340
- await db.execute(`UPDATE integration_sync_config SET lastRunAt = ?, lastRunStatus = 'SUCCESS', recordsSynced = recordsSynced + ?, updatedAt = ? WHERE id = ?`, [now, recordsSynced, now, syncConfigId]);
341
- const config = (await db.query(`SELECT * FROM integration_sync_config WHERE id = ?`, [
342
- syncConfigId
343
- ])).rows;
344
- if (config[0]) {
345
- await db.execute(`UPDATE integration_connection SET lastSyncAt = ?, updatedAt = ? WHERE id = ?`, [now, now, config[0].connectionId]);
346
- }
347
- const rows = (await db.query(`SELECT * FROM integration_sync_config WHERE id = ?`, [
348
- syncConfigId
349
- ])).rows;
350
- return rowToSyncConfig(rows[0]);
351
- }
352
- async function validateByokKey(input) {
353
- const rows = (await db.query(`SELECT * FROM integration_connection WHERE id = ?`, [
354
- input.connectionId
355
- ])).rows;
356
- if (!rows[0]) {
357
- return {
358
- valid: false,
359
- provider: "unknown",
360
- keyPrefix: "",
361
- error: `Connection ${input.connectionId} not found`
362
- };
363
- }
364
- const keyPrefix = input.providerKey.slice(0, 8);
365
- const looksValid = input.providerKey.length >= 16;
366
- return {
367
- valid: looksValid,
368
- provider: rows[0].name,
369
- keyPrefix: `${keyPrefix}...`,
370
- expiresAt: looksValid ? new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString() : undefined,
371
- error: looksValid ? undefined : "Key must be at least 16 characters"
372
- };
373
- }
374
- async function refreshOAuth2Token(input) {
375
- const now = new Date().toISOString();
376
- await db.execute(`UPDATE integration_connection SET updatedAt = ? WHERE id = ?`, [now, input.connectionId]);
377
- return {
378
- refreshed: true,
379
- expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
380
- tokenType: "Bearer",
381
- scopes: ["read", "write", "sync"]
382
- };
383
- }
384
- async function getTransportOptions(input) {
385
- return {
386
- integrationId: input.integrationId,
387
- transports: [
388
- { transport: "rest", supported: true, defaultVersion: "v2" },
389
- { transport: "mcp", supported: true, defaultVersion: "v1" },
390
- { transport: "webhook", supported: true },
391
- { transport: "sdk", supported: false }
392
- ]
393
- };
394
- }
395
- return {
396
- listIntegrations,
397
- createIntegration,
398
- listConnections,
399
- connectService,
400
- disconnectService,
401
- listSyncConfigs,
402
- configureSync,
403
- mapFields,
404
- getFieldMappings,
405
- runSync,
406
- validateByokKey,
407
- refreshOAuth2Token,
408
- getTransportOptions
409
- };
410
- }
411
-
412
- // src/integration/integration.enum.ts
413
- import { defineEnum as defineEnum2 } from "@contractspec/lib.schema";
414
- var IntegrationStatusEnum = defineEnum2("IntegrationStatus", [
415
- "DRAFT",
416
- "ACTIVE",
417
- "PAUSED",
418
- "ERROR",
419
- "ARCHIVED"
420
- ]);
421
-
422
- // src/integration/integration.schema.ts
423
- import { defineSchemaModel as defineSchemaModel2, ScalarTypeEnum as ScalarTypeEnum2 } from "@contractspec/lib.schema";
424
- var IntegrationModel = defineSchemaModel2({
425
- name: "IntegrationModel",
426
- fields: {
427
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
428
- name: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
429
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
430
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
431
- provider: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
432
- status: { type: IntegrationStatusEnum, isOptional: false },
433
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
434
- }
435
- });
436
- var CreateIntegrationInputModel = defineSchemaModel2({
437
- name: "CreateIntegrationInput",
438
- fields: {
439
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
440
- slug: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
441
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
442
- provider: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
443
- config: { type: ScalarTypeEnum2.JSON(), isOptional: true },
444
- featureFlagKey: {
445
- type: ScalarTypeEnum2.String_unsecure(),
446
- isOptional: true
447
- }
448
- }
449
- });
450
-
451
- // src/integration/integration.operations.ts
452
- import { defineCommand as defineCommand2 } from "@contractspec/lib.contracts-spec/operations";
453
- var CreateIntegrationContract = defineCommand2({
454
- meta: {
455
- key: "integration.create",
456
- version: "1.0.0",
457
- stability: "stable",
458
- owners: ["@example.integration-hub"],
459
- tags: ["integration", "create"],
460
- description: "Create a new integration.",
461
- goal: "Allow users to set up integrations with external systems.",
462
- context: "Integration setup."
463
- },
464
- io: { input: CreateIntegrationInputModel, output: IntegrationModel },
465
- policy: { auth: "user" },
466
- sideEffects: {
467
- emits: [
468
- {
469
- key: "integration.created",
470
- version: "1.0.0",
471
- when: "Integration created",
472
- payload: IntegrationModel
473
- }
474
- ],
475
- audit: ["integration.created"]
476
- },
477
- acceptance: {
478
- scenarios: [
479
- {
480
- key: "create-integration-happy-path",
481
- given: ["User is admin"],
482
- when: ["User defines new integration type"],
483
- then: [
484
- "Integration definition is created",
485
- "IntegrationCreated event is emitted"
486
- ]
487
- }
488
- ],
489
- examples: [
490
- {
491
- key: "create-slack",
492
- input: { name: "Slack", category: "communication", authType: "oauth2" },
493
- output: { id: "slack", status: "active" }
494
- }
495
- ]
496
- }
497
- });
498
- // src/mcp-example.ts
499
- import {
500
- createMcpToolsets
501
- } from "@contractspec/lib.ai-agent/tools/mcp-client";
502
- import { randomUUID } from "crypto";
503
- var DEFAULT_STDIO_ARGS = [
504
- "-y",
505
- "@modelcontextprotocol/server-filesystem",
506
- "."
507
- ];
508
- async function runIntegrationHubMcpExampleFromEnv() {
509
- const mode = resolveMode();
510
- const transport = resolveTransport();
511
- const config = buildMcpConfigFromEnv();
512
- const toolset = await createMcpToolsets([config], {
513
- onNameCollision: "error"
514
- });
515
- try {
516
- const toolNames = Object.keys(toolset.tools).sort();
517
- const output = {
518
- mode,
519
- server: {
520
- name: config.name,
521
- transport
522
- },
523
- authMethod: process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_AUTH_METHOD,
524
- apiVersion: process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_API_VERSION,
525
- tools: toolNames
526
- };
527
- if (mode === "call") {
528
- const toolName = requireEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_NAME");
529
- const toolArgs = parseRecordEnvOrDefault("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_ARGS_JSON", {});
530
- const tool = toolset.tools[toolName];
531
- if (!tool?.execute) {
532
- throw new Error(`Tool "${toolName}" was not found. Available tools: ${toolNames.join(", ")}`);
533
- }
534
- const toolOutput = await tool.execute(toolArgs, {
535
- toolCallId: `integration-hub-${randomUUID()}`,
536
- messages: []
537
- });
538
- output.toolCall = {
539
- name: toolName,
540
- args: toolArgs,
541
- output: toolOutput
542
- };
543
- }
544
- return output;
545
- } finally {
546
- await toolset.cleanup().catch(() => {
547
- return;
548
- });
549
- }
550
- }
551
- function buildMcpConfigFromEnv() {
552
- const name = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_NAME ?? "filesystem";
553
- const transport = resolveTransport();
554
- const toolPrefix = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_PREFIX;
555
- if (transport === "stdio") {
556
- return {
557
- name,
558
- transport,
559
- command: process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_COMMAND ?? "npx",
560
- args: parseStringArrayEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_ARGS_JSON", DEFAULT_STDIO_ARGS),
561
- toolPrefix
562
- };
563
- }
564
- const accessToken = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN;
565
- const accessTokenEnvVar = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN_ENV;
566
- const mcpTransport = transport === "webhook" || transport === "http" ? "http" : "sse";
567
- return {
568
- name,
569
- transport: mcpTransport,
570
- url: requireEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_URL"),
571
- headers: parseStringRecordEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_HEADERS_JSON"),
572
- accessToken,
573
- accessTokenEnvVar,
574
- toolPrefix
575
- };
576
- }
577
- function resolveMode() {
578
- const rawMode = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE?.toLowerCase() ?? "list";
579
- if (rawMode === "list" || rawMode === "call") {
580
- return rawMode;
581
- }
582
- throw new Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE: ${rawMode}. Use "list" or "call".`);
583
- }
584
- function resolveTransport() {
585
- const rawTransport = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT?.toLowerCase() ?? "stdio";
586
- if (rawTransport === "stdio" || rawTransport === "http" || rawTransport === "sse" || rawTransport === "webhook") {
587
- return rawTransport;
588
- }
589
- throw new Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT: ${rawTransport}. Use "stdio", "http", "sse", or "webhook".`);
590
- }
591
- function parseStringArrayEnv(key, fallback) {
592
- const raw = process.env[key];
593
- if (!raw) {
594
- return fallback;
595
- }
596
- const parsed = parseJsonEnv(key);
597
- if (!Array.isArray(parsed) || parsed.some((value) => typeof value !== "string")) {
598
- throw new Error(`${key} must be a JSON string array.`);
599
- }
600
- return parsed;
601
- }
602
- function parseRecordEnv(key) {
603
- const raw = process.env[key];
604
- if (!raw) {
605
- return;
606
- }
607
- const parsed = parseJsonEnv(key);
608
- if (!isRecord(parsed)) {
609
- throw new Error(`${key} must be a JSON object.`);
610
- }
611
- return parsed;
612
- }
613
- function parseRecordEnvOrDefault(key, fallback) {
614
- return parseRecordEnv(key) ?? fallback;
615
- }
616
- function parseStringRecordEnv(key) {
617
- const parsed = parseRecordEnv(key);
618
- if (!parsed) {
619
- return;
620
- }
621
- const entries = Object.entries(parsed);
622
- const invalidEntry = entries.find(([, value]) => typeof value !== "string");
623
- if (invalidEntry) {
624
- throw new Error(`${key} must contain only string values.`);
625
- }
626
- return Object.fromEntries(entries);
627
- }
628
- function parseJsonEnv(key) {
629
- const raw = process.env[key];
630
- if (!raw) {
631
- return;
632
- }
633
- try {
634
- return JSON.parse(raw);
635
- } catch {
636
- throw new Error(`${key} contains invalid JSON.`);
637
- }
638
- }
639
- function requireEnv(key) {
640
- const value = process.env[key];
641
- if (!value) {
642
- throw new Error(`Missing required env var: ${key}`);
643
- }
644
- return value;
645
- }
646
- function isRecord(value) {
647
- return typeof value === "object" && value !== null && !Array.isArray(value);
648
- }
649
-
650
- // src/sync/sync.enum.ts
651
- import { defineEnum as defineEnum3 } from "@contractspec/lib.schema";
652
- var SyncDirectionEnum = defineEnum3("SyncDirection", [
653
- "INBOUND",
654
- "OUTBOUND",
655
- "BIDIRECTIONAL"
656
- ]);
657
- var SyncStatusEnum = defineEnum3("SyncStatus", [
658
- "PENDING",
659
- "RUNNING",
660
- "COMPLETED",
661
- "FAILED",
662
- "CANCELLED"
663
- ]);
664
- var MappingTypeEnum = defineEnum3("MappingType", [
665
- "DIRECT",
666
- "TRANSFORM",
667
- "LOOKUP",
668
- "CONSTANT",
669
- "COMPUTED"
670
- ]);
671
-
672
- // src/sync/sync.schema.ts
673
- import { defineSchemaModel as defineSchemaModel3, ScalarTypeEnum as ScalarTypeEnum3 } from "@contractspec/lib.schema";
674
- var FieldMappingModel = defineSchemaModel3({
675
- name: "FieldMappingModel",
676
- fields: {
677
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
678
- sourceField: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
679
- targetField: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
680
- mappingType: { type: MappingTypeEnum, isOptional: false },
681
- transformExpression: {
682
- type: ScalarTypeEnum3.String_unsecure(),
683
- isOptional: true
684
- },
685
- isRequired: { type: ScalarTypeEnum3.Boolean(), isOptional: false }
686
- }
687
- });
688
- var SyncConfigModel = defineSchemaModel3({
689
- name: "SyncConfigModel",
690
- fields: {
691
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
692
- integrationId: {
693
- type: ScalarTypeEnum3.String_unsecure(),
694
- isOptional: false
695
- },
696
- connectionId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
697
- name: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
698
- direction: { type: SyncDirectionEnum, isOptional: false },
699
- sourceObject: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
700
- targetObject: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
701
- scheduleEnabled: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
702
- scheduleCron: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
703
- isActive: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
704
- lastSyncAt: { type: ScalarTypeEnum3.DateTime(), isOptional: true },
705
- fieldMappings: { type: FieldMappingModel, isArray: true, isOptional: true }
706
- }
707
- });
708
- var SyncRunModel = defineSchemaModel3({
709
- name: "SyncRunModel",
710
- fields: {
711
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
712
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
713
- status: { type: SyncStatusEnum, isOptional: false },
714
- direction: { type: SyncDirectionEnum, isOptional: false },
715
- trigger: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
716
- recordsProcessed: {
717
- type: ScalarTypeEnum3.Int_unsecure(),
718
- isOptional: false
719
- },
720
- recordsCreated: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
721
- recordsUpdated: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
722
- recordsFailed: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
723
- errorMessage: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
724
- startedAt: { type: ScalarTypeEnum3.DateTime(), isOptional: true },
725
- completedAt: { type: ScalarTypeEnum3.DateTime(), isOptional: true },
726
- createdAt: { type: ScalarTypeEnum3.DateTime(), isOptional: false }
727
- }
728
- });
729
- var CreateSyncConfigInputModel = defineSchemaModel3({
730
- name: "CreateSyncConfigInput",
731
- fields: {
732
- integrationId: {
733
- type: ScalarTypeEnum3.String_unsecure(),
734
- isOptional: false
735
- },
736
- connectionId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
737
- name: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
738
- direction: { type: SyncDirectionEnum, isOptional: false },
739
- sourceObject: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
740
- targetObject: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
741
- scheduleEnabled: { type: ScalarTypeEnum3.Boolean(), isOptional: true },
742
- scheduleCron: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true }
743
- }
744
- });
745
- var AddFieldMappingInputModel = defineSchemaModel3({
746
- name: "AddFieldMappingInput",
747
- fields: {
748
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
749
- sourceField: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
750
- targetField: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
751
- mappingType: { type: MappingTypeEnum, isOptional: false },
752
- transformExpression: {
753
- type: ScalarTypeEnum3.String_unsecure(),
754
- isOptional: true
755
- },
756
- lookupConfig: { type: ScalarTypeEnum3.JSON(), isOptional: true },
757
- constantValue: { type: ScalarTypeEnum3.JSON(), isOptional: true },
758
- isRequired: { type: ScalarTypeEnum3.Boolean(), isOptional: true },
759
- defaultValue: { type: ScalarTypeEnum3.JSON(), isOptional: true }
760
- }
761
- });
762
- var TriggerSyncInputModel = defineSchemaModel3({
763
- name: "TriggerSyncInput",
764
- fields: {
765
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
766
- direction: { type: SyncDirectionEnum, isOptional: true },
767
- fullSync: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
768
- }
769
- });
770
- var ListSyncRunsInputModel = defineSchemaModel3({
771
- name: "ListSyncRunsInput",
772
- fields: {
773
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
774
- status: { type: SyncStatusEnum, isOptional: true },
775
- limit: {
776
- type: ScalarTypeEnum3.Int_unsecure(),
777
- isOptional: true,
778
- defaultValue: 20
779
- },
780
- offset: {
781
- type: ScalarTypeEnum3.Int_unsecure(),
782
- isOptional: true,
783
- defaultValue: 0
784
- }
785
- }
786
- });
787
- var ListSyncRunsOutputModel = defineSchemaModel3({
788
- name: "ListSyncRunsOutput",
789
- fields: {
790
- runs: { type: SyncRunModel, isArray: true, isOptional: false },
791
- total: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false }
792
- }
793
- });
794
-
795
- // src/sync/sync.operations.ts
796
- import {
797
- defineCommand as defineCommand3,
798
- defineQuery
799
- } from "@contractspec/lib.contracts-spec/operations";
800
- var OWNERS2 = ["@example.integration-hub"];
801
- var CreateSyncConfigContract = defineCommand3({
802
- meta: {
803
- key: "integration.syncConfig.create",
804
- version: "1.0.0",
805
- stability: "stable",
806
- owners: [...OWNERS2],
807
- tags: ["integration", "sync", "config", "create"],
808
- description: "Create a sync configuration.",
809
- goal: "Define how data should be synchronized.",
810
- context: "Sync setup."
811
- },
812
- io: { input: CreateSyncConfigInputModel, output: SyncConfigModel },
813
- policy: { auth: "user" },
814
- sideEffects: {
815
- emits: [
816
- {
817
- key: "integration.syncConfig.created",
818
- version: "1.0.0",
819
- when: "Sync config created",
820
- payload: SyncConfigModel
821
- }
822
- ],
823
- audit: ["integration.syncConfig.created"]
824
- },
825
- acceptance: {
826
- scenarios: [
827
- {
828
- key: "create-sync-happy-path",
829
- given: ["User is authenticated"],
830
- when: ["User creates sync config"],
831
- then: ["Sync config is created", "SyncConfigCreated event is emitted"]
832
- }
833
- ],
834
- examples: [
835
- {
836
- key: "create-contact-sync",
837
- input: {
838
- name: "Contacts Sync",
839
- sourceConnectionId: "conn-1",
840
- targetConnectionId: "conn-2"
841
- },
842
- output: { id: "sync-123", status: "active" }
843
- }
844
- ]
845
- }
846
- });
847
- var AddFieldMappingContract = defineCommand3({
848
- meta: {
849
- key: "integration.fieldMapping.add",
850
- version: "1.0.0",
851
- stability: "stable",
852
- owners: [...OWNERS2],
853
- tags: ["integration", "mapping", "field"],
854
- description: "Add a field mapping to a sync config.",
855
- goal: "Map fields between systems.",
856
- context: "Mapping configuration."
857
- },
858
- io: { input: AddFieldMappingInputModel, output: FieldMappingModel },
859
- policy: { auth: "user" },
860
- sideEffects: {
861
- emits: [
862
- {
863
- key: "integration.fieldMapping.added",
864
- version: "1.0.0",
865
- when: "Mapping added",
866
- payload: FieldMappingModel
867
- }
868
- ]
869
- },
870
- acceptance: {
871
- scenarios: [
872
- {
873
- key: "add-mapping-happy-path",
874
- given: ["Sync config exists"],
875
- when: ["User adds field mapping"],
876
- then: ["Mapping is added", "FieldMappingAdded event is emitted"]
877
- }
878
- ],
879
- examples: [
880
- {
881
- key: "map-email",
882
- input: {
883
- syncConfigId: "sync-123",
884
- sourceField: "email",
885
- targetField: "user_email"
886
- },
887
- output: { id: "map-456", type: "string" }
888
- }
889
- ]
890
- }
891
- });
892
- var TriggerSyncContract = defineCommand3({
893
- meta: {
894
- key: "integration.sync.trigger",
895
- version: "1.0.0",
896
- stability: "stable",
897
- owners: [...OWNERS2],
898
- tags: ["integration", "sync", "trigger"],
899
- description: "Trigger a manual sync.",
900
- goal: "Start data synchronization.",
901
- context: "Manual sync or webhook trigger."
902
- },
903
- io: { input: TriggerSyncInputModel, output: SyncRunModel },
904
- policy: { auth: "user" },
905
- sideEffects: {
906
- emits: [
907
- {
908
- key: "integration.sync.started",
909
- version: "1.0.0",
910
- when: "Sync starts",
911
- payload: SyncRunModel
912
- }
913
- ],
914
- audit: ["integration.sync.triggered"]
915
- },
916
- acceptance: {
917
- scenarios: [
918
- {
919
- key: "trigger-sync-happy-path",
920
- given: ["Sync config exists"],
921
- when: ["User triggers sync"],
922
- then: ["Sync run starts", "SyncStarted event is emitted"]
923
- }
924
- ],
925
- examples: [
926
- {
927
- key: "manual-trigger",
928
- input: { syncConfigId: "sync-123" },
929
- output: { id: "run-789", status: "pending" }
930
- }
931
- ]
932
- }
933
- });
934
- var ListSyncRunsContract = defineQuery({
935
- meta: {
936
- key: "integration.syncRun.list",
937
- version: "1.0.0",
938
- stability: "stable",
939
- owners: [...OWNERS2],
940
- tags: ["integration", "sync", "run", "list"],
941
- description: "List sync run history.",
942
- goal: "View sync history and status.",
943
- context: "Sync monitoring."
944
- },
945
- io: { input: ListSyncRunsInputModel, output: ListSyncRunsOutputModel },
946
- policy: { auth: "user" },
947
- acceptance: {
948
- scenarios: [
949
- {
950
- key: "list-runs-happy-path",
951
- given: ["User has access to syncs"],
952
- when: ["User lists sync runs"],
953
- then: ["List of runs is returned"]
954
- }
955
- ],
956
- examples: [
957
- {
958
- key: "list-recent",
959
- input: { limit: 10 },
960
- output: { items: [], total: 50 }
961
- }
962
- ]
963
- }
964
- });
965
- // src/sync-engine/index.ts
966
- class BasicFieldTransformer {
967
- transform(value, expression) {
968
- try {
969
- if (expression.startsWith("uppercase")) {
970
- return typeof value === "string" ? value.toUpperCase() : value;
971
- }
972
- if (expression.startsWith("lowercase")) {
973
- return typeof value === "string" ? value.toLowerCase() : value;
974
- }
975
- if (expression.startsWith("trim")) {
976
- return typeof value === "string" ? value.trim() : value;
977
- }
978
- if (expression.startsWith("default:")) {
979
- const defaultVal = expression.replace("default:", "");
980
- return value ?? JSON.parse(defaultVal);
981
- }
982
- if (expression.startsWith("concat:")) {
983
- const separator = expression.replace("concat:", "") || " ";
984
- if (Array.isArray(value)) {
985
- return value.join(separator);
986
- }
987
- return value;
988
- }
989
- if (expression.startsWith("split:")) {
990
- const separator = expression.replace("split:", "") || ",";
991
- if (typeof value === "string") {
992
- return value.split(separator);
993
- }
994
- return value;
995
- }
996
- if (expression.startsWith("number")) {
997
- return Number(value);
998
- }
999
- if (expression.startsWith("boolean")) {
1000
- return Boolean(value);
1001
- }
1002
- if (expression.startsWith("string")) {
1003
- return String(value);
1004
- }
1005
- return value;
1006
- } catch {
1007
- return value;
1008
- }
1009
- }
1010
- }
1011
-
1012
- class BasicSyncEngine {
1013
- transformer;
1014
- constructor(transformer) {
1015
- this.transformer = transformer ?? new BasicFieldTransformer;
1016
- }
1017
- async sync(_context) {
1018
- const result = {
1019
- success: true,
1020
- recordsProcessed: 0,
1021
- recordsCreated: 0,
1022
- recordsUpdated: 0,
1023
- recordsDeleted: 0,
1024
- recordsFailed: 0,
1025
- recordsSkipped: 0,
1026
- errors: []
1027
- };
1028
- return result;
1029
- }
1030
- transformRecord(sourceRecord, mappings, _context) {
1031
- const targetData = {};
1032
- for (const mapping of mappings) {
1033
- let value;
1034
- let sourceValue;
1035
- switch (mapping.mappingType) {
1036
- case "DIRECT":
1037
- value = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1038
- break;
1039
- case "TRANSFORM":
1040
- sourceValue = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1041
- value = mapping.transformExpression ? this.transformer.transform(sourceValue, mapping.transformExpression) : sourceValue;
1042
- break;
1043
- case "CONSTANT":
1044
- value = mapping.constantValue;
1045
- break;
1046
- case "LOOKUP":
1047
- value = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1048
- break;
1049
- case "COMPUTED":
1050
- value = mapping.transformExpression ? this.evaluateComputed(sourceRecord.data, mapping.transformExpression) : null;
1051
- break;
1052
- default:
1053
- value = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1054
- }
1055
- if (value === undefined || value === null) {
1056
- value = mapping.defaultValue;
1057
- }
1058
- this.setNestedValue(targetData, mapping.targetField, value);
1059
- }
1060
- return {
1061
- id: sourceRecord.id,
1062
- data: targetData
1063
- };
1064
- }
1065
- validateRecord(record, mappings) {
1066
- const errors = [];
1067
- for (const mapping of mappings) {
1068
- if (mapping.isRequired) {
1069
- const value = this.getNestedValue(record.data, mapping.targetField);
1070
- if (value === undefined || value === null) {
1071
- errors.push({
1072
- recordId: record.id,
1073
- field: mapping.targetField,
1074
- message: `Required field ${mapping.targetField} is missing`,
1075
- code: "REQUIRED_FIELD_MISSING"
1076
- });
1077
- }
1078
- }
1079
- }
1080
- return {
1081
- valid: errors.length === 0,
1082
- errors
1083
- };
1084
- }
1085
- getNestedValue(obj, path) {
1086
- const parts = path.split(".");
1087
- let current = obj;
1088
- for (const part of parts) {
1089
- if (current === null || current === undefined) {
1090
- return;
1091
- }
1092
- current = current[part];
1093
- }
1094
- return current;
1095
- }
1096
- setNestedValue(obj, path, value) {
1097
- const parts = path.split(".");
1098
- let current = obj;
1099
- for (let i = 0;i < parts.length - 1; i++) {
1100
- const part = parts[i];
1101
- if (part === undefined)
1102
- continue;
1103
- if (!(part in current)) {
1104
- current[part] = {};
1105
- }
1106
- current = current[part];
1107
- }
1108
- const lastPart = parts[parts.length - 1];
1109
- if (lastPart !== undefined) {
1110
- current[lastPart] = value;
1111
- }
1112
- }
1113
- evaluateComputed(data, expression) {
1114
- try {
1115
- const result = expression.replace(/\$\{([^}]+)\}/g, (_, path) => {
1116
- const value = this.getNestedValue(data, path);
1117
- return String(value ?? "");
1118
- });
1119
- return result;
1120
- } catch {
1121
- return null;
1122
- }
1123
- }
1124
- }
1125
- function createSyncEngine(transformer) {
1126
- return new BasicSyncEngine(transformer);
1127
- }
1128
- function computeChecksum(data) {
1129
- const str = JSON.stringify(data, Object.keys(data).sort());
1130
- let hash = 0;
1131
- for (let i = 0;i < str.length; i++) {
1132
- const char = str.charCodeAt(i);
1133
- hash = (hash << 5) - hash + char;
1134
- hash = hash & hash;
1135
- }
1136
- return hash.toString(16);
1137
- }
1138
- function hasChanges(sourceChecksum, targetChecksum) {
1139
- if (!sourceChecksum || !targetChecksum) {
1140
- return true;
1141
- }
1142
- return sourceChecksum !== targetChecksum;
1143
- }
1144
-
1145
- // src/ui/hooks/useIntegrationData.ts
1146
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1147
- import { useCallback, useEffect, useState } from "react";
1148
- "use client";
1149
- function useIntegrationData(projectId = "local-project") {
1150
- const { handlers } = useTemplateRuntime();
1151
- const integration = handlers.integration;
1152
- const [integrations, setIntegrations] = useState([]);
1153
- const [connections, setConnections] = useState([]);
1154
- const [syncConfigs, setSyncConfigs] = useState([]);
1155
- const [loading, setLoading] = useState(true);
1156
- const [error, setError] = useState(null);
1157
- const fetchData = useCallback(async () => {
1158
- try {
1159
- setLoading(true);
1160
- setError(null);
1161
- const [integResult, connResult, syncResult] = await Promise.all([
1162
- integration.listIntegrations({ projectId, limit: 100 }),
1163
- integration.listConnections({ limit: 100 }),
1164
- integration.listSyncConfigs({ limit: 100 })
1165
- ]);
1166
- setIntegrations(integResult.integrations);
1167
- setConnections(connResult.connections);
1168
- setSyncConfigs(syncResult.configs);
1169
- } catch (err) {
1170
- setError(err instanceof Error ? err : new Error("Failed to load integrations"));
1171
- } finally {
1172
- setLoading(false);
1173
- }
1174
- }, [integration, projectId]);
1175
- useEffect(() => {
1176
- fetchData();
1177
- }, [fetchData]);
1178
- const stats = {
1179
- totalIntegrations: integrations.length,
1180
- activeIntegrations: integrations.filter((i) => i.status === "ACTIVE").length,
1181
- totalConnections: connections.length,
1182
- connectedCount: connections.filter((c) => c.status === "CONNECTED").length,
1183
- totalSyncs: syncConfigs.length,
1184
- activeSyncs: syncConfigs.filter((s) => s.status === "ACTIVE").length
1185
- };
1186
- return {
1187
- integrations,
1188
- connections,
1189
- syncConfigs,
1190
- loading,
1191
- error,
1192
- stats,
1193
- refetch: fetchData
1194
- };
1195
- }
1196
-
1197
- // src/ui/hooks/index.ts
1198
- "use client";
1199
-
1200
- // src/visualizations/catalog.ts
1201
- import {
1202
- defineVisualization,
1203
- VisualizationRegistry
1204
- } from "@contractspec/lib.contracts-spec/visualizations";
1205
- var INTEGRATION_LIST_REF = {
1206
- key: "integration.list",
1207
- version: "1.0.0"
1208
- };
1209
- var CONNECTION_LIST_REF = {
1210
- key: "integration.connection.list",
1211
- version: "1.0.0"
1212
- };
1213
- var SYNC_CONFIG_REF = {
1214
- key: "integration.syncConfig.list",
1215
- version: "1.0.0"
1216
- };
1217
- var META = {
1218
- version: "1.0.0",
1219
- domain: "integration",
1220
- stability: "experimental",
1221
- owners: ["@example.integration-hub"],
1222
- tags: ["integration", "visualization", "sync"]
1223
- };
1224
- var IntegrationTypeVisualization = defineVisualization({
1225
- meta: {
1226
- ...META,
1227
- key: "integration-hub.visualization.integration-types",
1228
- title: "Integration Types",
1229
- description: "Distribution of configured integration categories.",
1230
- goal: "Show where integration coverage is concentrated.",
1231
- context: "Integration overview."
1232
- },
1233
- source: { primary: INTEGRATION_LIST_REF, resultPath: "data" },
1234
- visualization: {
1235
- kind: "pie",
1236
- nameDimension: "type",
1237
- valueMeasure: "count",
1238
- dimensions: [
1239
- { key: "type", label: "Type", dataPath: "type", type: "category" }
1240
- ],
1241
- measures: [
1242
- { key: "count", label: "Count", dataPath: "count", format: "number" }
1243
- ],
1244
- table: { caption: "Integration counts by type." }
1245
- }
1246
- });
1247
- var ConnectionStatusVisualization = defineVisualization({
1248
- meta: {
1249
- ...META,
1250
- key: "integration-hub.visualization.connection-status",
1251
- title: "Connection Status",
1252
- description: "Status distribution across configured connections.",
1253
- goal: "Highlight connection health and instability.",
1254
- context: "Connection monitoring."
1255
- },
1256
- source: { primary: CONNECTION_LIST_REF, resultPath: "data" },
1257
- visualization: {
1258
- kind: "cartesian",
1259
- variant: "bar",
1260
- xDimension: "status",
1261
- yMeasures: ["count"],
1262
- dimensions: [
1263
- { key: "status", label: "Status", dataPath: "status", type: "category" }
1264
- ],
1265
- measures: [
1266
- {
1267
- key: "count",
1268
- label: "Connections",
1269
- dataPath: "count",
1270
- format: "number",
1271
- color: "#1d4ed8"
1272
- }
1273
- ],
1274
- table: { caption: "Connection counts by status." }
1275
- }
1276
- });
1277
- var HealthySyncMetricVisualization = defineVisualization({
1278
- meta: {
1279
- ...META,
1280
- key: "integration-hub.visualization.sync-healthy",
1281
- title: "Healthy Syncs",
1282
- description: "Sync configurations currently healthy or recently successful.",
1283
- goal: "Summarize healthy synchronization capacity.",
1284
- context: "Sync-state comparison."
1285
- },
1286
- source: { primary: SYNC_CONFIG_REF, resultPath: "data" },
1287
- visualization: {
1288
- kind: "metric",
1289
- measure: "value",
1290
- measures: [
1291
- { key: "value", label: "Syncs", dataPath: "value", format: "number" }
1292
- ],
1293
- table: { caption: "Healthy sync count." }
1294
- }
1295
- });
1296
- var AttentionSyncMetricVisualization = defineVisualization({
1297
- meta: {
1298
- ...META,
1299
- key: "integration-hub.visualization.sync-attention",
1300
- title: "Attention Needed",
1301
- description: "Sync configurations paused, failing, or otherwise needing review.",
1302
- goal: "Summarize syncs needing action.",
1303
- context: "Sync-state comparison."
1304
- },
1305
- source: { primary: SYNC_CONFIG_REF, resultPath: "data" },
1306
- visualization: {
1307
- kind: "metric",
1308
- measure: "value",
1309
- measures: [
1310
- { key: "value", label: "Syncs", dataPath: "value", format: "number" }
1311
- ],
1312
- table: { caption: "Syncs requiring attention." }
1313
- }
1314
- });
1315
- var IntegrationVisualizationSpecs = [
1316
- IntegrationTypeVisualization,
1317
- ConnectionStatusVisualization,
1318
- HealthySyncMetricVisualization,
1319
- AttentionSyncMetricVisualization
1320
- ];
1321
- var IntegrationVisualizationRegistry = new VisualizationRegistry([
1322
- ...IntegrationVisualizationSpecs
1323
- ]);
1324
- var IntegrationVisualizationRefs = IntegrationVisualizationSpecs.map((spec) => ({
1325
- key: spec.meta.key,
1326
- version: spec.meta.version
1327
- }));
1328
-
1329
- // src/visualizations/selectors.ts
1330
- function isHealthySync(status) {
1331
- return status === "ACTIVE" || status === "SUCCESS";
1332
- }
1333
- function createIntegrationVisualizationSections(integrations, connections, syncConfigs) {
1334
- const integrationTypes = new Map;
1335
- const connectionStatuses = new Map;
1336
- let healthySyncs = 0;
1337
- let attentionSyncs = 0;
1338
- for (const integration of integrations) {
1339
- integrationTypes.set(integration.type, (integrationTypes.get(integration.type) ?? 0) + 1);
1340
- }
1341
- for (const connection of connections) {
1342
- connectionStatuses.set(connection.status, (connectionStatuses.get(connection.status) ?? 0) + 1);
1343
- }
1344
- for (const syncConfig of syncConfigs) {
1345
- if (isHealthySync(syncConfig.status)) {
1346
- healthySyncs += 1;
1347
- } else {
1348
- attentionSyncs += 1;
1349
- }
1350
- }
1351
- const primaryItems = [
1352
- {
1353
- key: "integration-types",
1354
- spec: IntegrationTypeVisualization,
1355
- data: {
1356
- data: Array.from(integrationTypes.entries()).map(([type, count]) => ({
1357
- type,
1358
- count
1359
- }))
1360
- },
1361
- title: "Integration Types",
1362
- description: "Configured integrations grouped by category.",
1363
- height: 260
1364
- },
1365
- {
1366
- key: "connection-status",
1367
- spec: ConnectionStatusVisualization,
1368
- data: {
1369
- data: Array.from(connectionStatuses.entries()).map(([status, count]) => ({
1370
- status,
1371
- count
1372
- }))
1373
- },
1374
- title: "Connection Status",
1375
- description: "Operational health across current connections."
1376
- }
1377
- ];
1378
- const comparisonItems = [
1379
- {
1380
- key: "healthy-syncs",
1381
- spec: HealthySyncMetricVisualization,
1382
- data: { data: [{ value: healthySyncs }] },
1383
- title: "Healthy Syncs",
1384
- description: "Active or recently successful sync configurations.",
1385
- height: 200
1386
- },
1387
- {
1388
- key: "attention-syncs",
1389
- spec: AttentionSyncMetricVisualization,
1390
- data: { data: [{ value: attentionSyncs }] },
1391
- title: "Attention Needed",
1392
- description: "Paused, failed, or degraded sync configurations.",
1393
- height: 200
1394
- }
1395
- ];
1396
- return {
1397
- primaryItems,
1398
- comparisonItems
1399
- };
1400
- }
1401
- // src/ui/IntegrationDashboard.visualizations.tsx
1402
- import {
1403
- ComparisonView,
1404
- VisualizationCard,
1405
- VisualizationGrid
1406
- } from "@contractspec/lib.design-system";
1407
- import { jsxDEV } from "react/jsx-dev-runtime";
1408
- "use client";
1409
- function IntegrationVisualizationOverview({
1410
- integrations,
1411
- connections,
1412
- syncConfigs
1413
- }) {
1414
- const { primaryItems, comparisonItems } = createIntegrationVisualizationSections(integrations, connections, syncConfigs);
1415
- return /* @__PURE__ */ jsxDEV("section", {
1416
- className: "space-y-4",
1417
- children: [
1418
- /* @__PURE__ */ jsxDEV("div", {
1419
- children: [
1420
- /* @__PURE__ */ jsxDEV("h3", {
1421
- className: "font-semibold text-lg",
1422
- children: "Integration Visualizations"
1423
- }, undefined, false, undefined, this),
1424
- /* @__PURE__ */ jsxDEV("p", {
1425
- className: "text-muted-foreground text-sm",
1426
- children: "Contract-backed charts for integration coverage and sync health."
1427
- }, undefined, false, undefined, this)
1428
- ]
1429
- }, undefined, true, undefined, this),
1430
- /* @__PURE__ */ jsxDEV(VisualizationGrid, {
1431
- children: primaryItems.map((item) => /* @__PURE__ */ jsxDEV(VisualizationCard, {
1432
- data: item.data,
1433
- description: item.description,
1434
- height: item.height,
1435
- spec: item.spec,
1436
- title: item.title
1437
- }, item.key, false, undefined, this))
1438
- }, undefined, false, undefined, this),
1439
- /* @__PURE__ */ jsxDEV(ComparisonView, {
1440
- description: "Comparison surface for healthy versus attention-needed syncs.",
1441
- items: comparisonItems,
1442
- title: "Sync-State Comparison"
1443
- }, undefined, false, undefined, this)
1444
- ]
1445
- }, undefined, true, undefined, this);
1446
- }
1447
-
1448
- // src/ui/IntegrationHubChat.tsx
1449
- import { ChatWithSidebar } from "@contractspec/module.ai-chat";
1450
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1451
- "use client";
1452
- var DEFAULT_SUGGESTIONS = [
1453
- "List my integrations",
1454
- "Show sync status",
1455
- "Add a connection"
1456
- ];
1457
- var DEFAULT_SYSTEM_PROMPT = `You are an Integration Hub assistant. Help users manage integrations, connections, and sync configurations. When asked about integrations, connections, or syncs, provide clear, actionable guidance.`;
1458
- function IntegrationHubChat({
1459
- proxyUrl = "/api/chat",
1460
- mcpServers,
1461
- thinkingLevel = "thinking",
1462
- suggestions = DEFAULT_SUGGESTIONS,
1463
- systemPrompt = DEFAULT_SYSTEM_PROMPT,
1464
- className
1465
- }) {
1466
- return /* @__PURE__ */ jsxDEV2("div", {
1467
- className: className ?? "flex h-[500px] flex-col",
1468
- children: /* @__PURE__ */ jsxDEV2(ChatWithSidebar, {
1469
- className: "flex-1",
1470
- systemPrompt,
1471
- proxyUrl,
1472
- mcpServers,
1473
- thinkingLevel,
1474
- suggestions,
1475
- showSuggestionsWhenEmpty: true
1476
- }, undefined, false, undefined, this)
1477
- }, undefined, false, undefined, this);
1478
- }
1479
-
1480
- // src/ui/tables/integration-table.shared.tsx
1481
- import { Button } from "@contractspec/lib.design-system";
1482
- import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
1483
- import { HStack } from "@contractspec/lib.ui-kit-web/ui/stack";
1484
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1485
- "use client";
1486
- var STATUS_VARIANTS = {
1487
- ACTIVE: "default",
1488
- CONNECTED: "default",
1489
- SUCCESS: "default",
1490
- PENDING: "secondary",
1491
- PAUSED: "secondary",
1492
- ERROR: "destructive",
1493
- DISCONNECTED: "outline"
1494
- };
1495
- function formatDateTime(value) {
1496
- return value ? value.toLocaleString() : "Never";
1497
- }
1498
- function formatJson(value) {
1499
- return value ? JSON.stringify(value, null, 2) : "No configuration";
1500
- }
1501
- function StatusBadge({ status }) {
1502
- return /* @__PURE__ */ jsxDEV3(Badge, {
1503
- variant: STATUS_VARIANTS[status] ?? "outline",
1504
- children: status
1505
- }, undefined, false, undefined, this);
1506
- }
1507
- function IntegrationTableToolbar({
1508
- controller,
1509
- label,
1510
- toggleColumnId,
1511
- toggleVisibleLabel,
1512
- toggleHiddenLabel,
1513
- pinColumnId,
1514
- pinLabel,
1515
- resizeColumnId,
1516
- resizeLabel
1517
- }) {
1518
- const firstRow = controller.rows[0];
1519
- const toggleColumn = controller.columns.find((column) => column.id === toggleColumnId);
1520
- const pinColumn = controller.columns.find((column) => column.id === pinColumnId);
1521
- const resizeColumn = controller.columns.find((column) => column.id === resizeColumnId);
1522
- const pinTarget = pinColumn?.pinState === "left" ? false : "left";
1523
- return /* @__PURE__ */ jsxDEV3(HStack, {
1524
- gap: "sm",
1525
- className: "flex-wrap",
1526
- children: [
1527
- /* @__PURE__ */ jsxDEV3(Badge, {
1528
- variant: "outline",
1529
- children: label
1530
- }, undefined, false, undefined, this),
1531
- /* @__PURE__ */ jsxDEV3(Button, {
1532
- variant: "outline",
1533
- size: "sm",
1534
- onPress: () => firstRow?.toggleExpanded?.(!firstRow?.isExpanded),
1535
- children: "Expand First Row"
1536
- }, undefined, false, undefined, this),
1537
- /* @__PURE__ */ jsxDEV3(Button, {
1538
- variant: "outline",
1539
- size: "sm",
1540
- onPress: () => toggleColumn?.toggleVisibility?.(!toggleColumn?.visible),
1541
- children: toggleColumn?.visible ? toggleVisibleLabel : toggleHiddenLabel
1542
- }, undefined, false, undefined, this),
1543
- /* @__PURE__ */ jsxDEV3(Button, {
1544
- variant: "outline",
1545
- size: "sm",
1546
- onPress: () => pinColumn?.pin?.(pinTarget),
1547
- children: pinColumn?.pinState === "left" ? `Unpin ${pinLabel}` : `Pin ${pinLabel}`
1548
- }, undefined, false, undefined, this),
1549
- /* @__PURE__ */ jsxDEV3(Button, {
1550
- variant: "outline",
1551
- size: "sm",
1552
- onPress: () => resizeColumn?.resizeBy?.(40),
1553
- children: resizeLabel
1554
- }, undefined, false, undefined, this)
1555
- ]
1556
- }, undefined, true, undefined, this);
1557
- }
1558
-
1559
- // src/ui/tables/ConnectionsTable.tsx
1560
- import { DataTable } from "@contractspec/lib.design-system";
1561
- import { useContractTable } from "@contractspec/lib.presentation-runtime-react";
1562
- import { VStack } from "@contractspec/lib.ui-kit-web/ui/stack";
1563
- import { Text } from "@contractspec/lib.ui-kit-web/ui/text";
1564
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1565
- "use client";
1566
- function ConnectionsTable({
1567
- connections
1568
- }) {
1569
- const controller = useContractTable({
1570
- data: connections,
1571
- columns: [
1572
- {
1573
- id: "connection",
1574
- header: "Connection",
1575
- label: "Connection",
1576
- accessor: (connection) => connection.name,
1577
- cell: ({ item }) => /* @__PURE__ */ jsxDEV4(VStack, {
1578
- gap: "xs",
1579
- children: [
1580
- /* @__PURE__ */ jsxDEV4(Text, {
1581
- className: "font-medium text-sm",
1582
- children: item.name
1583
- }, undefined, false, undefined, this),
1584
- /* @__PURE__ */ jsxDEV4(Text, {
1585
- className: "text-muted-foreground text-xs",
1586
- children: [
1587
- "Created ",
1588
- item.createdAt.toLocaleDateString()
1589
- ]
1590
- }, undefined, true, undefined, this)
1591
- ]
1592
- }, undefined, true, undefined, this),
1593
- size: 240,
1594
- minSize: 180,
1595
- canSort: true,
1596
- canPin: true,
1597
- canResize: true
1598
- },
1599
- {
1600
- id: "status",
1601
- header: "Status",
1602
- label: "Status",
1603
- accessorKey: "status",
1604
- cell: ({ value }) => /* @__PURE__ */ jsxDEV4(StatusBadge, {
1605
- status: String(value)
1606
- }, undefined, false, undefined, this),
1607
- size: 150,
1608
- canSort: true,
1609
- canPin: true,
1610
- canResize: true
1611
- },
1612
- {
1613
- id: "lastSyncAt",
1614
- header: "Last Sync",
1615
- label: "Last Sync",
1616
- accessor: (connection) => connection.lastSyncAt?.getTime() ?? 0,
1617
- cell: ({ item }) => formatDateTime(item.lastSyncAt),
1618
- size: 200,
1619
- canSort: true,
1620
- canHide: true,
1621
- canResize: true
1622
- },
1623
- {
1624
- id: "errorMessage",
1625
- header: "Errors",
1626
- label: "Errors",
1627
- accessor: (connection) => connection.errorMessage ?? "",
1628
- cell: ({ value }) => String(value || "No errors"),
1629
- size: 240,
1630
- canHide: true,
1631
- canResize: true
1632
- }
1633
- ],
1634
- initialState: {
1635
- pagination: { pageIndex: 0, pageSize: 3 },
1636
- columnVisibility: { errorMessage: false },
1637
- columnPinning: { left: ["connection"], right: [] }
1638
- },
1639
- renderExpandedContent: (connection) => /* @__PURE__ */ jsxDEV4(VStack, {
1640
- gap: "sm",
1641
- className: "py-2",
1642
- children: [
1643
- /* @__PURE__ */ jsxDEV4(Text, {
1644
- className: "font-medium text-sm",
1645
- children: "Credentials"
1646
- }, undefined, false, undefined, this),
1647
- /* @__PURE__ */ jsxDEV4("pre", {
1648
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1649
- children: formatJson(connection.credentials)
1650
- }, undefined, false, undefined, this),
1651
- /* @__PURE__ */ jsxDEV4(Text, {
1652
- className: "font-medium text-sm",
1653
- children: "Config"
1654
- }, undefined, false, undefined, this),
1655
- /* @__PURE__ */ jsxDEV4("pre", {
1656
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1657
- children: formatJson(connection.config)
1658
- }, undefined, false, undefined, this),
1659
- /* @__PURE__ */ jsxDEV4(Text, {
1660
- className: "text-muted-foreground text-sm",
1661
- children: connection.errorMessage ?? "No sync errors recorded."
1662
- }, undefined, false, undefined, this)
1663
- ]
1664
- }, undefined, true, undefined, this),
1665
- getCanExpand: () => true
1666
- });
1667
- return /* @__PURE__ */ jsxDEV4(DataTable, {
1668
- controller,
1669
- title: "Connections",
1670
- description: "Client-mode ContractSpec table with visibility, pinning, resizing, and expanded diagnostics.",
1671
- toolbar: /* @__PURE__ */ jsxDEV4(IntegrationTableToolbar, {
1672
- controller,
1673
- label: `${connections.length} total connections`,
1674
- toggleColumnId: "errorMessage",
1675
- toggleVisibleLabel: "Hide Error Column",
1676
- toggleHiddenLabel: "Show Error Column",
1677
- pinColumnId: "status",
1678
- pinLabel: "Status",
1679
- resizeColumnId: "connection",
1680
- resizeLabel: "Widen Connection"
1681
- }, undefined, false, undefined, this),
1682
- emptyState: /* @__PURE__ */ jsxDEV4("div", {
1683
- className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
1684
- children: "No connections found"
1685
- }, undefined, false, undefined, this)
1686
- }, undefined, false, undefined, this);
1687
- }
1688
-
1689
- // src/ui/tables/SyncConfigsTable.tsx
1690
- import { DataTable as DataTable2 } from "@contractspec/lib.design-system";
1691
- import { useContractTable as useContractTable2 } from "@contractspec/lib.presentation-runtime-react";
1692
- import { VStack as VStack2 } from "@contractspec/lib.ui-kit-web/ui/stack";
1693
- import { Text as Text2 } from "@contractspec/lib.ui-kit-web/ui/text";
1694
- import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
1695
- "use client";
1696
- function SyncConfigsTable({
1697
- syncConfigs
1698
- }) {
1699
- const controller = useContractTable2({
1700
- data: syncConfigs,
1701
- columns: [
1702
- {
1703
- id: "sync",
1704
- header: "Sync Config",
1705
- label: "Sync Config",
1706
- accessor: (sync) => sync.name,
1707
- cell: ({ item }) => /* @__PURE__ */ jsxDEV5(VStack2, {
1708
- gap: "xs",
1709
- children: [
1710
- /* @__PURE__ */ jsxDEV5(Text2, {
1711
- className: "font-medium text-sm",
1712
- children: item.name
1713
- }, undefined, false, undefined, this),
1714
- /* @__PURE__ */ jsxDEV5(Text2, {
1715
- className: "text-muted-foreground text-xs",
1716
- children: [
1717
- item.sourceEntity,
1718
- " → ",
1719
- item.targetEntity
1720
- ]
1721
- }, undefined, true, undefined, this)
1722
- ]
1723
- }, undefined, true, undefined, this),
1724
- size: 260,
1725
- minSize: 200,
1726
- canSort: true,
1727
- canPin: true,
1728
- canResize: true
1729
- },
1730
- {
1731
- id: "frequency",
1732
- header: "Frequency",
1733
- label: "Frequency",
1734
- accessorKey: "frequency",
1735
- size: 160,
1736
- canSort: true,
1737
- canHide: true,
1738
- canResize: true
1739
- },
1740
- {
1741
- id: "status",
1742
- header: "Status",
1743
- label: "Status",
1744
- accessorKey: "status",
1745
- cell: ({ value }) => /* @__PURE__ */ jsxDEV5(StatusBadge, {
1746
- status: String(value)
1747
- }, undefined, false, undefined, this),
1748
- size: 150,
1749
- canSort: true,
1750
- canPin: true,
1751
- canResize: true
1752
- },
1753
- {
1754
- id: "recordsSynced",
1755
- header: "Records",
1756
- label: "Records",
1757
- accessorKey: "recordsSynced",
1758
- align: "right",
1759
- size: 140,
1760
- canSort: true,
1761
- canResize: true
1762
- },
1763
- {
1764
- id: "lastRunAt",
1765
- header: "Last Run",
1766
- label: "Last Run",
1767
- accessor: (sync) => sync.lastRunAt?.getTime() ?? 0,
1768
- cell: ({ item }) => formatDateTime(item.lastRunAt),
1769
- size: 200,
1770
- canSort: true,
1771
- canHide: true,
1772
- canResize: true
1773
- }
1774
- ],
1775
- initialState: {
1776
- pagination: { pageIndex: 0, pageSize: 3 },
1777
- columnVisibility: { lastRunAt: false },
1778
- columnPinning: { left: ["sync"], right: [] }
1779
- },
1780
- renderExpandedContent: (sync) => /* @__PURE__ */ jsxDEV5(VStack2, {
1781
- gap: "sm",
1782
- className: "py-2",
1783
- children: [
1784
- /* @__PURE__ */ jsxDEV5(Text2, {
1785
- className: "text-muted-foreground text-sm",
1786
- children: [
1787
- "Connection ",
1788
- sync.connectionId
1789
- ]
1790
- }, undefined, true, undefined, this),
1791
- /* @__PURE__ */ jsxDEV5(Text2, {
1792
- className: "text-muted-foreground text-sm",
1793
- children: [
1794
- "Last run: ",
1795
- formatDateTime(sync.lastRunAt)
1796
- ]
1797
- }, undefined, true, undefined, this),
1798
- /* @__PURE__ */ jsxDEV5(Text2, {
1799
- className: "text-muted-foreground text-sm",
1800
- children: [
1801
- "Last status: ",
1802
- sync.lastRunStatus ?? "No runs recorded"
1803
- ]
1804
- }, undefined, true, undefined, this),
1805
- /* @__PURE__ */ jsxDEV5(Text2, {
1806
- className: "text-muted-foreground text-sm",
1807
- children: [
1808
- "Updated ",
1809
- sync.updatedAt.toLocaleString()
1810
- ]
1811
- }, undefined, true, undefined, this)
1812
- ]
1813
- }, undefined, true, undefined, this),
1814
- getCanExpand: () => true
1815
- });
1816
- return /* @__PURE__ */ jsxDEV5(DataTable2, {
1817
- controller,
1818
- title: "Sync Configs",
1819
- description: "Shared table primitives applied to sync monitoring without changing the surrounding dashboard layout.",
1820
- toolbar: /* @__PURE__ */ jsxDEV5(IntegrationTableToolbar, {
1821
- controller,
1822
- label: `${syncConfigs.length} syncs`,
1823
- toggleColumnId: "lastRunAt",
1824
- toggleVisibleLabel: "Hide Last Run",
1825
- toggleHiddenLabel: "Show Last Run",
1826
- pinColumnId: "status",
1827
- pinLabel: "Status",
1828
- resizeColumnId: "sync",
1829
- resizeLabel: "Widen Sync"
1830
- }, undefined, false, undefined, this),
1831
- emptyState: /* @__PURE__ */ jsxDEV5("div", {
1832
- className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
1833
- children: "No sync configurations found"
1834
- }, undefined, false, undefined, this)
1835
- }, undefined, false, undefined, this);
1836
- }
1837
- // src/ui/IntegrationDashboard.tsx
1838
- import {
1839
- Button as Button2,
1840
- ErrorState,
1841
- LoaderBlock,
1842
- StatCard,
1843
- StatCardGroup
1844
- } from "@contractspec/lib.design-system";
1845
- import { useState as useState2 } from "react";
1846
- import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
1847
- "use client";
1848
- var STATUS_COLORS = {
1849
- ACTIVE: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1850
- INACTIVE: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1851
- CONNECTED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1852
- DISCONNECTED: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1853
- PENDING: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
1854
- ERROR: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
1855
- PAUSED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
1856
- };
1857
- var TYPE_ICONS = {
1858
- CRM: "\uD83D\uDCCA",
1859
- MARKETING: "\uD83D\uDCE3",
1860
- PAYMENT: "\uD83D\uDCB3",
1861
- COMMUNICATION: "\uD83D\uDCAC",
1862
- DATA: "\uD83D\uDDC4️",
1863
- CUSTOM: "⚙️"
1864
- };
1865
- function IntegrationDashboard() {
1866
- const [activeTab, setActiveTab] = useState2("integrations");
1867
- const {
1868
- integrations,
1869
- connections,
1870
- syncConfigs,
1871
- loading,
1872
- error,
1873
- stats,
1874
- refetch
1875
- } = useIntegrationData();
1876
- const tabs = [
1877
- { id: "integrations", label: "Integrations", icon: "\uD83D\uDD0C" },
1878
- { id: "connections", label: "Connections", icon: "\uD83D\uDD17" },
1879
- { id: "syncs", label: "Sync Configs", icon: "\uD83D\uDD04" },
1880
- { id: "chat", label: "Chat", icon: "\uD83D\uDCAC" }
1881
- ];
1882
- if (loading) {
1883
- return /* @__PURE__ */ jsxDEV6(LoaderBlock, {
1884
- label: "Loading Integrations..."
1885
- }, undefined, false, undefined, this);
1886
- }
1887
- if (error) {
1888
- return /* @__PURE__ */ jsxDEV6(ErrorState, {
1889
- title: "Failed to load Integrations",
1890
- description: error.message,
1891
- onRetry: refetch,
1892
- retryLabel: "Retry"
1893
- }, undefined, false, undefined, this);
1894
- }
1895
- return /* @__PURE__ */ jsxDEV6("div", {
1896
- className: "space-y-6",
1897
- children: [
1898
- /* @__PURE__ */ jsxDEV6("div", {
1899
- className: "flex items-center justify-between",
1900
- children: [
1901
- /* @__PURE__ */ jsxDEV6("h2", {
1902
- className: "font-bold text-2xl",
1903
- children: "Integration Hub"
1904
- }, undefined, false, undefined, this),
1905
- /* @__PURE__ */ jsxDEV6(Button2, {
1906
- onClick: () => alert("Add integration modal"),
1907
- children: [
1908
- /* @__PURE__ */ jsxDEV6("span", {
1909
- className: "mr-2",
1910
- children: "+"
1911
- }, undefined, false, undefined, this),
1912
- " Add Integration"
1913
- ]
1914
- }, undefined, true, undefined, this)
1915
- ]
1916
- }, undefined, true, undefined, this),
1917
- /* @__PURE__ */ jsxDEV6(StatCardGroup, {
1918
- children: [
1919
- /* @__PURE__ */ jsxDEV6(StatCard, {
1920
- label: "Integrations",
1921
- value: stats.totalIntegrations,
1922
- hint: `${stats.activeIntegrations} active`
1923
- }, undefined, false, undefined, this),
1924
- /* @__PURE__ */ jsxDEV6(StatCard, {
1925
- label: "Connections",
1926
- value: stats.totalConnections,
1927
- hint: `${stats.connectedCount} connected`
1928
- }, undefined, false, undefined, this),
1929
- /* @__PURE__ */ jsxDEV6(StatCard, {
1930
- label: "Syncs",
1931
- value: stats.totalSyncs,
1932
- hint: `${stats.activeSyncs} active`
1933
- }, undefined, false, undefined, this)
1934
- ]
1935
- }, undefined, true, undefined, this),
1936
- /* @__PURE__ */ jsxDEV6(IntegrationVisualizationOverview, {
1937
- connections,
1938
- integrations,
1939
- syncConfigs
1940
- }, undefined, false, undefined, this),
1941
- /* @__PURE__ */ jsxDEV6("nav", {
1942
- className: "flex gap-1 rounded-lg bg-muted p-1",
1943
- role: "tablist",
1944
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV6(Button2, {
1945
- type: "button",
1946
- role: "tab",
1947
- "aria-selected": activeTab === tab.id,
1948
- onClick: () => setActiveTab(tab.id),
1949
- className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
1950
- children: [
1951
- /* @__PURE__ */ jsxDEV6("span", {
1952
- children: tab.icon
1953
- }, undefined, false, undefined, this),
1954
- tab.label
1955
- ]
1956
- }, tab.id, true, undefined, this))
1957
- }, undefined, false, undefined, this),
1958
- /* @__PURE__ */ jsxDEV6("div", {
1959
- className: "min-h-[400px]",
1960
- role: "tabpanel",
1961
- children: [
1962
- activeTab === "integrations" && /* @__PURE__ */ jsxDEV6("div", {
1963
- className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1964
- children: [
1965
- integrations.map((integration) => /* @__PURE__ */ jsxDEV6("div", {
1966
- className: "cursor-pointer rounded-lg border border-border bg-card p-4 transition-colors hover:bg-muted/50",
1967
- children: [
1968
- /* @__PURE__ */ jsxDEV6("div", {
1969
- className: "mb-3 flex items-center gap-3",
1970
- children: [
1971
- /* @__PURE__ */ jsxDEV6("span", {
1972
- className: "text-2xl",
1973
- children: TYPE_ICONS[integration.type] ?? "⚙️"
1974
- }, undefined, false, undefined, this),
1975
- /* @__PURE__ */ jsxDEV6("div", {
1976
- children: [
1977
- /* @__PURE__ */ jsxDEV6("h3", {
1978
- className: "font-medium",
1979
- children: integration.name
1980
- }, undefined, false, undefined, this),
1981
- /* @__PURE__ */ jsxDEV6("p", {
1982
- className: "text-muted-foreground text-sm",
1983
- children: integration.type
1984
- }, undefined, false, undefined, this)
1985
- ]
1986
- }, undefined, true, undefined, this)
1987
- ]
1988
- }, undefined, true, undefined, this),
1989
- /* @__PURE__ */ jsxDEV6("div", {
1990
- className: "flex items-center justify-between",
1991
- children: [
1992
- /* @__PURE__ */ jsxDEV6("span", {
1993
- className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[integration.status] ?? ""}`,
1994
- children: integration.status
1995
- }, undefined, false, undefined, this),
1996
- /* @__PURE__ */ jsxDEV6("span", {
1997
- className: "text-muted-foreground text-xs",
1998
- children: integration.createdAt.toLocaleDateString()
1999
- }, undefined, false, undefined, this)
2000
- ]
2001
- }, undefined, true, undefined, this)
2002
- ]
2003
- }, integration.id, true, undefined, this)),
2004
- integrations.length === 0 && /* @__PURE__ */ jsxDEV6("div", {
2005
- className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
2006
- children: "No integrations configured"
2007
- }, undefined, false, undefined, this)
2008
- ]
2009
- }, undefined, true, undefined, this),
2010
- activeTab === "connections" && /* @__PURE__ */ jsxDEV6(ConnectionsTable, {
2011
- connections
2012
- }, undefined, false, undefined, this),
2013
- activeTab === "chat" && /* @__PURE__ */ jsxDEV6(IntegrationHubChat, {
2014
- proxyUrl: "/api/chat",
2015
- thinkingLevel: "thinking",
2016
- suggestions: [
2017
- "List my integrations",
2018
- "Show sync status",
2019
- "Add a connection"
2020
- ],
2021
- className: "min-h-[400px]"
2022
- }, undefined, false, undefined, this),
2023
- activeTab === "syncs" && /* @__PURE__ */ jsxDEV6(SyncConfigsTable, {
2024
- syncConfigs
2025
- }, undefined, false, undefined, this)
2026
- ]
2027
- }, undefined, true, undefined, this)
2028
- ]
2029
- }, undefined, true, undefined, this);
2030
- }
2031
-
2032
- // src/ui/renderers/integration.markdown.ts
2033
- var mockIntegrations = [
2034
- {
2035
- id: "int-1",
2036
- name: "Salesforce",
2037
- type: "CRM",
2038
- status: "ACTIVE",
2039
- connectionCount: 3
2040
- },
2041
- {
2042
- id: "int-2",
2043
- name: "HubSpot",
2044
- type: "MARKETING",
2045
- status: "ACTIVE",
2046
- connectionCount: 2
2047
- },
2048
- {
2049
- id: "int-3",
2050
- name: "Stripe",
2051
- type: "PAYMENT",
2052
- status: "ACTIVE",
2053
- connectionCount: 1
2054
- },
2055
- {
2056
- id: "int-4",
2057
- name: "Slack",
2058
- type: "COMMUNICATION",
2059
- status: "INACTIVE",
2060
- connectionCount: 0
2061
- },
2062
- {
2063
- id: "int-5",
2064
- name: "Google Sheets",
2065
- type: "DATA",
2066
- status: "ACTIVE",
2067
- connectionCount: 5
2068
- },
2069
- {
2070
- id: "int-6",
2071
- name: "PostHog",
2072
- type: "ANALYTICS",
2073
- status: "ACTIVE",
2074
- connectionCount: 1
2075
- }
2076
- ];
2077
- var mockConnections = [
2078
- {
2079
- id: "conn-1",
2080
- integrationId: "int-1",
2081
- name: "Production Salesforce",
2082
- status: "CONNECTED",
2083
- lastSyncAt: "2024-01-16T10:00:00Z"
2084
- },
2085
- {
2086
- id: "conn-2",
2087
- integrationId: "int-1",
2088
- name: "Sandbox Salesforce",
2089
- status: "CONNECTED",
2090
- lastSyncAt: "2024-01-15T14:00:00Z"
2091
- },
2092
- {
2093
- id: "conn-3",
2094
- integrationId: "int-2",
2095
- name: "Marketing HubSpot",
2096
- status: "CONNECTED",
2097
- lastSyncAt: "2024-01-16T08:00:00Z"
2098
- },
2099
- {
2100
- id: "conn-4",
2101
- integrationId: "int-3",
2102
- name: "Stripe Live",
2103
- status: "CONNECTED",
2104
- lastSyncAt: "2024-01-16T12:00:00Z"
2105
- },
2106
- {
2107
- id: "conn-5",
2108
- integrationId: "int-5",
2109
- name: "Analytics Sheet",
2110
- status: "ERROR",
2111
- lastSyncAt: "2024-01-14T09:00:00Z",
2112
- error: "Authentication expired"
2113
- },
2114
- {
2115
- id: "conn-6",
2116
- integrationId: "int-6",
2117
- name: "PostHog Workspace",
2118
- status: "CONNECTED",
2119
- lastSyncAt: "2024-01-16T11:45:00Z"
2120
- }
2121
- ];
2122
- var mockSyncConfigs = [
2123
- {
2124
- id: "sync-1",
2125
- connectionId: "conn-1",
2126
- name: "Contacts Sync",
2127
- frequency: "HOURLY",
2128
- lastRunAt: "2024-01-16T10:00:00Z",
2129
- status: "SUCCESS",
2130
- recordsSynced: 1250
2131
- },
2132
- {
2133
- id: "sync-2",
2134
- connectionId: "conn-1",
2135
- name: "Opportunities Sync",
2136
- frequency: "DAILY",
2137
- lastRunAt: "2024-01-16T00:00:00Z",
2138
- status: "SUCCESS",
2139
- recordsSynced: 340
2140
- },
2141
- {
2142
- id: "sync-3",
2143
- connectionId: "conn-3",
2144
- name: "Orders Sync",
2145
- frequency: "REALTIME",
2146
- lastRunAt: "2024-01-16T12:30:00Z",
2147
- status: "SUCCESS",
2148
- recordsSynced: 89
2149
- },
2150
- {
2151
- id: "sync-4",
2152
- connectionId: "conn-5",
2153
- name: "Metrics Export",
2154
- frequency: "DAILY",
2155
- lastRunAt: "2024-01-14T09:00:00Z",
2156
- status: "FAILED",
2157
- recordsSynced: 0
2158
- }
2159
- ];
2160
- var integrationDashboardMarkdownRenderer = {
2161
- target: "markdown",
2162
- render: async (desc) => {
2163
- if (desc.source.type !== "component" || desc.source.componentKey !== "IntegrationDashboard") {
2164
- throw new Error("integrationDashboardMarkdownRenderer: not IntegrationDashboard");
2165
- }
2166
- const integrations = mockIntegrations;
2167
- const connections = mockConnections;
2168
- const syncs = mockSyncConfigs;
2169
- const visualizations = createIntegrationVisualizationSections(integrations, connections, syncs);
2170
- const activeIntegrations = integrations.filter((i) => i.status === "ACTIVE");
2171
- const connectedConnections = connections.filter((c) => c.status === "CONNECTED");
2172
- const errorConnections = connections.filter((c) => c.status === "ERROR");
2173
- const successfulSyncs = syncs.filter((s) => s.status === "SUCCESS");
2174
- const totalRecordsSynced = successfulSyncs.reduce((sum, s) => sum + s.recordsSynced, 0);
2175
- const lines = [
2176
- "# Integration Hub",
2177
- "",
2178
- "> Connect and sync data with external services",
2179
- "",
2180
- "## Overview",
2181
- "",
2182
- "| Metric | Value |",
2183
- "|--------|-------|",
2184
- `| Active Integrations | ${activeIntegrations.length} |`,
2185
- `| Connected Services | ${connectedConnections.length} |`,
2186
- `| Error Connections | ${errorConnections.length} |`,
2187
- `| Sync Configs | ${syncs.length} |`,
2188
- `| Records Synced (24h) | ${totalRecordsSynced.toLocaleString()} |`,
2189
- ""
2190
- ];
2191
- lines.push("## Visualization Overview");
2192
- lines.push("");
2193
- for (const item of [
2194
- ...visualizations.primaryItems,
2195
- ...visualizations.comparisonItems
2196
- ]) {
2197
- lines.push(`- **${item.title}** via \`${item.spec.meta.key}\``);
2198
- }
2199
- lines.push("");
2200
- lines.push("## Integrations");
2201
- lines.push("");
2202
- lines.push("| Name | Type | Connections | Status |");
2203
- lines.push("|------|------|-------------|--------|");
2204
- for (const integration of integrations) {
2205
- const statusIcon = integration.status === "ACTIVE" ? "\uD83D\uDFE2" : "⚫";
2206
- lines.push(`| ${integration.name} | ${integration.type} | ${integration.connectionCount} | ${statusIcon} ${integration.status} |`);
2207
- }
2208
- lines.push("");
2209
- lines.push("## Recent Sync Activity");
2210
- lines.push("");
2211
- lines.push("| Sync | Frequency | Last Run | Records | Status |");
2212
- lines.push("|------|-----------|----------|---------|--------|");
2213
- for (const sync of syncs) {
2214
- const lastRun = new Date(sync.lastRunAt).toLocaleString();
2215
- const statusIcon = sync.status === "SUCCESS" ? "✅" : "❌";
2216
- lines.push(`| ${sync.name} | ${sync.frequency} | ${lastRun} | ${sync.recordsSynced} | ${statusIcon} ${sync.status} |`);
2217
- }
2218
- if (errorConnections.length > 0) {
2219
- lines.push("");
2220
- lines.push("## ⚠️ Connections with Errors");
2221
- lines.push("");
2222
- for (const conn of errorConnections) {
2223
- const integration = integrations.find((i) => i.id === conn.integrationId);
2224
- lines.push(`- **${conn.name}** (${integration?.name ?? "Unknown"}): ${conn.error ?? "Unknown error"}`);
2225
- }
2226
- }
2227
- return {
2228
- mimeType: "text/markdown",
2229
- body: lines.join(`
2230
- `)
2231
- };
2232
- }
2233
- };
2234
- var connectionListMarkdownRenderer = {
2235
- target: "markdown",
2236
- render: async (desc) => {
2237
- if (desc.source.type !== "component" || desc.source.componentKey !== "ConnectionList") {
2238
- throw new Error("connectionListMarkdownRenderer: not ConnectionList");
2239
- }
2240
- const connections = mockConnections;
2241
- const integrations = mockIntegrations;
2242
- const lines = [
2243
- "# Connections",
2244
- "",
2245
- "> Manage connections to external services",
2246
- ""
2247
- ];
2248
- for (const integration of integrations) {
2249
- const intConnections = connections.filter((c) => c.integrationId === integration.id);
2250
- if (intConnections.length === 0)
2251
- continue;
2252
- lines.push(`## ${integration.name}`);
2253
- lines.push("");
2254
- lines.push("| Connection | Status | Last Sync |");
2255
- lines.push("|------------|--------|-----------|");
2256
- for (const conn of intConnections) {
2257
- const lastSync = new Date(conn.lastSyncAt).toLocaleString();
2258
- const statusIcon = conn.status === "CONNECTED" ? "\uD83D\uDFE2" : conn.status === "ERROR" ? "\uD83D\uDD34" : "⚫";
2259
- lines.push(`| ${conn.name} | ${statusIcon} ${conn.status} | ${lastSync} |`);
2260
- }
2261
- lines.push("");
2262
- }
2263
- return {
2264
- mimeType: "text/markdown",
2265
- body: lines.join(`
2266
- `)
2267
- };
2268
- }
2269
- };
2270
- var syncConfigMarkdownRenderer = {
2271
- target: "markdown",
2272
- render: async (desc) => {
2273
- if (desc.source.type !== "component" || desc.source.componentKey !== "SyncConfigEditor") {
2274
- throw new Error("syncConfigMarkdownRenderer: not SyncConfigEditor");
2275
- }
2276
- const syncs = mockSyncConfigs;
2277
- const connections = mockConnections;
2278
- const lines = [
2279
- "# Sync Configurations",
2280
- "",
2281
- "> Configure automated data synchronization",
2282
- ""
2283
- ];
2284
- for (const sync of syncs) {
2285
- const connection = connections.find((c) => c.id === sync.connectionId);
2286
- const statusIcon = sync.status === "SUCCESS" ? "✅" : "❌";
2287
- lines.push(`## ${sync.name}`);
2288
- lines.push("");
2289
- lines.push(`**Connection:** ${connection?.name ?? "Unknown"}`);
2290
- lines.push(`**Frequency:** ${sync.frequency}`);
2291
- lines.push(`**Status:** ${statusIcon} ${sync.status}`);
2292
- lines.push(`**Last Run:** ${new Date(sync.lastRunAt).toLocaleString()}`);
2293
- lines.push(`**Records Synced:** ${sync.recordsSynced.toLocaleString()}`);
2294
- lines.push("");
2295
- }
2296
- lines.push("## Frequency Options");
2297
- lines.push("");
2298
- lines.push("- **REALTIME**: Sync on every change");
2299
- lines.push("- **HOURLY**: Sync every hour");
2300
- lines.push("- **DAILY**: Sync once per day");
2301
- lines.push("- **WEEKLY**: Sync once per week");
2302
- lines.push("- **MANUAL**: Sync only when triggered");
2303
- return {
2304
- mimeType: "text/markdown",
2305
- body: lines.join(`
2306
- `)
2307
- };
2308
- }
2309
- };
2310
- export {
2311
- useIntegrationData,
2312
- syncConfigMarkdownRenderer,
2313
- runIntegrationHubMcpExampleFromEnv,
2314
- integrationDashboardMarkdownRenderer,
2315
- hasChanges,
2316
- createSyncEngine,
2317
- createIntegrationVisualizationSections,
2318
- createIntegrationHandlers,
2319
- connectionListMarkdownRenderer,
2320
- computeChecksum,
2321
- TriggerSyncInputModel,
2322
- TriggerSyncContract,
2323
- SyncStatusEnum,
2324
- SyncRunModel,
2325
- SyncDirectionEnum,
2326
- SyncConfigModel,
2327
- MappingTypeEnum,
2328
- ListSyncRunsOutputModel,
2329
- ListSyncRunsInputModel,
2330
- ListSyncRunsContract,
2331
- IntegrationVisualizationSpecs,
2332
- IntegrationVisualizationRegistry,
2333
- IntegrationVisualizationRefs,
2334
- IntegrationTypeVisualization,
2335
- IntegrationStatusEnum,
2336
- IntegrationModel,
2337
- IntegrationHubChat,
2338
- IntegrationDashboard,
2339
- HealthySyncMetricVisualization,
2340
- FieldMappingModel,
2341
- CreateSyncConfigInputModel,
2342
- CreateSyncConfigContract,
2343
- CreateIntegrationInputModel,
2344
- CreateIntegrationContract,
2345
- CreateConnectionInputModel,
2346
- CreateConnectionContract,
2347
- ConnectionStatusVisualization,
2348
- ConnectionStatusEnum,
2349
- ConnectionModel,
2350
- BasicSyncEngine,
2351
- BasicFieldTransformer,
2352
- AttentionSyncMetricVisualization,
2353
- AddFieldMappingInputModel,
2354
- AddFieldMappingContract
2355
- };
1
+ import{defineEnum as HH}from"@contractspec/lib.schema";var KH=HH("ConnectionStatus",["PENDING","CONNECTED","DISCONNECTED","ERROR","EXPIRED"]),XH=HH("AuthType",["api_key","oauth2","bearer","header","basic","webhook_signing","service_account"]),ZH=HH("TransportType",["rest","mcp","webhook","sdk"]);import{defineSchemaModel as jH,ScalarTypeEnum as N}from"@contractspec/lib.schema";var m=jH({name:"ConnectionModel",fields:{id:{type:N.String_unsecure(),isOptional:!1},integrationId:{type:N.String_unsecure(),isOptional:!1},name:{type:N.String_unsecure(),isOptional:!1},status:{type:KH,isOptional:!1},authType:{type:N.String_unsecure(),isOptional:!1},externalAccountName:{type:N.String_unsecure(),isOptional:!0},connectedAt:{type:N.DateTime(),isOptional:!0},lastHealthCheck:{type:N.DateTime(),isOptional:!0},healthStatus:{type:N.String_unsecure(),isOptional:!0},transport:{type:ZH,isOptional:!0},authMethod:{type:XH,isOptional:!0},apiVersion:{type:N.String_unsecure(),isOptional:!0},ownershipMode:{type:N.String_unsecure(),isOptional:!0}}}),$H=jH({name:"CreateConnectionInput",fields:{integrationId:{type:N.String_unsecure(),isOptional:!1},name:{type:N.NonEmptyString(),isOptional:!1},authType:{type:N.NonEmptyString(),isOptional:!1},credentials:{type:N.JSON(),isOptional:!0},transport:{type:ZH,isOptional:!0},authMethod:{type:XH,isOptional:!0},apiVersion:{type:N.String_unsecure(),isOptional:!0},ownershipMode:{type:N.String_unsecure(),isOptional:!0}}});import{defineCommand as aH}from"@contractspec/lib.contracts-spec/operations";var nH=["@example.integration-hub"],eH=aH({meta:{key:"integration.connection.create",version:"1.0.0",stability:"stable",owners:[...nH],tags:["integration","connection","create"],description:"Create a connection to an external system.",goal:"Authenticate with external systems.",context:"Connection setup."},io:{input:$H,output:m},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.connection.created",version:"1.0.0",when:"Connection created",payload:m}],audit:["integration.connection.created"]},acceptance:{scenarios:[{key:"create-connection-happy-path",given:["User is authenticated"],when:["User creates connection with valid credentials"],then:["Connection is created","ConnectionCreated event is emitted"]}],examples:[{key:"connect-crm",input:{name:"Salesforce Prod",integrationId:"salesforce",credentials:{clientId:"xxx"}},output:{id:"conn-123",status:"connected",connectedAt:"2025-01-01T12:00:00Z"}}]}});import{web as HK}from"@contractspec/lib.runtime-sandbox";var{generateId:p}=HK;function hH(H){return{id:H.id,projectId:H.projectId,organizationId:H.organizationId,name:H.name,description:H.description??void 0,type:H.type,status:H.status,iconUrl:H.iconUrl??void 0,createdAt:new Date(H.createdAt),updatedAt:new Date(H.updatedAt)}}function QH(H){return{id:H.id,integrationId:H.integrationId,name:H.name,status:H.status,credentials:H.credentials?JSON.parse(H.credentials):void 0,config:H.config?JSON.parse(H.config):void 0,lastSyncAt:H.lastSyncAt?new Date(H.lastSyncAt):void 0,errorMessage:H.errorMessage??void 0,createdAt:new Date(H.createdAt),updatedAt:new Date(H.updatedAt)}}function qH(H){return{id:H.id,connectionId:H.connectionId,name:H.name,sourceEntity:H.sourceEntity,targetEntity:H.targetEntity,frequency:H.frequency,status:H.status,lastRunAt:H.lastRunAt?new Date(H.lastRunAt):void 0,lastRunStatus:H.lastRunStatus??void 0,recordsSynced:H.recordsSynced,createdAt:new Date(H.createdAt),updatedAt:new Date(H.updatedAt)}}function xH(H){return{id:H.id,syncConfigId:H.syncConfigId,sourceField:H.sourceField,targetField:H.targetField,transformType:H.transformType??void 0,transformConfig:H.transformConfig?JSON.parse(H.transformConfig):void 0,createdAt:new Date(H.createdAt)}}function KK(H){async function Z(Q){let{projectId:Y,type:P,status:B,search:_,limit:z=20,offset:M=0}=Q,j="WHERE projectId = ?",f=[Y];if(P&&P!=="all")j+=" AND type = ?",f.push(P);if(B&&B!=="all")j+=" AND status = ?",f.push(B);if(_)j+=" AND name LIKE ?",f.push(`%${_}%`);let sH=(await H.query(`SELECT COUNT(*) as count FROM integration ${j}`,f)).rows[0]?.count??0;return{integrations:(await H.query(`SELECT * FROM integration ${j} ORDER BY name LIMIT ? OFFSET ?`,[...f,z,M])).rows.map(hH),total:sH}}async function K(Q,Y){let P=p("integ"),B=new Date().toISOString();await H.execute(`INSERT INTO integration (id, projectId, organizationId, name, description, type, status, iconUrl, createdAt, updatedAt)
2
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[P,Y.projectId,Y.organizationId,Q.name,Q.description??null,Q.type,"INACTIVE",Q.iconUrl??null,B,B]);let _=(await H.query("SELECT * FROM integration WHERE id = ?",[P])).rows;return hH(_[0])}async function X(Q){let{integrationId:Y,status:P,limit:B=20,offset:_=0}=Q,z="WHERE 1=1",M=[];if(Y)z+=" AND integrationId = ?",M.push(Y);if(P&&P!=="all")z+=" AND status = ?",M.push(P);let f=(await H.query(`SELECT COUNT(*) as count FROM integration_connection ${z}`,M)).rows[0]?.count??0;return{connections:(await H.query(`SELECT * FROM integration_connection ${z} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...M,B,_])).rows.map(QH),total:f}}async function $(Q){let Y=p("conn"),P=new Date().toISOString();await H.execute(`INSERT INTO integration_connection (id, integrationId, name, status, credentials, config, createdAt, updatedAt)
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[Y,Q.integrationId,Q.name,"PENDING",Q.credentials?JSON.stringify(Q.credentials):null,Q.config?JSON.stringify(Q.config):null,P,P]),await H.execute("UPDATE integration_connection SET status = 'CONNECTED', updatedAt = ? WHERE id = ?",[P,Y]),await H.execute("UPDATE integration SET status = 'ACTIVE', updatedAt = ? WHERE id = ?",[P,Q.integrationId]);let B=(await H.query("SELECT * FROM integration_connection WHERE id = ?",[Y])).rows;return QH(B[0])}async function q(Q){let Y=new Date().toISOString();await H.execute("UPDATE integration_connection SET status = 'DISCONNECTED', updatedAt = ? WHERE id = ?",[Y,Q]);let P=(await H.query("SELECT * FROM integration_connection WHERE id = ?",[Q])).rows;return QH(P[0])}async function G(Q){let{connectionId:Y,status:P,limit:B=20,offset:_=0}=Q,z="WHERE 1=1",M=[];if(Y)z+=" AND connectionId = ?",M.push(Y);if(P&&P!=="all")z+=" AND status = ?",M.push(P);let f=(await H.query(`SELECT COUNT(*) as count FROM integration_sync_config ${z}`,M)).rows[0]?.count??0;return{configs:(await H.query(`SELECT * FROM integration_sync_config ${z} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...M,B,_])).rows.map(qH),total:f}}async function W(Q){let Y=p("sync"),P=new Date().toISOString();await H.execute(`INSERT INTO integration_sync_config (id, connectionId, name, sourceEntity, targetEntity, frequency, status, recordsSynced, createdAt, updatedAt)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Y,Q.connectionId,Q.name,Q.sourceEntity,Q.targetEntity,Q.frequency??"DAILY","ACTIVE",0,P,P]);let B=(await H.query("SELECT * FROM integration_sync_config WHERE id = ?",[Y])).rows;return qH(B[0])}async function A(Q){let Y=new Date().toISOString(),P=[];await H.execute("DELETE FROM integration_field_mapping WHERE syncConfigId = ?",[Q.syncConfigId]);for(let B of Q.mappings){let _=p("fmap");await H.execute(`INSERT INTO integration_field_mapping (id, syncConfigId, sourceField, targetField, transformType, transformConfig, createdAt)
5
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,[_,Q.syncConfigId,B.sourceField,B.targetField,B.transformType??null,B.transformConfig?JSON.stringify(B.transformConfig):null,Y]);let z=(await H.query("SELECT * FROM integration_field_mapping WHERE id = ?",[_])).rows;P.push(xH(z[0]))}return P}async function O(Q){return(await H.query("SELECT * FROM integration_field_mapping WHERE syncConfigId = ?",[Q])).rows.map(xH)}async function U(Q){let Y=new Date().toISOString(),P=Math.floor(Math.random()*1000)+50;await H.execute("UPDATE integration_sync_config SET lastRunAt = ?, lastRunStatus = 'SUCCESS', recordsSynced = recordsSynced + ?, updatedAt = ? WHERE id = ?",[Y,P,Y,Q]);let B=(await H.query("SELECT * FROM integration_sync_config WHERE id = ?",[Q])).rows;if(B[0])await H.execute("UPDATE integration_connection SET lastSyncAt = ?, updatedAt = ? WHERE id = ?",[Y,Y,B[0].connectionId]);let _=(await H.query("SELECT * FROM integration_sync_config WHERE id = ?",[Q])).rows;return qH(_[0])}async function D(Q){let Y=(await H.query("SELECT * FROM integration_connection WHERE id = ?",[Q.connectionId])).rows;if(!Y[0])return{valid:!1,provider:"unknown",keyPrefix:"",error:`Connection ${Q.connectionId} not found`};let P=Q.providerKey.slice(0,8),B=Q.providerKey.length>=16;return{valid:B,provider:Y[0].name,keyPrefix:`${P}...`,expiresAt:B?new Date(Date.now()+7776000000).toISOString():void 0,error:B?void 0:"Key must be at least 16 characters"}}async function F(Q){let Y=new Date().toISOString();return await H.execute("UPDATE integration_connection SET updatedAt = ? WHERE id = ?",[Y,Q.connectionId]),{refreshed:!0,expiresAt:new Date(Date.now()+3600000).toISOString(),tokenType:"Bearer",scopes:["read","write","sync"]}}async function V(Q){return{integrationId:Q.integrationId,transports:[{transport:"rest",supported:!0,defaultVersion:"v2"},{transport:"mcp",supported:!0,defaultVersion:"v1"},{transport:"webhook",supported:!0},{transport:"sdk",supported:!1}]}}return{listIntegrations:Z,createIntegration:K,listConnections:X,connectService:$,disconnectService:q,listSyncConfigs:G,configureSync:W,mapFields:A,getFieldMappings:O,runSync:U,validateByokKey:D,refreshOAuth2Token:F,getTransportOptions:V}}import{defineEnum as XK}from"@contractspec/lib.schema";var UH=XK("IntegrationStatus",["DRAFT","ACTIVE","PAUSED","ERROR","ARCHIVED"]);import{defineSchemaModel as EH,ScalarTypeEnum as R}from"@contractspec/lib.schema";var u=EH({name:"IntegrationModel",fields:{id:{type:R.String_unsecure(),isOptional:!1},name:{type:R.String_unsecure(),isOptional:!1},slug:{type:R.String_unsecure(),isOptional:!1},description:{type:R.String_unsecure(),isOptional:!0},provider:{type:R.String_unsecure(),isOptional:!1},status:{type:UH,isOptional:!1},createdAt:{type:R.DateTime(),isOptional:!1}}}),JH=EH({name:"CreateIntegrationInput",fields:{name:{type:R.NonEmptyString(),isOptional:!1},slug:{type:R.NonEmptyString(),isOptional:!1},description:{type:R.String_unsecure(),isOptional:!0},provider:{type:R.NonEmptyString(),isOptional:!1},config:{type:R.JSON(),isOptional:!0},featureFlagKey:{type:R.String_unsecure(),isOptional:!0}}});import{defineCommand as ZK}from"@contractspec/lib.contracts-spec/operations";var $K=ZK({meta:{key:"integration.create",version:"1.0.0",stability:"stable",owners:["@example.integration-hub"],tags:["integration","create"],description:"Create a new integration.",goal:"Allow users to set up integrations with external systems.",context:"Integration setup."},io:{input:JH,output:u},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.created",version:"1.0.0",when:"Integration created",payload:u}],audit:["integration.created"]},acceptance:{scenarios:[{key:"create-integration-happy-path",given:["User is admin"],when:["User defines new integration type"],then:["Integration definition is created","IntegrationCreated event is emitted"]}],examples:[{key:"create-slack",input:{name:"Slack",category:"communication",authType:"oauth2"},output:{id:"slack",status:"active"}}]}});import{createMcpToolsets as QK}from"@contractspec/lib.ai-agent/tools/mcp-client";import{randomUUID as qK}from"crypto";var UK=["-y","@modelcontextprotocol/server-filesystem","."];async function MX(){let H=YK(),Z=vH(),K=JK(),X=await QK([K],{onNameCollision:"error"});try{let $=Object.keys(X.tools).sort(),q={mode:H,server:{name:K.name,transport:Z},authMethod:process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_AUTH_METHOD,apiVersion:process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_API_VERSION,tools:$};if(H==="call"){let G=wH("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_NAME"),W=GK("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_ARGS_JSON",{}),A=X.tools[G];if(!A?.execute)throw Error(`Tool "${G}" was not found. Available tools: ${$.join(", ")}`);let O=await A.execute(W,{toolCallId:`integration-hub-${qK()}`,messages:[]});q.toolCall={name:G,args:W,output:O}}return q}finally{await X.cleanup().catch(()=>{return})}}function JK(){let H=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_NAME??"filesystem",Z=vH(),K=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_PREFIX;if(Z==="stdio")return{name:H,transport:Z,command:process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_COMMAND??"npx",args:DK("CONTRACTSPEC_INTEGRATION_HUB_MCP_ARGS_JSON",UK),toolPrefix:K};let X=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN,$=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN_ENV;return{name:H,transport:Z==="webhook"||Z==="http"?"http":"sse",url:wH("CONTRACTSPEC_INTEGRATION_HUB_MCP_URL"),headers:PK("CONTRACTSPEC_INTEGRATION_HUB_MCP_HEADERS_JSON"),accessToken:X,accessTokenEnvVar:$,toolPrefix:K}}function YK(){let H=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE?.toLowerCase()??"list";if(H==="list"||H==="call")return H;throw Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE: ${H}. Use "list" or "call".`)}function vH(){let H=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT?.toLowerCase()??"stdio";if(H==="stdio"||H==="http"||H==="sse"||H==="webhook")return H;throw Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT: ${H}. Use "stdio", "http", "sse", or "webhook".`)}function DK(H,Z){if(!process.env[H])return Z;let X=TH(H);if(!Array.isArray(X)||X.some(($)=>typeof $!=="string"))throw Error(`${H} must be a JSON string array.`);return X}function bH(H){if(!process.env[H])return;let K=TH(H);if(!WK(K))throw Error(`${H} must be a JSON object.`);return K}function GK(H,Z){return bH(H)??Z}function PK(H){let Z=bH(H);if(!Z)return;let K=Object.entries(Z);if(K.find(([,$])=>typeof $!=="string"))throw Error(`${H} must contain only string values.`);return Object.fromEntries(K)}function TH(H){let Z=process.env[H];if(!Z)return;try{return JSON.parse(Z)}catch{throw Error(`${H} contains invalid JSON.`)}}function wH(H){let Z=process.env[H];if(!Z)throw Error(`Missing required env var: ${H}`);return Z}function WK(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}import{defineEnum as YH}from"@contractspec/lib.schema";var x=YH("SyncDirection",["INBOUND","OUTBOUND","BIDIRECTIONAL"]),l=YH("SyncStatus",["PENDING","RUNNING","COMPLETED","FAILED","CANCELLED"]),c=YH("MappingType",["DIRECT","TRANSFORM","LOOKUP","CONSTANT","COMPUTED"]);import{defineSchemaModel as C,ScalarTypeEnum as J}from"@contractspec/lib.schema";var b=C({name:"FieldMappingModel",fields:{id:{type:J.String_unsecure(),isOptional:!1},sourceField:{type:J.String_unsecure(),isOptional:!1},targetField:{type:J.String_unsecure(),isOptional:!1},mappingType:{type:c,isOptional:!1},transformExpression:{type:J.String_unsecure(),isOptional:!0},isRequired:{type:J.Boolean(),isOptional:!1}}}),r=C({name:"SyncConfigModel",fields:{id:{type:J.String_unsecure(),isOptional:!1},integrationId:{type:J.String_unsecure(),isOptional:!1},connectionId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.String_unsecure(),isOptional:!1},direction:{type:x,isOptional:!1},sourceObject:{type:J.String_unsecure(),isOptional:!1},targetObject:{type:J.String_unsecure(),isOptional:!1},scheduleEnabled:{type:J.Boolean(),isOptional:!1},scheduleCron:{type:J.String_unsecure(),isOptional:!0},isActive:{type:J.Boolean(),isOptional:!1},lastSyncAt:{type:J.DateTime(),isOptional:!0},fieldMappings:{type:b,isArray:!0,isOptional:!0}}}),T=C({name:"SyncRunModel",fields:{id:{type:J.String_unsecure(),isOptional:!1},syncConfigId:{type:J.String_unsecure(),isOptional:!1},status:{type:l,isOptional:!1},direction:{type:x,isOptional:!1},trigger:{type:J.String_unsecure(),isOptional:!1},recordsProcessed:{type:J.Int_unsecure(),isOptional:!1},recordsCreated:{type:J.Int_unsecure(),isOptional:!1},recordsUpdated:{type:J.Int_unsecure(),isOptional:!1},recordsFailed:{type:J.Int_unsecure(),isOptional:!1},errorMessage:{type:J.String_unsecure(),isOptional:!0},startedAt:{type:J.DateTime(),isOptional:!0},completedAt:{type:J.DateTime(),isOptional:!0},createdAt:{type:J.DateTime(),isOptional:!1}}}),DH=C({name:"CreateSyncConfigInput",fields:{integrationId:{type:J.String_unsecure(),isOptional:!1},connectionId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.NonEmptyString(),isOptional:!1},direction:{type:x,isOptional:!1},sourceObject:{type:J.NonEmptyString(),isOptional:!1},targetObject:{type:J.NonEmptyString(),isOptional:!1},scheduleEnabled:{type:J.Boolean(),isOptional:!0},scheduleCron:{type:J.String_unsecure(),isOptional:!0}}}),GH=C({name:"AddFieldMappingInput",fields:{syncConfigId:{type:J.String_unsecure(),isOptional:!1},sourceField:{type:J.NonEmptyString(),isOptional:!1},targetField:{type:J.NonEmptyString(),isOptional:!1},mappingType:{type:c,isOptional:!1},transformExpression:{type:J.String_unsecure(),isOptional:!0},lookupConfig:{type:J.JSON(),isOptional:!0},constantValue:{type:J.JSON(),isOptional:!0},isRequired:{type:J.Boolean(),isOptional:!0},defaultValue:{type:J.JSON(),isOptional:!0}}}),PH=C({name:"TriggerSyncInput",fields:{syncConfigId:{type:J.String_unsecure(),isOptional:!1},direction:{type:x,isOptional:!0},fullSync:{type:J.Boolean(),isOptional:!0}}}),WH=C({name:"ListSyncRunsInput",fields:{syncConfigId:{type:J.String_unsecure(),isOptional:!1},status:{type:l,isOptional:!0},limit:{type:J.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:J.Int_unsecure(),isOptional:!0,defaultValue:0}}}),BH=C({name:"ListSyncRunsOutput",fields:{runs:{type:T,isArray:!0,isOptional:!1},total:{type:J.Int_unsecure(),isOptional:!1}}});import{defineCommand as OH,defineQuery as BK}from"@contractspec/lib.contracts-spec/operations";var i=["@example.integration-hub"],OK=OH({meta:{key:"integration.syncConfig.create",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","sync","config","create"],description:"Create a sync configuration.",goal:"Define how data should be synchronized.",context:"Sync setup."},io:{input:DH,output:r},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.syncConfig.created",version:"1.0.0",when:"Sync config created",payload:r}],audit:["integration.syncConfig.created"]},acceptance:{scenarios:[{key:"create-sync-happy-path",given:["User is authenticated"],when:["User creates sync config"],then:["Sync config is created","SyncConfigCreated event is emitted"]}],examples:[{key:"create-contact-sync",input:{name:"Contacts Sync",sourceConnectionId:"conn-1",targetConnectionId:"conn-2"},output:{id:"sync-123",status:"active"}}]}}),LK=OH({meta:{key:"integration.fieldMapping.add",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","mapping","field"],description:"Add a field mapping to a sync config.",goal:"Map fields between systems.",context:"Mapping configuration."},io:{input:GH,output:b},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.fieldMapping.added",version:"1.0.0",when:"Mapping added",payload:b}]},acceptance:{scenarios:[{key:"add-mapping-happy-path",given:["Sync config exists"],when:["User adds field mapping"],then:["Mapping is added","FieldMappingAdded event is emitted"]}],examples:[{key:"map-email",input:{syncConfigId:"sync-123",sourceField:"email",targetField:"user_email"},output:{id:"map-456",type:"string"}}]}}),NK=OH({meta:{key:"integration.sync.trigger",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","sync","trigger"],description:"Trigger a manual sync.",goal:"Start data synchronization.",context:"Manual sync or webhook trigger."},io:{input:PH,output:T},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.sync.started",version:"1.0.0",when:"Sync starts",payload:T}],audit:["integration.sync.triggered"]},acceptance:{scenarios:[{key:"trigger-sync-happy-path",given:["Sync config exists"],when:["User triggers sync"],then:["Sync run starts","SyncStarted event is emitted"]}],examples:[{key:"manual-trigger",input:{syncConfigId:"sync-123"},output:{id:"run-789",status:"pending"}}]}}),AK=BK({meta:{key:"integration.syncRun.list",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","sync","run","list"],description:"List sync run history.",goal:"View sync history and status.",context:"Sync monitoring."},io:{input:WH,output:BH},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-runs-happy-path",given:["User has access to syncs"],when:["User lists sync runs"],then:["List of runs is returned"]}],examples:[{key:"list-recent",input:{limit:10},output:{items:[],total:50}}]}});class SH{transform(H,Z){try{if(Z.startsWith("uppercase"))return typeof H==="string"?H.toUpperCase():H;if(Z.startsWith("lowercase"))return typeof H==="string"?H.toLowerCase():H;if(Z.startsWith("trim"))return typeof H==="string"?H.trim():H;if(Z.startsWith("default:")){let K=Z.replace("default:","");return H??JSON.parse(K)}if(Z.startsWith("concat:")){let K=Z.replace("concat:","")||" ";if(Array.isArray(H))return H.join(K);return H}if(Z.startsWith("split:")){let K=Z.replace("split:","")||",";if(typeof H==="string")return H.split(K);return H}if(Z.startsWith("number"))return Number(H);if(Z.startsWith("boolean"))return Boolean(H);if(Z.startsWith("string"))return String(H);return H}catch{return H}}}class gH{transformer;constructor(H){this.transformer=H??new SH}async sync(H){return{success:!0,recordsProcessed:0,recordsCreated:0,recordsUpdated:0,recordsDeleted:0,recordsFailed:0,recordsSkipped:0,errors:[]}}transformRecord(H,Z,K){let X={};for(let $ of Z){let q,G;switch($.mappingType){case"DIRECT":q=this.getNestedValue(H.data,$.sourceField);break;case"TRANSFORM":G=this.getNestedValue(H.data,$.sourceField),q=$.transformExpression?this.transformer.transform(G,$.transformExpression):G;break;case"CONSTANT":q=$.constantValue;break;case"LOOKUP":q=this.getNestedValue(H.data,$.sourceField);break;case"COMPUTED":q=$.transformExpression?this.evaluateComputed(H.data,$.transformExpression):null;break;default:q=this.getNestedValue(H.data,$.sourceField)}if(q===void 0||q===null)q=$.defaultValue;this.setNestedValue(X,$.targetField,q)}return{id:H.id,data:X}}validateRecord(H,Z){let K=[];for(let X of Z)if(X.isRequired){let $=this.getNestedValue(H.data,X.targetField);if($===void 0||$===null)K.push({recordId:H.id,field:X.targetField,message:`Required field ${X.targetField} is missing`,code:"REQUIRED_FIELD_MISSING"})}return{valid:K.length===0,errors:K}}getNestedValue(H,Z){let K=Z.split("."),X=H;for(let $ of K){if(X===null||X===void 0)return;X=X[$]}return X}setNestedValue(H,Z,K){let X=Z.split("."),$=H;for(let G=0;G<X.length-1;G++){let W=X[G];if(W===void 0)continue;if(!(W in $))$[W]={};$=$[W]}let q=X[X.length-1];if(q!==void 0)$[q]=K}evaluateComputed(H,Z){try{return Z.replace(/\$\{([^}]+)\}/g,(X,$)=>{let q=this.getNestedValue(H,$);return String(q??"")})}catch{return null}}}function gX(H){return new gH(H)}function yX(H){let Z=JSON.stringify(H,Object.keys(H).sort()),K=0;for(let X=0;X<Z.length;X++){let $=Z.charCodeAt(X);K=(K<<5)-K+$,K=K&K}return K.toString(16)}function dX(H,Z){if(!H||!Z)return!0;return H!==Z}import{useTemplateRuntime as FK}from"@contractspec/lib.example-shared-ui";import{useCallback as _K,useEffect as zK,useState as w}from"react";function LH(H="local-project"){let{handlers:Z}=FK(),K=Z.integration,[X,$]=w([]),[q,G]=w([]),[W,A]=w([]),[O,U]=w(!0),[D,F]=w(null),V=_K(async()=>{try{U(!0),F(null);let[Y,P,B]=await Promise.all([K.listIntegrations({projectId:H,limit:100}),K.listConnections({limit:100}),K.listSyncConfigs({limit:100})]);$(Y.integrations),G(P.connections),A(B.configs)}catch(Y){F(Y instanceof Error?Y:Error("Failed to load integrations"))}finally{U(!1)}},[K,H]);zK(()=>{V()},[V]);let Q={totalIntegrations:X.length,activeIntegrations:X.filter((Y)=>Y.status==="ACTIVE").length,totalConnections:q.length,connectedCount:q.filter((Y)=>Y.status==="CONNECTED").length,totalSyncs:W.length,activeSyncs:W.filter((Y)=>Y.status==="ACTIVE").length};return{integrations:X,connections:q,syncConfigs:W,loading:O,error:D,stats:Q,refetch:V}}import{defineVisualization as o,VisualizationRegistry as RK}from"@contractspec/lib.contracts-spec/visualizations";var VK={key:"integration.list",version:"1.0.0"},MK={key:"integration.connection.list",version:"1.0.0"},yH={key:"integration.syncConfig.list",version:"1.0.0"},t={version:"1.0.0",domain:"integration",stability:"experimental",owners:["@example.integration-hub"],tags:["integration","visualization","sync"]},NH=o({meta:{...t,key:"integration-hub.visualization.integration-types",title:"Integration Types",description:"Distribution of configured integration categories.",goal:"Show where integration coverage is concentrated.",context:"Integration overview."},source:{primary:VK,resultPath:"data"},visualization:{kind:"pie",nameDimension:"type",valueMeasure:"count",dimensions:[{key:"type",label:"Type",dataPath:"type",type:"category"}],measures:[{key:"count",label:"Count",dataPath:"count",format:"number"}],table:{caption:"Integration counts by type."}}}),AH=o({meta:{...t,key:"integration-hub.visualization.connection-status",title:"Connection Status",description:"Status distribution across configured connections.",goal:"Highlight connection health and instability.",context:"Connection monitoring."},source:{primary:MK,resultPath:"data"},visualization:{kind:"cartesian",variant:"bar",xDimension:"status",yMeasures:["count"],dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"count",label:"Connections",dataPath:"count",format:"number",color:"#1d4ed8"}],table:{caption:"Connection counts by status."}}}),FH=o({meta:{...t,key:"integration-hub.visualization.sync-healthy",title:"Healthy Syncs",description:"Sync configurations currently healthy or recently successful.",goal:"Summarize healthy synchronization capacity.",context:"Sync-state comparison."},source:{primary:yH,resultPath:"data"},visualization:{kind:"metric",measure:"value",measures:[{key:"value",label:"Syncs",dataPath:"value",format:"number"}],table:{caption:"Healthy sync count."}}}),_H=o({meta:{...t,key:"integration-hub.visualization.sync-attention",title:"Attention Needed",description:"Sync configurations paused, failing, or otherwise needing review.",goal:"Summarize syncs needing action.",context:"Sync-state comparison."},source:{primary:yH,resultPath:"data"},visualization:{kind:"metric",measure:"value",measures:[{key:"value",label:"Syncs",dataPath:"value",format:"number"}],table:{caption:"Syncs requiring attention."}}}),dH=[NH,AH,FH,_H],oX=new RK([...dH]),tX=dH.map((H)=>({key:H.meta.key,version:H.meta.version}));function IK(H){return H==="ACTIVE"||H==="SUCCESS"}function s(H,Z,K){let X=new Map,$=new Map,q=0,G=0;for(let O of H)X.set(O.type,(X.get(O.type)??0)+1);for(let O of Z)$.set(O.status,($.get(O.status)??0)+1);for(let O of K)if(IK(O.status))q+=1;else G+=1;return{primaryItems:[{key:"integration-types",spec:NH,data:{data:Array.from(X.entries()).map(([O,U])=>({type:O,count:U}))},title:"Integration Types",description:"Configured integrations grouped by category.",height:260},{key:"connection-status",spec:AH,data:{data:Array.from($.entries()).map(([O,U])=>({status:O,count:U}))},title:"Connection Status",description:"Operational health across current connections."}],comparisonItems:[{key:"healthy-syncs",spec:FH,data:{data:[{value:q}]},title:"Healthy Syncs",description:"Active or recently successful sync configurations.",height:200},{key:"attention-syncs",spec:_H,data:{data:[{value:G}]},title:"Attention Needed",description:"Paused, failed, or degraded sync configurations.",height:200}]}}import{ComparisonView as kK,VisualizationCard as fK,VisualizationGrid as CK}from"@contractspec/lib.design-system";import{jsx as S,jsxs as mH}from"react/jsx-runtime";function pH({integrations:H,connections:Z,syncConfigs:K}){let{primaryItems:X,comparisonItems:$}=s(H,Z,K);return mH("section",{className:"space-y-4",children:[mH("div",{children:[S("h3",{className:"font-semibold text-lg",children:"Integration Visualizations"}),S("p",{className:"text-muted-foreground text-sm",children:"Contract-backed charts for integration coverage and sync health."})]}),S(CK,{children:X.map((q)=>S(fK,{data:q.data,description:q.description,height:q.height,spec:q.spec,title:q.title},q.key))}),S(kK,{description:"Comparison surface for healthy versus attention-needed syncs.",items:$,title:"Sync-State Comparison"})]})}import{ChatWithSidebar as jK}from"@contractspec/module.ai-chat";import{jsx as uH}from"react/jsx-runtime";var hK=["List my integrations","Show sync status","Add a connection"],xK="You are an Integration Hub assistant. Help users manage integrations, connections, and sync configurations. When asked about integrations, connections, or syncs, provide clear, actionable guidance.";function zH({proxyUrl:H="/api/chat",mcpServers:Z,thinkingLevel:K="thinking",suggestions:X=hK,systemPrompt:$=xK,className:q}){return uH("div",{className:q??"flex h-[500px] flex-col",children:uH(jK,{className:"flex-1",systemPrompt:$,proxyUrl:H,mcpServers:Z,thinkingLevel:K,suggestions:X,showSuggestionsWhenEmpty:!0})})}import{Button as a}from"@contractspec/lib.design-system";import{Badge as lH}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as EK}from"@contractspec/lib.ui-kit-web/ui/stack";import{jsx as E,jsxs as bK}from"react/jsx-runtime";var vK={ACTIVE:"default",CONNECTED:"default",SUCCESS:"default",PENDING:"secondary",PAUSED:"secondary",ERROR:"destructive",DISCONNECTED:"outline"};function g(H){return H?H.toLocaleString():"Never"}function RH(H){return H?JSON.stringify(H,null,2):"No configuration"}function n({status:H}){return E(lH,{variant:vK[H]??"outline",children:H})}function e({controller:H,label:Z,toggleColumnId:K,toggleVisibleLabel:X,toggleHiddenLabel:$,pinColumnId:q,pinLabel:G,resizeColumnId:W,resizeLabel:A}){let O=H.rows[0],U=H.columns.find((Q)=>Q.id===K),D=H.columns.find((Q)=>Q.id===q),F=H.columns.find((Q)=>Q.id===W),V=D?.pinState==="left"?!1:"left";return bK(EK,{gap:"sm",className:"flex-wrap",children:[E(lH,{variant:"outline",children:Z}),E(a,{variant:"outline",size:"sm",onPress:()=>O?.toggleExpanded?.(!O?.isExpanded),children:"Expand First Row"}),E(a,{variant:"outline",size:"sm",onPress:()=>U?.toggleVisibility?.(!U?.visible),children:U?.visible?X:$}),E(a,{variant:"outline",size:"sm",onPress:()=>D?.pin?.(V),children:D?.pinState==="left"?`Unpin ${G}`:`Pin ${G}`}),E(a,{variant:"outline",size:"sm",onPress:()=>F?.resizeBy?.(40),children:A})]})}import{DataTable as TK}from"@contractspec/lib.design-system";import{useContractTable as wK}from"@contractspec/lib.presentation-runtime-react";import{VStack as cH}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as y}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as k,jsxs as VH}from"react/jsx-runtime";function MH({connections:H}){let Z=wK({data:H,columns:[{id:"connection",header:"Connection",label:"Connection",accessor:(K)=>K.name,cell:({item:K})=>VH(cH,{gap:"xs",children:[k(y,{className:"font-medium text-sm",children:K.name}),VH(y,{className:"text-muted-foreground text-xs",children:["Created ",K.createdAt.toLocaleDateString()]})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:K})=>k(n,{status:String(K)}),size:150,canSort:!0,canPin:!0,canResize:!0},{id:"lastSyncAt",header:"Last Sync",label:"Last Sync",accessor:(K)=>K.lastSyncAt?.getTime()??0,cell:({item:K})=>g(K.lastSyncAt),size:200,canSort:!0,canHide:!0,canResize:!0},{id:"errorMessage",header:"Errors",label:"Errors",accessor:(K)=>K.errorMessage??"",cell:({value:K})=>String(K||"No errors"),size:240,canHide:!0,canResize:!0}],initialState:{pagination:{pageIndex:0,pageSize:3},columnVisibility:{errorMessage:!1},columnPinning:{left:["connection"],right:[]}},renderExpandedContent:(K)=>VH(cH,{gap:"sm",className:"py-2",children:[k(y,{className:"font-medium text-sm",children:"Credentials"}),k("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:RH(K.credentials)}),k(y,{className:"font-medium text-sm",children:"Config"}),k("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:RH(K.config)}),k(y,{className:"text-muted-foreground text-sm",children:K.errorMessage??"No sync errors recorded."})]}),getCanExpand:()=>!0});return k(TK,{controller:Z,title:"Connections",description:"Client-mode ContractSpec table with visibility, pinning, resizing, and expanded diagnostics.",toolbar:k(e,{controller:Z,label:`${H.length} total connections`,toggleColumnId:"errorMessage",toggleVisibleLabel:"Hide Error Column",toggleHiddenLabel:"Show Error Column",pinColumnId:"status",pinLabel:"Status",resizeColumnId:"connection",resizeLabel:"Widen Connection"}),emptyState:k("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No connections found"})})}import{DataTable as SK}from"@contractspec/lib.design-system";import{useContractTable as gK}from"@contractspec/lib.presentation-runtime-react";import{VStack as rH}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as v}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as d,jsxs as h}from"react/jsx-runtime";function IH({syncConfigs:H}){let Z=gK({data:H,columns:[{id:"sync",header:"Sync Config",label:"Sync Config",accessor:(K)=>K.name,cell:({item:K})=>h(rH,{gap:"xs",children:[d(v,{className:"font-medium text-sm",children:K.name}),h(v,{className:"text-muted-foreground text-xs",children:[K.sourceEntity," → ",K.targetEntity]})]}),size:260,minSize:200,canSort:!0,canPin:!0,canResize:!0},{id:"frequency",header:"Frequency",label:"Frequency",accessorKey:"frequency",size:160,canSort:!0,canHide:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:K})=>d(n,{status:String(K)}),size:150,canSort:!0,canPin:!0,canResize:!0},{id:"recordsSynced",header:"Records",label:"Records",accessorKey:"recordsSynced",align:"right",size:140,canSort:!0,canResize:!0},{id:"lastRunAt",header:"Last Run",label:"Last Run",accessor:(K)=>K.lastRunAt?.getTime()??0,cell:({item:K})=>g(K.lastRunAt),size:200,canSort:!0,canHide:!0,canResize:!0}],initialState:{pagination:{pageIndex:0,pageSize:3},columnVisibility:{lastRunAt:!1},columnPinning:{left:["sync"],right:[]}},renderExpandedContent:(K)=>h(rH,{gap:"sm",className:"py-2",children:[h(v,{className:"text-muted-foreground text-sm",children:["Connection ",K.connectionId]}),h(v,{className:"text-muted-foreground text-sm",children:["Last run: ",g(K.lastRunAt)]}),h(v,{className:"text-muted-foreground text-sm",children:["Last status: ",K.lastRunStatus??"No runs recorded"]}),h(v,{className:"text-muted-foreground text-sm",children:["Updated ",K.updatedAt.toLocaleString()]})]}),getCanExpand:()=>!0});return d(SK,{controller:Z,title:"Sync Configs",description:"Shared table primitives applied to sync monitoring without changing the surrounding dashboard layout.",toolbar:d(e,{controller:Z,label:`${H.length} syncs`,toggleColumnId:"lastRunAt",toggleVisibleLabel:"Hide Last Run",toggleHiddenLabel:"Show Last Run",pinColumnId:"status",pinLabel:"Status",resizeColumnId:"sync",resizeLabel:"Widen Sync"}),emptyState:d("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No sync configurations found"})})}import{Button as iH,ErrorState as yK,LoaderBlock as dK,StatCard as kH,StatCardGroup as mK}from"@contractspec/lib.design-system";import{useState as pK}from"react";import{jsx as L,jsxs as I}from"react/jsx-runtime";var uK={ACTIVE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",INACTIVE:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",CONNECTED:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DISCONNECTED:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",PENDING:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",ERROR:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",PAUSED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"},lK={CRM:"\uD83D\uDCCA",MARKETING:"\uD83D\uDCE3",PAYMENT:"\uD83D\uDCB3",COMMUNICATION:"\uD83D\uDCAC",DATA:"\uD83D\uDDC4️",CUSTOM:"⚙️"};function cK(){let[H,Z]=pK("integrations"),{integrations:K,connections:X,syncConfigs:$,loading:q,error:G,stats:W,refetch:A}=LH(),O=[{id:"integrations",label:"Integrations",icon:"\uD83D\uDD0C"},{id:"connections",label:"Connections",icon:"\uD83D\uDD17"},{id:"syncs",label:"Sync Configs",icon:"\uD83D\uDD04"},{id:"chat",label:"Chat",icon:"\uD83D\uDCAC"}];if(q)return L(dK,{label:"Loading Integrations..."});if(G)return L(yK,{title:"Failed to load Integrations",description:G.message,onRetry:A,retryLabel:"Retry"});return I("div",{className:"space-y-6",children:[I("div",{className:"flex items-center justify-between",children:[L("h2",{className:"font-bold text-2xl",children:"Integration Hub"}),I(iH,{onClick:()=>alert("Add integration modal"),children:[L("span",{className:"mr-2",children:"+"})," Add Integration"]})]}),I(mK,{children:[L(kH,{label:"Integrations",value:W.totalIntegrations,hint:`${W.activeIntegrations} active`}),L(kH,{label:"Connections",value:W.totalConnections,hint:`${W.connectedCount} connected`}),L(kH,{label:"Syncs",value:W.totalSyncs,hint:`${W.activeSyncs} active`})]}),L(pH,{connections:X,integrations:K,syncConfigs:$}),L("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:O.map((U)=>I(iH,{type:"button",role:"tab","aria-selected":H===U.id,onClick:()=>Z(U.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${H===U.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[L("span",{children:U.icon}),U.label]},U.id))}),I("div",{className:"min-h-[400px]",role:"tabpanel",children:[H==="integrations"&&I("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[K.map((U)=>I("div",{className:"cursor-pointer rounded-lg border border-border bg-card p-4 transition-colors hover:bg-muted/50",children:[I("div",{className:"mb-3 flex items-center gap-3",children:[L("span",{className:"text-2xl",children:lK[U.type]??"⚙️"}),I("div",{children:[L("h3",{className:"font-medium",children:U.name}),L("p",{className:"text-muted-foreground text-sm",children:U.type})]})]}),I("div",{className:"flex items-center justify-between",children:[L("span",{className:`inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${uK[U.status]??""}`,children:U.status}),L("span",{className:"text-muted-foreground text-xs",children:U.createdAt.toLocaleDateString()})]})]},U.id)),K.length===0&&L("div",{className:"col-span-full flex h-64 items-center justify-center text-muted-foreground",children:"No integrations configured"})]}),H==="connections"&&L(MH,{connections:X}),H==="chat"&&L(zH,{proxyUrl:"/api/chat",thinkingLevel:"thinking",suggestions:["List my integrations","Show sync status","Add a connection"],className:"min-h-[400px]"}),H==="syncs"&&L(IH,{syncConfigs:$})]})]})}var oH=[{id:"int-1",name:"Salesforce",type:"CRM",status:"ACTIVE",connectionCount:3},{id:"int-2",name:"HubSpot",type:"MARKETING",status:"ACTIVE",connectionCount:2},{id:"int-3",name:"Stripe",type:"PAYMENT",status:"ACTIVE",connectionCount:1},{id:"int-4",name:"Slack",type:"COMMUNICATION",status:"INACTIVE",connectionCount:0},{id:"int-5",name:"Google Sheets",type:"DATA",status:"ACTIVE",connectionCount:5},{id:"int-6",name:"PostHog",type:"ANALYTICS",status:"ACTIVE",connectionCount:1}],fH=[{id:"conn-1",integrationId:"int-1",name:"Production Salesforce",status:"CONNECTED",lastSyncAt:"2024-01-16T10:00:00Z"},{id:"conn-2",integrationId:"int-1",name:"Sandbox Salesforce",status:"CONNECTED",lastSyncAt:"2024-01-15T14:00:00Z"},{id:"conn-3",integrationId:"int-2",name:"Marketing HubSpot",status:"CONNECTED",lastSyncAt:"2024-01-16T08:00:00Z"},{id:"conn-4",integrationId:"int-3",name:"Stripe Live",status:"CONNECTED",lastSyncAt:"2024-01-16T12:00:00Z"},{id:"conn-5",integrationId:"int-5",name:"Analytics Sheet",status:"ERROR",lastSyncAt:"2024-01-14T09:00:00Z",error:"Authentication expired"},{id:"conn-6",integrationId:"int-6",name:"PostHog Workspace",status:"CONNECTED",lastSyncAt:"2024-01-16T11:45:00Z"}],tH=[{id:"sync-1",connectionId:"conn-1",name:"Contacts Sync",frequency:"HOURLY",lastRunAt:"2024-01-16T10:00:00Z",status:"SUCCESS",recordsSynced:1250},{id:"sync-2",connectionId:"conn-1",name:"Opportunities Sync",frequency:"DAILY",lastRunAt:"2024-01-16T00:00:00Z",status:"SUCCESS",recordsSynced:340},{id:"sync-3",connectionId:"conn-3",name:"Orders Sync",frequency:"REALTIME",lastRunAt:"2024-01-16T12:30:00Z",status:"SUCCESS",recordsSynced:89},{id:"sync-4",connectionId:"conn-5",name:"Metrics Export",frequency:"DAILY",lastRunAt:"2024-01-14T09:00:00Z",status:"FAILED",recordsSynced:0}],rK={target:"markdown",render:async(H)=>{if(H.source.type!=="component"||H.source.componentKey!=="IntegrationDashboard")throw Error("integrationDashboardMarkdownRenderer: not IntegrationDashboard");let Z=oH,K=fH,X=tH,$=s(Z,K,X),q=Z.filter((D)=>D.status==="ACTIVE"),G=K.filter((D)=>D.status==="CONNECTED"),W=K.filter((D)=>D.status==="ERROR"),O=X.filter((D)=>D.status==="SUCCESS").reduce((D,F)=>D+F.recordsSynced,0),U=["# Integration Hub","","> Connect and sync data with external services","","## Overview","","| Metric | Value |","|--------|-------|",`| Active Integrations | ${q.length} |`,`| Connected Services | ${G.length} |`,`| Error Connections | ${W.length} |`,`| Sync Configs | ${X.length} |`,`| Records Synced (24h) | ${O.toLocaleString()} |`,""];U.push("## Visualization Overview"),U.push("");for(let D of[...$.primaryItems,...$.comparisonItems])U.push(`- **${D.title}** via \`${D.spec.meta.key}\``);U.push(""),U.push("## Integrations"),U.push(""),U.push("| Name | Type | Connections | Status |"),U.push("|------|------|-------------|--------|");for(let D of Z){let F=D.status==="ACTIVE"?"\uD83D\uDFE2":"⚫";U.push(`| ${D.name} | ${D.type} | ${D.connectionCount} | ${F} ${D.status} |`)}U.push(""),U.push("## Recent Sync Activity"),U.push(""),U.push("| Sync | Frequency | Last Run | Records | Status |"),U.push("|------|-----------|----------|---------|--------|");for(let D of X){let F=new Date(D.lastRunAt).toLocaleString(),V=D.status==="SUCCESS"?"✅":"❌";U.push(`| ${D.name} | ${D.frequency} | ${F} | ${D.recordsSynced} | ${V} ${D.status} |`)}if(W.length>0){U.push(""),U.push("## ⚠️ Connections with Errors"),U.push("");for(let D of W){let F=Z.find((V)=>V.id===D.integrationId);U.push(`- **${D.name}** (${F?.name??"Unknown"}): ${D.error??"Unknown error"}`)}}return{mimeType:"text/markdown",body:U.join(`
6
+ `)}}},iK={target:"markdown",render:async(H)=>{if(H.source.type!=="component"||H.source.componentKey!=="ConnectionList")throw Error("connectionListMarkdownRenderer: not ConnectionList");let Z=fH,K=oH,X=["# Connections","","> Manage connections to external services",""];for(let $ of K){let q=Z.filter((G)=>G.integrationId===$.id);if(q.length===0)continue;X.push(`## ${$.name}`),X.push(""),X.push("| Connection | Status | Last Sync |"),X.push("|------------|--------|-----------|");for(let G of q){let W=new Date(G.lastSyncAt).toLocaleString(),A=G.status==="CONNECTED"?"\uD83D\uDFE2":G.status==="ERROR"?"\uD83D\uDD34":"⚫";X.push(`| ${G.name} | ${A} ${G.status} | ${W} |`)}X.push("")}return{mimeType:"text/markdown",body:X.join(`
7
+ `)}}},oK={target:"markdown",render:async(H)=>{if(H.source.type!=="component"||H.source.componentKey!=="SyncConfigEditor")throw Error("syncConfigMarkdownRenderer: not SyncConfigEditor");let Z=tH,K=fH,X=["# Sync Configurations","","> Configure automated data synchronization",""];for(let $ of Z){let q=K.find((W)=>W.id===$.connectionId),G=$.status==="SUCCESS"?"✅":"❌";X.push(`## ${$.name}`),X.push(""),X.push(`**Connection:** ${q?.name??"Unknown"}`),X.push(`**Frequency:** ${$.frequency}`),X.push(`**Status:** ${G} ${$.status}`),X.push(`**Last Run:** ${new Date($.lastRunAt).toLocaleString()}`),X.push(`**Records Synced:** ${$.recordsSynced.toLocaleString()}`),X.push("")}return X.push("## Frequency Options"),X.push(""),X.push("- **REALTIME**: Sync on every change"),X.push("- **HOURLY**: Sync every hour"),X.push("- **DAILY**: Sync once per day"),X.push("- **WEEKLY**: Sync once per week"),X.push("- **MANUAL**: Sync only when triggered"),{mimeType:"text/markdown",body:X.join(`
8
+ `)}}};export{LH as useIntegrationData,oK as syncConfigMarkdownRenderer,MX as runIntegrationHubMcpExampleFromEnv,rK as integrationDashboardMarkdownRenderer,dX as hasChanges,gX as createSyncEngine,s as createIntegrationVisualizationSections,KK as createIntegrationHandlers,iK as connectionListMarkdownRenderer,yX as computeChecksum,PH as TriggerSyncInputModel,NK as TriggerSyncContract,l as SyncStatusEnum,T as SyncRunModel,x as SyncDirectionEnum,r as SyncConfigModel,c as MappingTypeEnum,BH as ListSyncRunsOutputModel,WH as ListSyncRunsInputModel,AK as ListSyncRunsContract,dH as IntegrationVisualizationSpecs,oX as IntegrationVisualizationRegistry,tX as IntegrationVisualizationRefs,NH as IntegrationTypeVisualization,UH as IntegrationStatusEnum,u as IntegrationModel,zH as IntegrationHubChat,cK as IntegrationDashboard,FH as HealthySyncMetricVisualization,b as FieldMappingModel,DH as CreateSyncConfigInputModel,OK as CreateSyncConfigContract,JH as CreateIntegrationInputModel,$K as CreateIntegrationContract,$H as CreateConnectionInputModel,eH as CreateConnectionContract,AH as ConnectionStatusVisualization,KH as ConnectionStatusEnum,m as ConnectionModel,gH as BasicSyncEngine,SH as BasicFieldTransformer,_H as AttentionSyncMetricVisualization,GH as AddFieldMappingInputModel,LK as AddFieldMappingContract};