integrate-sdk 0.9.55 → 0.9.58

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 (63) hide show
  1. package/dist/adapters/index.js +2440 -31
  2. package/dist/adapters/solid-start.js +2440 -31
  3. package/dist/adapters/svelte-kit.js +2440 -31
  4. package/dist/ai/anthropic.d.ts.map +1 -1
  5. package/dist/ai/anthropic.js +11 -2
  6. package/dist/ai/google.d.ts.map +1 -1
  7. package/dist/ai/google.js +11 -2
  8. package/dist/ai/index.js +16 -7
  9. package/dist/ai/openai.d.ts.map +1 -1
  10. package/dist/ai/openai.js +11 -2
  11. package/dist/ai/utils.d.ts +21 -0
  12. package/dist/ai/utils.d.ts.map +1 -1
  13. package/dist/ai/utils.js +10 -0
  14. package/dist/ai/vercel-ai.d.ts.map +1 -1
  15. package/dist/ai/vercel-ai.js +10 -1
  16. package/dist/database/adapters/drizzle.d.ts +23 -0
  17. package/dist/database/adapters/drizzle.d.ts.map +1 -0
  18. package/dist/database/adapters/drizzle.js +646 -0
  19. package/dist/database/adapters/mongodb.d.ts +17 -0
  20. package/dist/database/adapters/mongodb.d.ts.map +1 -0
  21. package/dist/database/adapters/mongodb.js +643 -0
  22. package/dist/database/adapters/prisma.d.ts +18 -0
  23. package/dist/database/adapters/prisma.d.ts.map +1 -0
  24. package/dist/database/adapters/prisma.js +679 -0
  25. package/dist/database/index.d.ts +9 -0
  26. package/dist/database/index.d.ts.map +1 -0
  27. package/dist/database/index.js +1167 -0
  28. package/dist/index.js +77 -31
  29. package/dist/integrations.js +77 -31
  30. package/dist/server.js +3633 -42
  31. package/dist/src/ai/anthropic.d.ts.map +1 -1
  32. package/dist/src/ai/google.d.ts.map +1 -1
  33. package/dist/src/ai/openai.d.ts.map +1 -1
  34. package/dist/src/ai/utils.d.ts +21 -0
  35. package/dist/src/ai/utils.d.ts.map +1 -1
  36. package/dist/src/ai/vercel-ai.d.ts.map +1 -1
  37. package/dist/src/client.d.ts +4 -2
  38. package/dist/src/client.d.ts.map +1 -1
  39. package/dist/src/config/types.d.ts +44 -1
  40. package/dist/src/config/types.d.ts.map +1 -1
  41. package/dist/src/database/adapters/drizzle.d.ts +23 -0
  42. package/dist/src/database/adapters/drizzle.d.ts.map +1 -0
  43. package/dist/src/database/adapters/mongodb.d.ts +17 -0
  44. package/dist/src/database/adapters/mongodb.d.ts.map +1 -0
  45. package/dist/src/database/adapters/prisma.d.ts +18 -0
  46. package/dist/src/database/adapters/prisma.d.ts.map +1 -0
  47. package/dist/src/database/factory.d.ts +9 -0
  48. package/dist/src/database/factory.d.ts.map +1 -0
  49. package/dist/src/database/index.d.ts +9 -0
  50. package/dist/src/database/index.d.ts.map +1 -0
  51. package/dist/src/database/schemas/drizzle.d.ts +508 -0
  52. package/dist/src/database/schemas/drizzle.d.ts.map +1 -0
  53. package/dist/src/database/token-store.d.ts +28 -0
  54. package/dist/src/database/token-store.d.ts.map +1 -0
  55. package/dist/src/database/trigger-store.d.ts +23 -0
  56. package/dist/src/database/trigger-store.d.ts.map +1 -0
  57. package/dist/src/database/types.d.ts +132 -0
  58. package/dist/src/database/types.d.ts.map +1 -0
  59. package/dist/src/integrations/integration-docs-metadata.d.ts +40 -0
  60. package/dist/src/integrations/integration-docs-metadata.d.ts.map +1 -0
  61. package/dist/src/server.d.ts +4 -3
  62. package/dist/src/server.d.ts.map +1 -1
  63. package/package.json +32 -5
@@ -0,0 +1,1167 @@
1
+ // src/database/token-store.ts
2
+ var USABLE_ACCESS_TOKEN_BUFFER_MS = 30 * 1000;
3
+ var MIN_MEANINGFUL_EXPIRY_MS = Date.UTC(2000, 0, 1);
4
+ function getRowUpdatedAtMs(row) {
5
+ return row.updatedAt instanceof Date ? row.updatedAt.getTime() : 0;
6
+ }
7
+ function normalizeAccountEmail(value) {
8
+ if (!value)
9
+ return null;
10
+ const normalized = value.trim().toLowerCase();
11
+ return normalized.length > 0 ? normalized : null;
12
+ }
13
+ function normalizeAccountEmailHint(value) {
14
+ const normalized = normalizeAccountEmail(value);
15
+ if (!normalized)
16
+ return null;
17
+ return normalized.includes("@") ? normalized : null;
18
+ }
19
+ function normalizeAccountIdentifier(value) {
20
+ return normalizeAccountEmail(value);
21
+ }
22
+ function normalizeAccountIdHint(value) {
23
+ if (!value)
24
+ return null;
25
+ const normalized = value.trim().toLowerCase();
26
+ return normalized.length > 0 ? normalized : null;
27
+ }
28
+ function normalizeProviderTokenType(value) {
29
+ const normalized = value?.trim();
30
+ return normalized && normalized.length > 0 ? normalized : "Bearer";
31
+ }
32
+ function hasMeaningfulExpiresAt(value) {
33
+ if (!value)
34
+ return false;
35
+ const ms = value.getTime();
36
+ return Number.isFinite(ms) && ms >= MIN_MEANINGFUL_EXPIRY_MS;
37
+ }
38
+ function hasUsableAccessToken(row, now = Date.now(), bufferMs = USABLE_ACCESS_TOKEN_BUFFER_MS) {
39
+ if (!row.accessToken)
40
+ return false;
41
+ const expiresAt = row.expiresAt;
42
+ if (!hasMeaningfulExpiresAt(expiresAt))
43
+ return true;
44
+ return expiresAt.getTime() > now + bufferMs;
45
+ }
46
+ function isLikelyUsableToken(row, now = Date.now()) {
47
+ return hasUsableAccessToken(row, now) || Boolean(row.refreshToken);
48
+ }
49
+ function parseScopes(scope) {
50
+ if (!scope)
51
+ return;
52
+ const scopes = scope.split(" ").map((item) => item.trim()).filter((item) => item.length > 0);
53
+ return scopes.length > 0 ? scopes : undefined;
54
+ }
55
+ function choosePreferredTokenRow(rows) {
56
+ if (rows.length === 0)
57
+ return;
58
+ const sorted = [...rows].sort((left, right) => getRowUpdatedAtMs(right) - getRowUpdatedAtMs(left));
59
+ return sorted.find((row) => hasUsableAccessToken(row)) ?? sorted.find((row) => Boolean(row.refreshToken)) ?? sorted[0];
60
+ }
61
+ function selectProviderTokenRow(rows, email, accountId) {
62
+ if (rows.length === 0) {
63
+ return;
64
+ }
65
+ const normalizedEmail = normalizeAccountEmailHint(email);
66
+ const normalizedAccountId = normalizeAccountIdHint(accountId);
67
+ if (normalizedAccountId && normalizedEmail) {
68
+ const exactBoth = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedAccountId && normalizeAccountEmail(row.accountEmail) === normalizedEmail);
69
+ if (exactBoth.length > 0) {
70
+ return choosePreferredTokenRow(exactBoth);
71
+ }
72
+ }
73
+ if (normalizedAccountId) {
74
+ const exactAccountId = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedAccountId);
75
+ if (exactAccountId.length > 0) {
76
+ return choosePreferredTokenRow(exactAccountId);
77
+ }
78
+ }
79
+ if (normalizedEmail) {
80
+ const exactEmail = rows.filter((row) => normalizeAccountEmail(row.accountEmail) === normalizedEmail);
81
+ if (exactEmail.length > 0) {
82
+ return choosePreferredTokenRow(exactEmail);
83
+ }
84
+ } else if (email) {
85
+ const normalizedIdentifier = normalizeAccountIdentifier(email);
86
+ if (normalizedIdentifier) {
87
+ const identifierMatches = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedIdentifier);
88
+ if (identifierMatches.length > 0) {
89
+ return choosePreferredTokenRow(identifierMatches);
90
+ }
91
+ }
92
+ }
93
+ if (normalizedAccountId || normalizedEmail) {
94
+ const legacyRows = rows.filter((row) => !normalizeAccountIdHint(row.accountId) && !normalizeAccountEmail(row.accountEmail));
95
+ if (legacyRows.length === 1) {
96
+ return choosePreferredTokenRow(legacyRows);
97
+ }
98
+ return;
99
+ }
100
+ return choosePreferredTokenRow(rows);
101
+ }
102
+ function providerTokenRecordToData(row) {
103
+ const expiresAt = hasMeaningfulExpiresAt(row.expiresAt) ? row.expiresAt : null;
104
+ const expiresIn = expiresAt ? Math.max(0, Math.floor((expiresAt.getTime() - Date.now()) / 1000)) : 3600;
105
+ return {
106
+ accessToken: row.accessToken,
107
+ refreshToken: row.refreshToken ?? undefined,
108
+ tokenType: normalizeProviderTokenType(row.tokenType),
109
+ expiresIn,
110
+ expiresAt: expiresAt?.toISOString(),
111
+ scopes: parseScopes(row.scope),
112
+ email: row.accountEmail ?? undefined,
113
+ accountId: row.accountId ?? undefined
114
+ };
115
+ }
116
+ function listConnectedProvidersFromRows(rows, configuredIntegrationIds) {
117
+ const allowed = configuredIntegrationIds ? new Set(configuredIntegrationIds) : undefined;
118
+ const rowsByProvider = new Map;
119
+ for (const row of rows) {
120
+ if (allowed && !allowed.has(row.provider))
121
+ continue;
122
+ const existing = rowsByProvider.get(row.provider);
123
+ if (existing) {
124
+ existing.push(row);
125
+ } else {
126
+ rowsByProvider.set(row.provider, [row]);
127
+ }
128
+ }
129
+ const connected = [];
130
+ for (const [provider, providerRows] of rowsByProvider.entries()) {
131
+ const selected = selectProviderTokenRow(providerRows);
132
+ if (selected && isLikelyUsableToken(selected)) {
133
+ connected.push(provider);
134
+ }
135
+ }
136
+ return connected.sort();
137
+ }
138
+ async function listConnectedProviders(configuredIntegrationIds, getProviderToken, context) {
139
+ if (!context.userId || configuredIntegrationIds.length === 0) {
140
+ return [];
141
+ }
142
+ const connected = [];
143
+ await Promise.all(configuredIntegrationIds.map(async (provider) => {
144
+ try {
145
+ const token = await getProviderToken(provider, undefined, context);
146
+ if (token?.accessToken || typeof token?.refreshToken === "string" && token.refreshToken.length > 0) {
147
+ connected.push(provider);
148
+ }
149
+ } catch {}
150
+ }));
151
+ return connected.sort();
152
+ }
153
+ function defaultResolveAccountIdentity(provider, tokenData, emailHint) {
154
+ const accountEmail = normalizeAccountEmail(emailHint ?? tokenData.email ?? null);
155
+ let accountId = normalizeAccountIdHint(tokenData.accountId ?? null);
156
+ if (!accountId && accountEmail) {
157
+ accountId = `${provider}:${accountEmail}`;
158
+ }
159
+ return { accountEmail, accountId };
160
+ }
161
+
162
+ // src/database/trigger-store.ts
163
+ function toIsoString(value) {
164
+ if (!value)
165
+ return null;
166
+ if (value instanceof Date) {
167
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
168
+ }
169
+ const parsed = new Date(value);
170
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
171
+ }
172
+ function toDbSchedule(value) {
173
+ if (value.scheduleType && value.scheduleValue) {
174
+ return {
175
+ scheduleType: value.scheduleType,
176
+ scheduleValue: value.scheduleValue
177
+ };
178
+ }
179
+ if (value.schedule.type === "once") {
180
+ const runAt = toIsoString(value.schedule.runAt);
181
+ if (!runAt) {
182
+ throw new Error("Invalid trigger once schedule");
183
+ }
184
+ return {
185
+ scheduleType: "once",
186
+ scheduleValue: runAt
187
+ };
188
+ }
189
+ return {
190
+ scheduleType: "cron",
191
+ scheduleValue: value.schedule.expression
192
+ };
193
+ }
194
+ function toSdkSchedule(row) {
195
+ if (row.scheduleType === "once") {
196
+ return {
197
+ type: "once",
198
+ runAt: row.scheduleValue
199
+ };
200
+ }
201
+ return {
202
+ type: "cron",
203
+ expression: row.scheduleValue
204
+ };
205
+ }
206
+ function toSdkTrigger(row) {
207
+ return {
208
+ id: row.id,
209
+ userId: row.userId ?? undefined,
210
+ name: row.name ?? undefined,
211
+ description: row.description ?? undefined,
212
+ toolName: row.toolName,
213
+ toolArguments: row.toolArguments ?? {},
214
+ schedule: toSdkSchedule(row),
215
+ status: row.status,
216
+ provider: row.provider ?? undefined,
217
+ createdAt: row.createdAt.toISOString(),
218
+ updatedAt: row.updatedAt.toISOString(),
219
+ lastRunAt: toIsoString(row.lastRunAt) ?? undefined,
220
+ nextRunAt: toIsoString(row.nextRunAt) ?? undefined,
221
+ runCount: row.runCount,
222
+ lastError: row.lastError ?? undefined,
223
+ lastResult: row.lastResult ?? undefined
224
+ };
225
+ }
226
+ function toDbTriggerUpdates(updates) {
227
+ const dbUpdates = {
228
+ updatedAt: new Date
229
+ };
230
+ if (updates.name !== undefined)
231
+ dbUpdates.name = updates.name ?? null;
232
+ if (updates.description !== undefined) {
233
+ dbUpdates.description = updates.description ?? null;
234
+ }
235
+ if (updates.toolArguments !== undefined) {
236
+ dbUpdates.toolArguments = updates.toolArguments;
237
+ }
238
+ if (updates.status !== undefined)
239
+ dbUpdates.status = updates.status;
240
+ if (updates.provider !== undefined)
241
+ dbUpdates.provider = updates.provider ?? null;
242
+ if (updates.lastError !== undefined)
243
+ dbUpdates.lastError = updates.lastError ?? null;
244
+ if (updates.lastResult !== undefined) {
245
+ dbUpdates.lastResult = updates.lastResult ?? null;
246
+ }
247
+ if (updates.lastRunAt !== undefined) {
248
+ dbUpdates.lastRunAt = updates.lastRunAt ? new Date(updates.lastRunAt) : null;
249
+ }
250
+ if (updates.nextRunAt !== undefined) {
251
+ dbUpdates.nextRunAt = updates.nextRunAt ? new Date(updates.nextRunAt) : null;
252
+ }
253
+ if (updates.runCount !== undefined)
254
+ dbUpdates.runCount = updates.runCount;
255
+ if (updates.schedule) {
256
+ if (updates.schedule.type === "once") {
257
+ dbUpdates.scheduleType = "once";
258
+ dbUpdates.scheduleValue = new Date(updates.schedule.runAt).toISOString();
259
+ } else {
260
+ dbUpdates.scheduleType = "cron";
261
+ dbUpdates.scheduleValue = updates.schedule.expression;
262
+ }
263
+ }
264
+ return dbUpdates;
265
+ }
266
+ function flattenedTriggerToCreateInput(triggerData, contextUserId) {
267
+ const schedule = toDbSchedule(triggerData);
268
+ return {
269
+ id: triggerData.id,
270
+ userId: contextUserId ?? triggerData.userId ?? null,
271
+ name: triggerData.name ?? null,
272
+ description: triggerData.description ?? null,
273
+ toolName: triggerData.toolName,
274
+ toolArguments: triggerData.toolArguments ?? {},
275
+ scheduleType: schedule.scheduleType,
276
+ scheduleValue: schedule.scheduleValue,
277
+ status: triggerData.status ?? "active",
278
+ provider: triggerData.provider ?? null,
279
+ nextRunAt: triggerData.nextRunAt ? new Date(triggerData.nextRunAt) : null
280
+ };
281
+ }
282
+
283
+ // src/database/factory.ts
284
+ function log(debug, message, error) {
285
+ if (!debug)
286
+ return;
287
+ if (error !== undefined) {
288
+ console.error(`[Integrate SDK] ${message}`, error);
289
+ return;
290
+ }
291
+ console.log(`[Integrate SDK] ${message}`);
292
+ }
293
+ async function authorizeTriggerRow(row, context, hooks) {
294
+ if (!row)
295
+ return null;
296
+ const repaired = hooks?.authorizeTrigger ? await hooks.authorizeTrigger(row, context) : row;
297
+ if (!repaired)
298
+ return null;
299
+ if (context?.userId && repaired.userId !== context.userId) {
300
+ return null;
301
+ }
302
+ return repaired;
303
+ }
304
+ function createDatabaseAdapterCallbacks(options) {
305
+ const { driver, hooks, debugLogs } = options;
306
+ const getProviderToken = async (provider, email, context) => {
307
+ const userId = context?.userId;
308
+ if (!userId) {
309
+ return;
310
+ }
311
+ const accountEmailHint = normalizeAccountEmailHint(email) ?? normalizeAccountEmailHint(typeof context?.accountEmail === "string" ? context.accountEmail : null);
312
+ const accountIdHint = normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null);
313
+ try {
314
+ const rows = await driver.tokens.listProviderTokens(userId, provider);
315
+ const selectedRow = selectProviderTokenRow(rows, accountEmailHint ?? undefined, accountIdHint ?? undefined);
316
+ if (!selectedRow) {
317
+ return;
318
+ }
319
+ return providerTokenRecordToData(selectedRow);
320
+ } catch (error) {
321
+ log(debugLogs, "Error fetching provider token:", error);
322
+ return;
323
+ }
324
+ };
325
+ const setProviderToken = async (provider, tokenData, email, context) => {
326
+ const userId = context?.userId;
327
+ if (!userId) {
328
+ console.error("[Integrate SDK] Cannot save token: No userId in context");
329
+ return;
330
+ }
331
+ const accountEmail = normalizeAccountEmailHint(email) ?? normalizeAccountEmail(tokenData?.email ?? null);
332
+ if (tokenData === null) {
333
+ try {
334
+ await driver.tokens.deleteProviderTokens({
335
+ userId,
336
+ provider,
337
+ accountEmail,
338
+ accountId: normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null)
339
+ });
340
+ await hooks?.onTokenChange?.({ userId, provider, action: "remove" });
341
+ } catch (error) {
342
+ log(debugLogs, "Error deleting provider token:", error);
343
+ throw error;
344
+ }
345
+ return;
346
+ }
347
+ try {
348
+ const resolvedIdentity = hooks?.resolveAccountIdentity ? await hooks.resolveAccountIdentity(provider, tokenData, accountEmail, context) : defaultResolveAccountIdentity(provider, tokenData, accountEmail);
349
+ const resolvedAccountEmail = resolvedIdentity.accountEmail;
350
+ const resolvedAccountId = normalizeAccountIdHint(resolvedIdentity.accountId) ?? normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null) ?? null;
351
+ const rows = await driver.tokens.listProviderTokens(userId, provider);
352
+ let existing = selectProviderTokenRow(rows, resolvedAccountEmail ?? accountEmail ?? undefined, resolvedAccountId ?? undefined) ?? rows.find((row) => {
353
+ const sameEmail = resolvedAccountEmail && normalizeAccountEmail(row.accountEmail) === resolvedAccountEmail;
354
+ const sameAccountId = resolvedAccountId && normalizeAccountIdHint(row.accountId) === resolvedAccountId;
355
+ return Boolean(sameEmail || sameAccountId);
356
+ }) ?? (rows.length === 1 ? rows[0] : undefined);
357
+ const parsedExpiresAt = tokenData.expiresAt ? new Date(tokenData.expiresAt) : null;
358
+ const expiresAt = hasMeaningfulExpiresAt(parsedExpiresAt) ? parsedExpiresAt : null;
359
+ const scope = tokenData.scopes?.join(" ") ?? null;
360
+ const saved = await driver.tokens.upsertProviderToken({
361
+ existingId: existing?.id,
362
+ id: existing?.id ?? `${userId}-${provider}-${resolvedAccountEmail ?? "default"}-${Date.now()}`,
363
+ userId,
364
+ provider,
365
+ accountEmail: resolvedAccountEmail,
366
+ accountId: resolvedAccountId,
367
+ accessToken: tokenData.accessToken,
368
+ refreshToken: tokenData.refreshToken ?? null,
369
+ tokenType: normalizeProviderTokenType(tokenData.tokenType),
370
+ expiresAt,
371
+ scope
372
+ });
373
+ await driver.tokens.deleteDuplicateProviderTokens({
374
+ keepId: saved.id,
375
+ userId,
376
+ provider,
377
+ accountEmail: resolvedAccountEmail,
378
+ accountId: resolvedAccountId
379
+ });
380
+ await hooks?.onTokenChange?.({ userId, provider, action: "set" });
381
+ } catch (error) {
382
+ log(debugLogs, "Error saving provider token:", error);
383
+ throw error;
384
+ }
385
+ };
386
+ const removeProviderToken = async (provider, email, context) => {
387
+ const userId = context?.userId;
388
+ if (!userId) {
389
+ console.error("[Integrate SDK] Cannot delete token: No userId in context");
390
+ return;
391
+ }
392
+ try {
393
+ await driver.tokens.deleteProviderTokens({
394
+ userId,
395
+ provider,
396
+ accountEmail: normalizeAccountEmail(email)
397
+ });
398
+ await hooks?.onTokenChange?.({ userId, provider, action: "remove" });
399
+ } catch (error) {
400
+ log(debugLogs, "Error deleting provider token:", error);
401
+ throw error;
402
+ }
403
+ };
404
+ const callbacks = {
405
+ getProviderToken,
406
+ setProviderToken,
407
+ removeProviderToken
408
+ };
409
+ if (driver.triggers) {
410
+ const triggerDriver = driver.triggers;
411
+ const triggers = {
412
+ create: async (triggerData, context) => {
413
+ try {
414
+ const created = await triggerDriver.createTrigger(flattenedTriggerToCreateInput(triggerData, context?.userId));
415
+ return toSdkTrigger(created);
416
+ } catch (error) {
417
+ log(debugLogs, "Error creating trigger:", error);
418
+ throw error;
419
+ }
420
+ },
421
+ get: async (triggerId, context) => {
422
+ try {
423
+ const found = await triggerDriver.getTriggerById(triggerId);
424
+ const authorized = await authorizeTriggerRow(found, context, hooks);
425
+ return authorized ? toSdkTrigger(authorized) : null;
426
+ } catch (error) {
427
+ log(debugLogs, "Error getting trigger:", error);
428
+ throw error;
429
+ }
430
+ },
431
+ list: async (params, context) => {
432
+ try {
433
+ const { rows, total } = await triggerDriver.listTriggers({
434
+ userId: context?.userId,
435
+ status: params.status,
436
+ toolName: params.toolName,
437
+ limit: params.limit ?? 20,
438
+ offset: params.offset ?? 0
439
+ });
440
+ const triggers2 = [];
441
+ for (const row of rows) {
442
+ const authorized = await authorizeTriggerRow(row, context, hooks);
443
+ if (authorized) {
444
+ triggers2.push(toSdkTrigger(authorized));
445
+ }
446
+ }
447
+ return { triggers: triggers2, total };
448
+ } catch (error) {
449
+ log(debugLogs, "Error listing triggers:", error);
450
+ throw error;
451
+ }
452
+ },
453
+ update: async (triggerId, updates, context) => {
454
+ try {
455
+ const existing = await triggerDriver.getTriggerById(triggerId);
456
+ const authorized = await authorizeTriggerRow(existing, context, hooks);
457
+ if (!authorized) {
458
+ throw new Error(`Trigger not found: ${triggerId}`);
459
+ }
460
+ const updated = await triggerDriver.updateTrigger(authorized.id, toDbTriggerUpdates(updates));
461
+ if (!updated) {
462
+ throw new Error(`Trigger not found: ${triggerId}`);
463
+ }
464
+ return toSdkTrigger(updated);
465
+ } catch (error) {
466
+ log(debugLogs, "Error updating trigger:", error);
467
+ throw error;
468
+ }
469
+ },
470
+ delete: async (triggerId, context) => {
471
+ try {
472
+ const existing = await triggerDriver.getTriggerById(triggerId);
473
+ const authorized = await authorizeTriggerRow(existing, context, hooks);
474
+ if (!authorized) {
475
+ return;
476
+ }
477
+ await triggerDriver.deleteTrigger(authorized.id);
478
+ } catch (error) {
479
+ log(debugLogs, "Error deleting trigger:", error);
480
+ throw error;
481
+ }
482
+ }
483
+ };
484
+ callbacks.triggers = triggers;
485
+ }
486
+ return callbacks;
487
+ }
488
+ function createDatabaseAdapterFactory(createDriver, options) {
489
+ return () => createDatabaseAdapterCallbacks({
490
+ driver: createDriver(),
491
+ hooks: options?.hooks,
492
+ debugLogs: options?.debugLogs
493
+ });
494
+ }
495
+ // src/database/adapters/drizzle.ts
496
+ import { and, count, desc, eq, ne, or } from "drizzle-orm";
497
+ function mapProviderTokenRow(row) {
498
+ return {
499
+ id: String(row.id),
500
+ userId: String(row.userId),
501
+ provider: String(row.provider),
502
+ accountEmail: row.accountEmail ?? null,
503
+ accountId: row.accountId ?? null,
504
+ accessToken: String(row.accessToken),
505
+ refreshToken: row.refreshToken ?? null,
506
+ tokenType: String(row.tokenType ?? "Bearer"),
507
+ expiresAt: row.expiresAt ?? null,
508
+ scope: row.scope ?? null,
509
+ createdAt: row.createdAt,
510
+ updatedAt: row.updatedAt
511
+ };
512
+ }
513
+ function mapTriggerRow(row) {
514
+ return {
515
+ id: String(row.id),
516
+ userId: row.userId ?? null,
517
+ name: row.name ?? null,
518
+ description: row.description ?? null,
519
+ toolName: String(row.toolName),
520
+ toolArguments: row.toolArguments ?? {},
521
+ scheduleType: row.scheduleType,
522
+ scheduleValue: String(row.scheduleValue),
523
+ status: String(row.status),
524
+ provider: row.provider ?? null,
525
+ lastRunAt: row.lastRunAt ?? null,
526
+ nextRunAt: row.nextRunAt ?? null,
527
+ runCount: Number(row.runCount ?? 0),
528
+ lastError: row.lastError ?? null,
529
+ lastResult: row.lastResult ?? null,
530
+ createdAt: row.createdAt,
531
+ updatedAt: row.updatedAt
532
+ };
533
+ }
534
+ function createDrizzleTokenDriver(db, table) {
535
+ const t = table;
536
+ return {
537
+ async listProviderTokens(userId, provider) {
538
+ const rows = await db.select().from(table).where(and(eq(t.userId, userId), eq(t.provider, provider))).orderBy(desc(t.updatedAt)).limit(32);
539
+ return rows.map((row) => mapProviderTokenRow(row));
540
+ },
541
+ async upsertProviderToken(input) {
542
+ const now = new Date;
543
+ const values = {
544
+ id: input.existingId ?? input.id,
545
+ userId: input.userId,
546
+ provider: input.provider,
547
+ accountEmail: input.accountEmail,
548
+ accountId: input.accountId,
549
+ accessToken: input.accessToken,
550
+ refreshToken: input.refreshToken,
551
+ tokenType: input.tokenType,
552
+ expiresAt: input.expiresAt,
553
+ scope: input.scope,
554
+ updatedAt: now,
555
+ ...input.existingId ? {} : { createdAt: now }
556
+ };
557
+ if (input.existingId) {
558
+ const [updated] = await db.update(table).set(values).where(eq(t.id, input.existingId)).returning();
559
+ return mapProviderTokenRow(updated);
560
+ }
561
+ const [created] = await db.insert(table).values(values).returning();
562
+ return mapProviderTokenRow(created);
563
+ },
564
+ async deleteProviderTokens(input) {
565
+ const conditions = [
566
+ eq(t.userId, input.userId),
567
+ eq(t.provider, input.provider)
568
+ ];
569
+ if (input.accountEmail) {
570
+ conditions.push(eq(t.accountEmail, input.accountEmail));
571
+ } else if (input.accountId) {
572
+ conditions.push(eq(t.accountId, input.accountId));
573
+ }
574
+ await db.delete(table).where(and(...conditions));
575
+ },
576
+ async deleteDuplicateProviderTokens(input) {
577
+ const normalizedEmail = normalizeAccountEmail(input.accountEmail);
578
+ const normalizedAccountId = normalizeAccountIdHint(input.accountId);
579
+ if (!normalizedEmail && !normalizedAccountId) {
580
+ return;
581
+ }
582
+ const duplicateConditions = [
583
+ eq(t.userId, input.userId),
584
+ eq(t.provider, input.provider),
585
+ ne(t.id, input.keepId)
586
+ ];
587
+ const identityConditions = [];
588
+ if (normalizedEmail) {
589
+ identityConditions.push(eq(t.accountEmail, normalizedEmail));
590
+ }
591
+ if (normalizedAccountId) {
592
+ identityConditions.push(eq(t.accountId, normalizedAccountId));
593
+ }
594
+ if (identityConditions.length === 0) {
595
+ return;
596
+ }
597
+ await db.delete(table).where(and(...duplicateConditions, or(...identityConditions)));
598
+ }
599
+ };
600
+ }
601
+ function createDrizzleTriggerDriver(db, table) {
602
+ const t = table;
603
+ return {
604
+ async createTrigger(input) {
605
+ const now = new Date;
606
+ const [created] = await db.insert(table).values({
607
+ id: input.id,
608
+ userId: input.userId,
609
+ name: input.name ?? null,
610
+ description: input.description ?? null,
611
+ toolName: input.toolName,
612
+ toolArguments: input.toolArguments,
613
+ scheduleType: input.scheduleType,
614
+ scheduleValue: input.scheduleValue,
615
+ status: input.status,
616
+ provider: input.provider ?? null,
617
+ nextRunAt: input.nextRunAt ?? null,
618
+ createdAt: now,
619
+ updatedAt: now
620
+ }).returning();
621
+ return mapTriggerRow(created);
622
+ },
623
+ async getTriggerById(triggerId) {
624
+ const [found] = await db.select().from(table).where(eq(t.id, triggerId)).limit(1);
625
+ return found ? mapTriggerRow(found) : null;
626
+ },
627
+ async listTriggers(query) {
628
+ const conditions = [];
629
+ if (query.userId) {
630
+ conditions.push(eq(t.userId, query.userId));
631
+ }
632
+ if (query.status) {
633
+ conditions.push(eq(t.status, query.status));
634
+ }
635
+ if (query.toolName) {
636
+ conditions.push(eq(t.toolName, query.toolName));
637
+ }
638
+ const whereClause = conditions.length > 0 ? and(...conditions) : undefined;
639
+ const rows = await db.select().from(table).where(whereClause).limit(query.limit).offset(query.offset);
640
+ const [totalResult] = await db.select({ count: count() }).from(table).where(whereClause);
641
+ return {
642
+ rows: rows.map((row) => mapTriggerRow(row)),
643
+ total: Number(totalResult?.count ?? 0)
644
+ };
645
+ },
646
+ async updateTrigger(triggerId, updates) {
647
+ const [updated] = await db.update(table).set(updates).where(eq(t.id, triggerId)).returning();
648
+ return updated ? mapTriggerRow(updated) : null;
649
+ },
650
+ async deleteTrigger(triggerId) {
651
+ await db.delete(table).where(eq(t.id, triggerId));
652
+ }
653
+ };
654
+ }
655
+ function createDrizzleDatabaseDriver(db, schema) {
656
+ const driver = {
657
+ tokens: createDrizzleTokenDriver(db, schema.providerToken)
658
+ };
659
+ if (schema.trigger) {
660
+ driver.triggers = createDrizzleTriggerDriver(db, schema.trigger);
661
+ }
662
+ return driver;
663
+ }
664
+ function drizzleAdapter(db, config) {
665
+ config.provider;
666
+ const driver = () => createDrizzleDatabaseDriver(db, config.schema);
667
+ return createDatabaseAdapterFactory(driver, {
668
+ hooks: config.hooks,
669
+ debugLogs: config.debugLogs
670
+ });
671
+ }
672
+ function drizzleAdapterCallbacks(db, config) {
673
+ return createDatabaseAdapterCallbacks({
674
+ driver: createDrizzleDatabaseDriver(db, config.schema),
675
+ hooks: config.hooks,
676
+ debugLogs: config.debugLogs
677
+ });
678
+ }
679
+ // src/database/adapters/prisma.ts
680
+ var DEFAULT_MODEL_NAMES = {
681
+ providerToken: "providerToken",
682
+ trigger: "trigger"
683
+ };
684
+ function getModel(client, name) {
685
+ const model = client[name];
686
+ if (!model) {
687
+ throw new Error(`[Integrate SDK] Prisma model "${name}" was not found on the client`);
688
+ }
689
+ return model;
690
+ }
691
+ function mapProviderTokenRow2(row) {
692
+ return {
693
+ id: String(row.id),
694
+ userId: String(row.userId),
695
+ provider: String(row.provider),
696
+ accountEmail: row.accountEmail ?? null,
697
+ accountId: row.accountId ?? null,
698
+ accessToken: String(row.accessToken),
699
+ refreshToken: row.refreshToken ?? null,
700
+ tokenType: String(row.tokenType ?? "Bearer"),
701
+ expiresAt: row.expiresAt ?? null,
702
+ scope: row.scope ?? null,
703
+ createdAt: row.createdAt,
704
+ updatedAt: row.updatedAt
705
+ };
706
+ }
707
+ function mapTriggerRow2(row) {
708
+ return {
709
+ id: String(row.id),
710
+ userId: row.userId ?? null,
711
+ name: row.name ?? null,
712
+ description: row.description ?? null,
713
+ toolName: String(row.toolName),
714
+ toolArguments: row.toolArguments ?? {},
715
+ scheduleType: row.scheduleType,
716
+ scheduleValue: String(row.scheduleValue),
717
+ status: String(row.status),
718
+ provider: row.provider ?? null,
719
+ lastRunAt: row.lastRunAt ?? null,
720
+ nextRunAt: row.nextRunAt ?? null,
721
+ runCount: Number(row.runCount ?? 0),
722
+ lastError: row.lastError ?? null,
723
+ lastResult: row.lastResult ?? null,
724
+ createdAt: row.createdAt,
725
+ updatedAt: row.updatedAt
726
+ };
727
+ }
728
+ function createPrismaTokenDriver(prisma, modelName) {
729
+ const model = () => getModel(prisma, modelName);
730
+ return {
731
+ async listProviderTokens(userId, provider) {
732
+ const rows = await model().findMany({
733
+ where: { userId, provider },
734
+ orderBy: { updatedAt: "desc" },
735
+ take: 32
736
+ });
737
+ return rows.map((row) => mapProviderTokenRow2(row));
738
+ },
739
+ async upsertProviderToken(input) {
740
+ const now = new Date;
741
+ const data = {
742
+ userId: input.userId,
743
+ provider: input.provider,
744
+ accountEmail: input.accountEmail,
745
+ accountId: input.accountId,
746
+ accessToken: input.accessToken,
747
+ refreshToken: input.refreshToken,
748
+ tokenType: input.tokenType,
749
+ expiresAt: input.expiresAt,
750
+ scope: input.scope,
751
+ updatedAt: now
752
+ };
753
+ if (input.existingId) {
754
+ const updated = await model().update({
755
+ where: { id: input.existingId },
756
+ data
757
+ });
758
+ return mapProviderTokenRow2(updated);
759
+ }
760
+ const created = await model().create({
761
+ data: {
762
+ id: input.id,
763
+ ...data,
764
+ createdAt: now
765
+ }
766
+ });
767
+ return mapProviderTokenRow2(created);
768
+ },
769
+ async deleteProviderTokens(input) {
770
+ const where = {
771
+ userId: input.userId,
772
+ provider: input.provider
773
+ };
774
+ if (input.accountEmail) {
775
+ where.accountEmail = input.accountEmail;
776
+ } else if (input.accountId) {
777
+ where.accountId = input.accountId;
778
+ }
779
+ await model().deleteMany({ where });
780
+ },
781
+ async deleteDuplicateProviderTokens(input) {
782
+ const normalizedEmail = normalizeAccountEmail(input.accountEmail);
783
+ const normalizedAccountId = normalizeAccountIdHint(input.accountId);
784
+ if (!normalizedEmail && !normalizedAccountId) {
785
+ return;
786
+ }
787
+ const orConditions = [];
788
+ if (normalizedEmail) {
789
+ orConditions.push({ accountEmail: normalizedEmail });
790
+ }
791
+ if (normalizedAccountId) {
792
+ orConditions.push({ accountId: normalizedAccountId });
793
+ }
794
+ await model().deleteMany({
795
+ where: {
796
+ userId: input.userId,
797
+ provider: input.provider,
798
+ id: { not: input.keepId },
799
+ OR: orConditions
800
+ }
801
+ });
802
+ }
803
+ };
804
+ }
805
+ function createPrismaTriggerDriver(prisma, modelName) {
806
+ const model = () => getModel(prisma, modelName);
807
+ return {
808
+ async createTrigger(input) {
809
+ const now = new Date;
810
+ const created = await model().create({
811
+ data: {
812
+ id: input.id,
813
+ userId: input.userId,
814
+ name: input.name ?? null,
815
+ description: input.description ?? null,
816
+ toolName: input.toolName,
817
+ toolArguments: input.toolArguments,
818
+ scheduleType: input.scheduleType,
819
+ scheduleValue: input.scheduleValue,
820
+ status: input.status,
821
+ provider: input.provider ?? null,
822
+ nextRunAt: input.nextRunAt ?? null,
823
+ createdAt: now,
824
+ updatedAt: now
825
+ }
826
+ });
827
+ return mapTriggerRow2(created);
828
+ },
829
+ async getTriggerById(triggerId) {
830
+ const found = await model().findFirst({ where: { id: triggerId } });
831
+ return found ? mapTriggerRow2(found) : null;
832
+ },
833
+ async listTriggers(query) {
834
+ const where = {};
835
+ if (query.userId)
836
+ where.userId = query.userId;
837
+ if (query.status)
838
+ where.status = query.status;
839
+ if (query.toolName)
840
+ where.toolName = query.toolName;
841
+ const [rows, total] = await Promise.all([
842
+ model().findMany({
843
+ where,
844
+ take: query.limit,
845
+ skip: query.offset,
846
+ orderBy: { updatedAt: "desc" }
847
+ }),
848
+ model().count({ where })
849
+ ]);
850
+ return {
851
+ rows: rows.map((row) => mapTriggerRow2(row)),
852
+ total
853
+ };
854
+ },
855
+ async updateTrigger(triggerId, updates) {
856
+ try {
857
+ const updated = await model().update({
858
+ where: { id: triggerId },
859
+ data: updates
860
+ });
861
+ return mapTriggerRow2(updated);
862
+ } catch {
863
+ return null;
864
+ }
865
+ },
866
+ async deleteTrigger(triggerId) {
867
+ await model().delete({ where: { id: triggerId } });
868
+ }
869
+ };
870
+ }
871
+ function createPrismaDatabaseDriver(prisma, config) {
872
+ const modelNames = {
873
+ ...DEFAULT_MODEL_NAMES,
874
+ ...config.modelNames
875
+ };
876
+ const driver = {
877
+ tokens: createPrismaTokenDriver(prisma, modelNames.providerToken)
878
+ };
879
+ if (config.modelNames?.trigger !== null) {
880
+ driver.triggers = createPrismaTriggerDriver(prisma, modelNames.trigger);
881
+ }
882
+ return driver;
883
+ }
884
+ function prismaAdapter(prisma, config) {
885
+ config.provider;
886
+ return createDatabaseAdapterFactory(() => createPrismaDatabaseDriver(prisma, config), {
887
+ hooks: config.hooks,
888
+ debugLogs: config.debugLogs
889
+ });
890
+ }
891
+ function prismaAdapterCallbacks(prisma, config) {
892
+ return createDatabaseAdapterCallbacks({
893
+ driver: createPrismaDatabaseDriver(prisma, config),
894
+ hooks: config.hooks,
895
+ debugLogs: config.debugLogs
896
+ });
897
+ }
898
+ // src/database/adapters/mongodb.ts
899
+ var DEFAULT_COLLECTIONS = {
900
+ providerTokens: "provider_tokens",
901
+ triggers: "triggers"
902
+ };
903
+ function mapProviderTokenDoc(doc) {
904
+ return {
905
+ id: String(doc.id),
906
+ userId: String(doc.userId),
907
+ provider: String(doc.provider),
908
+ accountEmail: doc.accountEmail ?? null,
909
+ accountId: doc.accountId ?? null,
910
+ accessToken: String(doc.accessToken),
911
+ refreshToken: doc.refreshToken ?? null,
912
+ tokenType: String(doc.tokenType ?? "Bearer"),
913
+ expiresAt: doc.expiresAt ? new Date(doc.expiresAt) : null,
914
+ scope: doc.scope ?? null,
915
+ createdAt: new Date(doc.createdAt),
916
+ updatedAt: new Date(doc.updatedAt)
917
+ };
918
+ }
919
+ function mapTriggerDoc(doc) {
920
+ return {
921
+ id: String(doc.id),
922
+ userId: doc.userId ?? null,
923
+ name: doc.name ?? null,
924
+ description: doc.description ?? null,
925
+ toolName: String(doc.toolName),
926
+ toolArguments: doc.toolArguments ?? {},
927
+ scheduleType: doc.scheduleType,
928
+ scheduleValue: String(doc.scheduleValue),
929
+ status: String(doc.status),
930
+ provider: doc.provider ?? null,
931
+ lastRunAt: doc.lastRunAt ? new Date(doc.lastRunAt) : null,
932
+ nextRunAt: doc.nextRunAt ? new Date(doc.nextRunAt) : null,
933
+ runCount: Number(doc.runCount ?? 0),
934
+ lastError: doc.lastError ?? null,
935
+ lastResult: doc.lastResult ?? null,
936
+ createdAt: new Date(doc.createdAt),
937
+ updatedAt: new Date(doc.updatedAt)
938
+ };
939
+ }
940
+ function createMongoTokenDriver(db, collectionName) {
941
+ const collection = () => db.collection(collectionName);
942
+ return {
943
+ async listProviderTokens(userId, provider) {
944
+ const docs = await collection().find({ userId, provider }).sort({ updatedAt: -1 }).limit(32).toArray();
945
+ return docs.map((doc) => mapProviderTokenDoc(doc));
946
+ },
947
+ async upsertProviderToken(input) {
948
+ const now = new Date;
949
+ const id = input.existingId ?? input.id;
950
+ const doc = {
951
+ id,
952
+ userId: input.userId,
953
+ provider: input.provider,
954
+ accountEmail: input.accountEmail,
955
+ accountId: input.accountId,
956
+ accessToken: input.accessToken,
957
+ refreshToken: input.refreshToken,
958
+ tokenType: input.tokenType,
959
+ expiresAt: input.expiresAt,
960
+ scope: input.scope,
961
+ updatedAt: now,
962
+ ...input.existingId ? {} : { createdAt: now }
963
+ };
964
+ await collection().updateOne({ id }, { $set: doc }, { upsert: true });
965
+ const saved = await collection().findOne({ id });
966
+ return mapProviderTokenDoc(saved);
967
+ },
968
+ async deleteProviderTokens(input) {
969
+ const filter = {
970
+ userId: input.userId,
971
+ provider: input.provider
972
+ };
973
+ if (input.accountEmail) {
974
+ filter.accountEmail = input.accountEmail;
975
+ } else if (input.accountId) {
976
+ filter.accountId = input.accountId;
977
+ }
978
+ await collection().deleteMany(filter);
979
+ },
980
+ async deleteDuplicateProviderTokens(input) {
981
+ const normalizedEmail = normalizeAccountEmail(input.accountEmail);
982
+ const normalizedAccountId = normalizeAccountIdHint(input.accountId);
983
+ if (!normalizedEmail && !normalizedAccountId) {
984
+ return;
985
+ }
986
+ const orConditions = [];
987
+ if (normalizedEmail) {
988
+ orConditions.push({ accountEmail: normalizedEmail });
989
+ }
990
+ if (normalizedAccountId) {
991
+ orConditions.push({ accountId: normalizedAccountId });
992
+ }
993
+ await collection().deleteMany({
994
+ userId: input.userId,
995
+ provider: input.provider,
996
+ id: { $ne: input.keepId },
997
+ $or: orConditions
998
+ });
999
+ }
1000
+ };
1001
+ }
1002
+ function createMongoTriggerDriver(db, collectionName) {
1003
+ const collection = () => db.collection(collectionName);
1004
+ return {
1005
+ async createTrigger(input) {
1006
+ const now = new Date;
1007
+ const doc = {
1008
+ id: input.id,
1009
+ userId: input.userId,
1010
+ name: input.name ?? null,
1011
+ description: input.description ?? null,
1012
+ toolName: input.toolName,
1013
+ toolArguments: input.toolArguments,
1014
+ scheduleType: input.scheduleType,
1015
+ scheduleValue: input.scheduleValue,
1016
+ status: input.status,
1017
+ provider: input.provider ?? null,
1018
+ nextRunAt: input.nextRunAt ?? null,
1019
+ createdAt: now,
1020
+ updatedAt: now
1021
+ };
1022
+ await collection().insertOne(doc);
1023
+ return mapTriggerDoc(doc);
1024
+ },
1025
+ async getTriggerById(triggerId) {
1026
+ const found = await collection().findOne({ id: triggerId });
1027
+ return found ? mapTriggerDoc(found) : null;
1028
+ },
1029
+ async listTriggers(query) {
1030
+ const filter = {};
1031
+ if (query.userId)
1032
+ filter.userId = query.userId;
1033
+ if (query.status)
1034
+ filter.status = query.status;
1035
+ if (query.toolName)
1036
+ filter.toolName = query.toolName;
1037
+ const [docs, total] = await Promise.all([
1038
+ collection().find(filter).sort({ updatedAt: -1 }).skip(query.offset).limit(query.limit).toArray(),
1039
+ collection().countDocuments(filter)
1040
+ ]);
1041
+ return {
1042
+ rows: docs.map((doc) => mapTriggerDoc(doc)),
1043
+ total
1044
+ };
1045
+ },
1046
+ async updateTrigger(triggerId, updates) {
1047
+ const result = await collection().findOneAndUpdate({ id: triggerId }, { $set: updates }, { returnDocument: "after" });
1048
+ return result ? mapTriggerDoc(result) : null;
1049
+ },
1050
+ async deleteTrigger(triggerId) {
1051
+ await collection().deleteOne({ id: triggerId });
1052
+ }
1053
+ };
1054
+ }
1055
+ function createMongoDatabaseDriver(db, config) {
1056
+ const names = {
1057
+ ...DEFAULT_COLLECTIONS,
1058
+ ...config.collectionNames
1059
+ };
1060
+ const driver = {
1061
+ tokens: createMongoTokenDriver(db, names.providerTokens)
1062
+ };
1063
+ if (config.collectionNames?.triggers !== null) {
1064
+ driver.triggers = createMongoTriggerDriver(db, names.triggers);
1065
+ }
1066
+ return driver;
1067
+ }
1068
+ function mongodbAdapter(db, config = {}) {
1069
+ return createDatabaseAdapterFactory(() => createMongoDatabaseDriver(db, config), {
1070
+ hooks: config.hooks,
1071
+ debugLogs: config.debugLogs
1072
+ });
1073
+ }
1074
+ function mongodbAdapterCallbacks(db, config = {}) {
1075
+ return createDatabaseAdapterCallbacks({
1076
+ driver: createMongoDatabaseDriver(db, config),
1077
+ hooks: config.hooks,
1078
+ debugLogs: config.debugLogs
1079
+ });
1080
+ }
1081
+ // src/database/schemas/drizzle.ts
1082
+ import { sql } from "drizzle-orm";
1083
+ import {
1084
+ index,
1085
+ integer,
1086
+ jsonb,
1087
+ pgTable,
1088
+ text,
1089
+ timestamp,
1090
+ uniqueIndex
1091
+ } from "drizzle-orm/pg-core";
1092
+ var integrateProviderToken = pgTable("provider_token", {
1093
+ id: text("id").primaryKey(),
1094
+ userId: text("user_id").notNull(),
1095
+ provider: text("provider").notNull(),
1096
+ accountEmail: text("account_email"),
1097
+ accountId: text("account_id"),
1098
+ accessToken: text("access_token").notNull(),
1099
+ refreshToken: text("refresh_token"),
1100
+ tokenType: text("token_type").notNull().default("Bearer"),
1101
+ expiresAt: timestamp("expires_at"),
1102
+ scope: text("scope"),
1103
+ createdAt: timestamp("created_at", { mode: "date", precision: 3 }).default(sql`CURRENT_TIMESTAMP(3)`).notNull(),
1104
+ updatedAt: timestamp("updated_at", { mode: "date", precision: 3 }).default(sql`CURRENT_TIMESTAMP(3)`).notNull()
1105
+ }, (table) => [
1106
+ index("provider_token_user_id_idx").on(table.userId),
1107
+ index("provider_token_provider_idx").on(table.provider),
1108
+ index("provider_token_user_provider_idx").on(table.userId, table.provider),
1109
+ uniqueIndex("provider_token_user_provider_account_email_uidx").on(table.userId, table.provider, table.accountEmail)
1110
+ ]);
1111
+ var integrateTrigger = pgTable("trigger", {
1112
+ id: text("id").primaryKey(),
1113
+ userId: text("user_id"),
1114
+ name: text("name"),
1115
+ description: text("description"),
1116
+ toolName: text("tool_name").notNull(),
1117
+ toolArguments: jsonb("tool_arguments").notNull(),
1118
+ scheduleType: text("schedule_type").notNull(),
1119
+ scheduleValue: text("schedule_value").notNull(),
1120
+ status: text("status").notNull().default("active"),
1121
+ provider: text("provider"),
1122
+ lastRunAt: timestamp("last_run_at", { mode: "date", precision: 3 }),
1123
+ nextRunAt: timestamp("next_run_at", { mode: "date", precision: 3 }),
1124
+ runCount: integer("run_count").notNull().default(0),
1125
+ lastError: text("last_error"),
1126
+ lastResult: jsonb("last_result"),
1127
+ createdAt: timestamp("created_at", { mode: "date", precision: 3 }).default(sql`CURRENT_TIMESTAMP(3)`).notNull(),
1128
+ updatedAt: timestamp("updated_at", { mode: "date", precision: 3 }).default(sql`CURRENT_TIMESTAMP(3)`).notNull()
1129
+ }, (table) => [
1130
+ index("trigger_user_id_idx").on(table.userId),
1131
+ index("trigger_status_idx").on(table.status),
1132
+ index("trigger_next_run_at_idx").on(table.nextRunAt)
1133
+ ]);
1134
+ export {
1135
+ toSdkTrigger,
1136
+ toSdkSchedule,
1137
+ toDbTriggerUpdates,
1138
+ toDbSchedule,
1139
+ selectProviderTokenRow,
1140
+ providerTokenRecordToData,
1141
+ prismaAdapterCallbacks,
1142
+ prismaAdapter,
1143
+ parseScopes,
1144
+ normalizeProviderTokenType,
1145
+ normalizeAccountIdentifier,
1146
+ normalizeAccountIdHint,
1147
+ normalizeAccountEmailHint,
1148
+ normalizeAccountEmail,
1149
+ mongodbAdapterCallbacks,
1150
+ mongodbAdapter,
1151
+ listConnectedProvidersFromRows,
1152
+ listConnectedProviders,
1153
+ isLikelyUsableToken,
1154
+ integrateTrigger,
1155
+ integrateProviderToken,
1156
+ hasUsableAccessToken,
1157
+ hasMeaningfulExpiresAt,
1158
+ flattenedTriggerToCreateInput,
1159
+ drizzleAdapterCallbacks,
1160
+ drizzleAdapter,
1161
+ defaultResolveAccountIdentity,
1162
+ createPrismaDatabaseDriver,
1163
+ createMongoDatabaseDriver,
1164
+ createDrizzleDatabaseDriver,
1165
+ createDatabaseAdapterFactory,
1166
+ createDatabaseAdapterCallbacks
1167
+ };