integrate-sdk 0.9.54-dev.0 → 0.9.56

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 (41) hide show
  1. package/dist/adapters/index.js +2364 -0
  2. package/dist/adapters/solid-start.js +2364 -0
  3. package/dist/adapters/svelte-kit.js +2364 -0
  4. package/dist/database/adapters/drizzle.d.ts +23 -0
  5. package/dist/database/adapters/drizzle.d.ts.map +1 -0
  6. package/dist/database/adapters/drizzle.js +646 -0
  7. package/dist/database/adapters/mongodb.d.ts +17 -0
  8. package/dist/database/adapters/mongodb.d.ts.map +1 -0
  9. package/dist/database/adapters/mongodb.js +643 -0
  10. package/dist/database/adapters/prisma.d.ts +18 -0
  11. package/dist/database/adapters/prisma.d.ts.map +1 -0
  12. package/dist/database/adapters/prisma.js +679 -0
  13. package/dist/database/index.d.ts +9 -0
  14. package/dist/database/index.d.ts.map +1 -0
  15. package/dist/database/index.js +1128 -0
  16. package/dist/server.js +3515 -1
  17. package/dist/src/config/types.d.ts +25 -1
  18. package/dist/src/config/types.d.ts.map +1 -1
  19. package/dist/src/database/adapters/drizzle.d.ts +23 -0
  20. package/dist/src/database/adapters/drizzle.d.ts.map +1 -0
  21. package/dist/src/database/adapters/mongodb.d.ts +17 -0
  22. package/dist/src/database/adapters/mongodb.d.ts.map +1 -0
  23. package/dist/src/database/adapters/prisma.d.ts +18 -0
  24. package/dist/src/database/adapters/prisma.d.ts.map +1 -0
  25. package/dist/src/database/factory.d.ts +9 -0
  26. package/dist/src/database/factory.d.ts.map +1 -0
  27. package/dist/src/database/index.d.ts +9 -0
  28. package/dist/src/database/index.d.ts.map +1 -0
  29. package/dist/src/database/schemas/drizzle.d.ts +508 -0
  30. package/dist/src/database/schemas/drizzle.d.ts.map +1 -0
  31. package/dist/src/database/token-store.d.ts +18 -0
  32. package/dist/src/database/token-store.d.ts.map +1 -0
  33. package/dist/src/database/trigger-store.d.ts +23 -0
  34. package/dist/src/database/trigger-store.d.ts.map +1 -0
  35. package/dist/src/database/types.d.ts +132 -0
  36. package/dist/src/database/types.d.ts.map +1 -0
  37. package/dist/src/integrations/integration-docs-metadata.d.ts +40 -0
  38. package/dist/src/integrations/integration-docs-metadata.d.ts.map +1 -0
  39. package/dist/src/server.d.ts +4 -3
  40. package/dist/src/server.d.ts.map +1 -1
  41. package/package.json +32 -5
@@ -0,0 +1,643 @@
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 parseScopes(scope) {
47
+ if (!scope)
48
+ return;
49
+ const scopes = scope.split(" ").map((item) => item.trim()).filter((item) => item.length > 0);
50
+ return scopes.length > 0 ? scopes : undefined;
51
+ }
52
+ function choosePreferredTokenRow(rows) {
53
+ if (rows.length === 0)
54
+ return;
55
+ const sorted = [...rows].sort((left, right) => getRowUpdatedAtMs(right) - getRowUpdatedAtMs(left));
56
+ return sorted.find((row) => hasUsableAccessToken(row)) ?? sorted.find((row) => Boolean(row.refreshToken)) ?? sorted[0];
57
+ }
58
+ function selectProviderTokenRow(rows, email, accountId) {
59
+ if (rows.length === 0) {
60
+ return;
61
+ }
62
+ const normalizedEmail = normalizeAccountEmailHint(email);
63
+ const normalizedAccountId = normalizeAccountIdHint(accountId);
64
+ if (normalizedAccountId && normalizedEmail) {
65
+ const exactBoth = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedAccountId && normalizeAccountEmail(row.accountEmail) === normalizedEmail);
66
+ if (exactBoth.length > 0) {
67
+ return choosePreferredTokenRow(exactBoth);
68
+ }
69
+ }
70
+ if (normalizedAccountId) {
71
+ const exactAccountId = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedAccountId);
72
+ if (exactAccountId.length > 0) {
73
+ return choosePreferredTokenRow(exactAccountId);
74
+ }
75
+ }
76
+ if (normalizedEmail) {
77
+ const exactEmail = rows.filter((row) => normalizeAccountEmail(row.accountEmail) === normalizedEmail);
78
+ if (exactEmail.length > 0) {
79
+ return choosePreferredTokenRow(exactEmail);
80
+ }
81
+ } else if (email) {
82
+ const normalizedIdentifier = normalizeAccountIdentifier(email);
83
+ if (normalizedIdentifier) {
84
+ const identifierMatches = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedIdentifier);
85
+ if (identifierMatches.length > 0) {
86
+ return choosePreferredTokenRow(identifierMatches);
87
+ }
88
+ }
89
+ }
90
+ if (normalizedAccountId || normalizedEmail) {
91
+ const legacyRows = rows.filter((row) => !normalizeAccountIdHint(row.accountId) && !normalizeAccountEmail(row.accountEmail));
92
+ if (legacyRows.length === 1) {
93
+ return choosePreferredTokenRow(legacyRows);
94
+ }
95
+ return;
96
+ }
97
+ return choosePreferredTokenRow(rows);
98
+ }
99
+ function providerTokenRecordToData(row) {
100
+ const expiresAt = hasMeaningfulExpiresAt(row.expiresAt) ? row.expiresAt : null;
101
+ const expiresIn = expiresAt ? Math.max(0, Math.floor((expiresAt.getTime() - Date.now()) / 1000)) : 3600;
102
+ return {
103
+ accessToken: row.accessToken,
104
+ refreshToken: row.refreshToken ?? undefined,
105
+ tokenType: normalizeProviderTokenType(row.tokenType),
106
+ expiresIn,
107
+ expiresAt: expiresAt?.toISOString(),
108
+ scopes: parseScopes(row.scope),
109
+ email: row.accountEmail ?? undefined,
110
+ accountId: row.accountId ?? undefined
111
+ };
112
+ }
113
+ function defaultResolveAccountIdentity(provider, tokenData, emailHint) {
114
+ const accountEmail = normalizeAccountEmail(emailHint ?? tokenData.email ?? null);
115
+ let accountId = normalizeAccountIdHint(tokenData.accountId ?? null);
116
+ if (!accountId && accountEmail) {
117
+ accountId = `${provider}:${accountEmail}`;
118
+ }
119
+ return { accountEmail, accountId };
120
+ }
121
+
122
+ // src/database/trigger-store.ts
123
+ function toIsoString(value) {
124
+ if (!value)
125
+ return null;
126
+ if (value instanceof Date) {
127
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
128
+ }
129
+ const parsed = new Date(value);
130
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
131
+ }
132
+ function toDbSchedule(value) {
133
+ if (value.scheduleType && value.scheduleValue) {
134
+ return {
135
+ scheduleType: value.scheduleType,
136
+ scheduleValue: value.scheduleValue
137
+ };
138
+ }
139
+ if (value.schedule.type === "once") {
140
+ const runAt = toIsoString(value.schedule.runAt);
141
+ if (!runAt) {
142
+ throw new Error("Invalid trigger once schedule");
143
+ }
144
+ return {
145
+ scheduleType: "once",
146
+ scheduleValue: runAt
147
+ };
148
+ }
149
+ return {
150
+ scheduleType: "cron",
151
+ scheduleValue: value.schedule.expression
152
+ };
153
+ }
154
+ function toSdkSchedule(row) {
155
+ if (row.scheduleType === "once") {
156
+ return {
157
+ type: "once",
158
+ runAt: row.scheduleValue
159
+ };
160
+ }
161
+ return {
162
+ type: "cron",
163
+ expression: row.scheduleValue
164
+ };
165
+ }
166
+ function toSdkTrigger(row) {
167
+ return {
168
+ id: row.id,
169
+ userId: row.userId ?? undefined,
170
+ name: row.name ?? undefined,
171
+ description: row.description ?? undefined,
172
+ toolName: row.toolName,
173
+ toolArguments: row.toolArguments ?? {},
174
+ schedule: toSdkSchedule(row),
175
+ status: row.status,
176
+ provider: row.provider ?? undefined,
177
+ createdAt: row.createdAt.toISOString(),
178
+ updatedAt: row.updatedAt.toISOString(),
179
+ lastRunAt: toIsoString(row.lastRunAt) ?? undefined,
180
+ nextRunAt: toIsoString(row.nextRunAt) ?? undefined,
181
+ runCount: row.runCount,
182
+ lastError: row.lastError ?? undefined,
183
+ lastResult: row.lastResult ?? undefined
184
+ };
185
+ }
186
+ function toDbTriggerUpdates(updates) {
187
+ const dbUpdates = {
188
+ updatedAt: new Date
189
+ };
190
+ if (updates.name !== undefined)
191
+ dbUpdates.name = updates.name ?? null;
192
+ if (updates.description !== undefined) {
193
+ dbUpdates.description = updates.description ?? null;
194
+ }
195
+ if (updates.toolArguments !== undefined) {
196
+ dbUpdates.toolArguments = updates.toolArguments;
197
+ }
198
+ if (updates.status !== undefined)
199
+ dbUpdates.status = updates.status;
200
+ if (updates.provider !== undefined)
201
+ dbUpdates.provider = updates.provider ?? null;
202
+ if (updates.lastError !== undefined)
203
+ dbUpdates.lastError = updates.lastError ?? null;
204
+ if (updates.lastResult !== undefined) {
205
+ dbUpdates.lastResult = updates.lastResult ?? null;
206
+ }
207
+ if (updates.lastRunAt !== undefined) {
208
+ dbUpdates.lastRunAt = updates.lastRunAt ? new Date(updates.lastRunAt) : null;
209
+ }
210
+ if (updates.nextRunAt !== undefined) {
211
+ dbUpdates.nextRunAt = updates.nextRunAt ? new Date(updates.nextRunAt) : null;
212
+ }
213
+ if (updates.runCount !== undefined)
214
+ dbUpdates.runCount = updates.runCount;
215
+ if (updates.schedule) {
216
+ if (updates.schedule.type === "once") {
217
+ dbUpdates.scheduleType = "once";
218
+ dbUpdates.scheduleValue = new Date(updates.schedule.runAt).toISOString();
219
+ } else {
220
+ dbUpdates.scheduleType = "cron";
221
+ dbUpdates.scheduleValue = updates.schedule.expression;
222
+ }
223
+ }
224
+ return dbUpdates;
225
+ }
226
+ function flattenedTriggerToCreateInput(triggerData, contextUserId) {
227
+ const schedule = toDbSchedule(triggerData);
228
+ return {
229
+ id: triggerData.id,
230
+ userId: contextUserId ?? triggerData.userId ?? null,
231
+ name: triggerData.name ?? null,
232
+ description: triggerData.description ?? null,
233
+ toolName: triggerData.toolName,
234
+ toolArguments: triggerData.toolArguments ?? {},
235
+ scheduleType: schedule.scheduleType,
236
+ scheduleValue: schedule.scheduleValue,
237
+ status: triggerData.status ?? "active",
238
+ provider: triggerData.provider ?? null,
239
+ nextRunAt: triggerData.nextRunAt ? new Date(triggerData.nextRunAt) : null
240
+ };
241
+ }
242
+
243
+ // src/database/factory.ts
244
+ function log(debug, message, error) {
245
+ if (!debug)
246
+ return;
247
+ if (error !== undefined) {
248
+ console.error(`[Integrate SDK] ${message}`, error);
249
+ return;
250
+ }
251
+ console.log(`[Integrate SDK] ${message}`);
252
+ }
253
+ async function authorizeTriggerRow(row, context, hooks) {
254
+ if (!row)
255
+ return null;
256
+ const repaired = hooks?.authorizeTrigger ? await hooks.authorizeTrigger(row, context) : row;
257
+ if (!repaired)
258
+ return null;
259
+ if (context?.userId && repaired.userId !== context.userId) {
260
+ return null;
261
+ }
262
+ return repaired;
263
+ }
264
+ function createDatabaseAdapterCallbacks(options) {
265
+ const { driver, hooks, debugLogs } = options;
266
+ const getProviderToken = async (provider, email, context) => {
267
+ const userId = context?.userId;
268
+ if (!userId) {
269
+ return;
270
+ }
271
+ const accountEmailHint = normalizeAccountEmailHint(email) ?? normalizeAccountEmailHint(typeof context?.accountEmail === "string" ? context.accountEmail : null);
272
+ const accountIdHint = normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null);
273
+ try {
274
+ const rows = await driver.tokens.listProviderTokens(userId, provider);
275
+ const selectedRow = selectProviderTokenRow(rows, accountEmailHint ?? undefined, accountIdHint ?? undefined);
276
+ if (!selectedRow) {
277
+ return;
278
+ }
279
+ return providerTokenRecordToData(selectedRow);
280
+ } catch (error) {
281
+ log(debugLogs, "Error fetching provider token:", error);
282
+ return;
283
+ }
284
+ };
285
+ const setProviderToken = async (provider, tokenData, email, context) => {
286
+ const userId = context?.userId;
287
+ if (!userId) {
288
+ console.error("[Integrate SDK] Cannot save token: No userId in context");
289
+ return;
290
+ }
291
+ const accountEmail = normalizeAccountEmailHint(email) ?? normalizeAccountEmail(tokenData?.email ?? null);
292
+ if (tokenData === null) {
293
+ try {
294
+ await driver.tokens.deleteProviderTokens({
295
+ userId,
296
+ provider,
297
+ accountEmail,
298
+ accountId: normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null)
299
+ });
300
+ await hooks?.onTokenChange?.({ userId, provider, action: "remove" });
301
+ } catch (error) {
302
+ log(debugLogs, "Error deleting provider token:", error);
303
+ throw error;
304
+ }
305
+ return;
306
+ }
307
+ try {
308
+ const resolvedIdentity = hooks?.resolveAccountIdentity ? await hooks.resolveAccountIdentity(provider, tokenData, accountEmail, context) : defaultResolveAccountIdentity(provider, tokenData, accountEmail);
309
+ const resolvedAccountEmail = resolvedIdentity.accountEmail;
310
+ const resolvedAccountId = normalizeAccountIdHint(resolvedIdentity.accountId) ?? normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null) ?? null;
311
+ const rows = await driver.tokens.listProviderTokens(userId, provider);
312
+ let existing = selectProviderTokenRow(rows, resolvedAccountEmail ?? accountEmail ?? undefined, resolvedAccountId ?? undefined) ?? rows.find((row) => {
313
+ const sameEmail = resolvedAccountEmail && normalizeAccountEmail(row.accountEmail) === resolvedAccountEmail;
314
+ const sameAccountId = resolvedAccountId && normalizeAccountIdHint(row.accountId) === resolvedAccountId;
315
+ return Boolean(sameEmail || sameAccountId);
316
+ }) ?? (rows.length === 1 ? rows[0] : undefined);
317
+ const parsedExpiresAt = tokenData.expiresAt ? new Date(tokenData.expiresAt) : null;
318
+ const expiresAt = hasMeaningfulExpiresAt(parsedExpiresAt) ? parsedExpiresAt : null;
319
+ const scope = tokenData.scopes?.join(" ") ?? null;
320
+ const saved = await driver.tokens.upsertProviderToken({
321
+ existingId: existing?.id,
322
+ id: existing?.id ?? `${userId}-${provider}-${resolvedAccountEmail ?? "default"}-${Date.now()}`,
323
+ userId,
324
+ provider,
325
+ accountEmail: resolvedAccountEmail,
326
+ accountId: resolvedAccountId,
327
+ accessToken: tokenData.accessToken,
328
+ refreshToken: tokenData.refreshToken ?? null,
329
+ tokenType: normalizeProviderTokenType(tokenData.tokenType),
330
+ expiresAt,
331
+ scope
332
+ });
333
+ await driver.tokens.deleteDuplicateProviderTokens({
334
+ keepId: saved.id,
335
+ userId,
336
+ provider,
337
+ accountEmail: resolvedAccountEmail,
338
+ accountId: resolvedAccountId
339
+ });
340
+ await hooks?.onTokenChange?.({ userId, provider, action: "set" });
341
+ } catch (error) {
342
+ log(debugLogs, "Error saving provider token:", error);
343
+ throw error;
344
+ }
345
+ };
346
+ const removeProviderToken = async (provider, email, context) => {
347
+ const userId = context?.userId;
348
+ if (!userId) {
349
+ console.error("[Integrate SDK] Cannot delete token: No userId in context");
350
+ return;
351
+ }
352
+ try {
353
+ await driver.tokens.deleteProviderTokens({
354
+ userId,
355
+ provider,
356
+ accountEmail: normalizeAccountEmail(email)
357
+ });
358
+ await hooks?.onTokenChange?.({ userId, provider, action: "remove" });
359
+ } catch (error) {
360
+ log(debugLogs, "Error deleting provider token:", error);
361
+ throw error;
362
+ }
363
+ };
364
+ const callbacks = {
365
+ getProviderToken,
366
+ setProviderToken,
367
+ removeProviderToken
368
+ };
369
+ if (driver.triggers) {
370
+ const triggerDriver = driver.triggers;
371
+ const triggers = {
372
+ create: async (triggerData, context) => {
373
+ try {
374
+ const created = await triggerDriver.createTrigger(flattenedTriggerToCreateInput(triggerData, context?.userId));
375
+ return toSdkTrigger(created);
376
+ } catch (error) {
377
+ log(debugLogs, "Error creating trigger:", error);
378
+ throw error;
379
+ }
380
+ },
381
+ get: async (triggerId, context) => {
382
+ try {
383
+ const found = await triggerDriver.getTriggerById(triggerId);
384
+ const authorized = await authorizeTriggerRow(found, context, hooks);
385
+ return authorized ? toSdkTrigger(authorized) : null;
386
+ } catch (error) {
387
+ log(debugLogs, "Error getting trigger:", error);
388
+ throw error;
389
+ }
390
+ },
391
+ list: async (params, context) => {
392
+ try {
393
+ const { rows, total } = await triggerDriver.listTriggers({
394
+ userId: context?.userId,
395
+ status: params.status,
396
+ toolName: params.toolName,
397
+ limit: params.limit ?? 20,
398
+ offset: params.offset ?? 0
399
+ });
400
+ const triggers2 = [];
401
+ for (const row of rows) {
402
+ const authorized = await authorizeTriggerRow(row, context, hooks);
403
+ if (authorized) {
404
+ triggers2.push(toSdkTrigger(authorized));
405
+ }
406
+ }
407
+ return { triggers: triggers2, total };
408
+ } catch (error) {
409
+ log(debugLogs, "Error listing triggers:", error);
410
+ throw error;
411
+ }
412
+ },
413
+ update: async (triggerId, updates, context) => {
414
+ try {
415
+ const existing = await triggerDriver.getTriggerById(triggerId);
416
+ const authorized = await authorizeTriggerRow(existing, context, hooks);
417
+ if (!authorized) {
418
+ throw new Error(`Trigger not found: ${triggerId}`);
419
+ }
420
+ const updated = await triggerDriver.updateTrigger(authorized.id, toDbTriggerUpdates(updates));
421
+ if (!updated) {
422
+ throw new Error(`Trigger not found: ${triggerId}`);
423
+ }
424
+ return toSdkTrigger(updated);
425
+ } catch (error) {
426
+ log(debugLogs, "Error updating trigger:", error);
427
+ throw error;
428
+ }
429
+ },
430
+ delete: async (triggerId, context) => {
431
+ try {
432
+ const existing = await triggerDriver.getTriggerById(triggerId);
433
+ const authorized = await authorizeTriggerRow(existing, context, hooks);
434
+ if (!authorized) {
435
+ return;
436
+ }
437
+ await triggerDriver.deleteTrigger(authorized.id);
438
+ } catch (error) {
439
+ log(debugLogs, "Error deleting trigger:", error);
440
+ throw error;
441
+ }
442
+ }
443
+ };
444
+ callbacks.triggers = triggers;
445
+ }
446
+ return callbacks;
447
+ }
448
+ function createDatabaseAdapterFactory(createDriver, options) {
449
+ return () => createDatabaseAdapterCallbacks({
450
+ driver: createDriver(),
451
+ hooks: options?.hooks,
452
+ debugLogs: options?.debugLogs
453
+ });
454
+ }
455
+
456
+ // src/database/adapters/mongodb.ts
457
+ var DEFAULT_COLLECTIONS = {
458
+ providerTokens: "provider_tokens",
459
+ triggers: "triggers"
460
+ };
461
+ function mapProviderTokenDoc(doc) {
462
+ return {
463
+ id: String(doc.id),
464
+ userId: String(doc.userId),
465
+ provider: String(doc.provider),
466
+ accountEmail: doc.accountEmail ?? null,
467
+ accountId: doc.accountId ?? null,
468
+ accessToken: String(doc.accessToken),
469
+ refreshToken: doc.refreshToken ?? null,
470
+ tokenType: String(doc.tokenType ?? "Bearer"),
471
+ expiresAt: doc.expiresAt ? new Date(doc.expiresAt) : null,
472
+ scope: doc.scope ?? null,
473
+ createdAt: new Date(doc.createdAt),
474
+ updatedAt: new Date(doc.updatedAt)
475
+ };
476
+ }
477
+ function mapTriggerDoc(doc) {
478
+ return {
479
+ id: String(doc.id),
480
+ userId: doc.userId ?? null,
481
+ name: doc.name ?? null,
482
+ description: doc.description ?? null,
483
+ toolName: String(doc.toolName),
484
+ toolArguments: doc.toolArguments ?? {},
485
+ scheduleType: doc.scheduleType,
486
+ scheduleValue: String(doc.scheduleValue),
487
+ status: String(doc.status),
488
+ provider: doc.provider ?? null,
489
+ lastRunAt: doc.lastRunAt ? new Date(doc.lastRunAt) : null,
490
+ nextRunAt: doc.nextRunAt ? new Date(doc.nextRunAt) : null,
491
+ runCount: Number(doc.runCount ?? 0),
492
+ lastError: doc.lastError ?? null,
493
+ lastResult: doc.lastResult ?? null,
494
+ createdAt: new Date(doc.createdAt),
495
+ updatedAt: new Date(doc.updatedAt)
496
+ };
497
+ }
498
+ function createMongoTokenDriver(db, collectionName) {
499
+ const collection = () => db.collection(collectionName);
500
+ return {
501
+ async listProviderTokens(userId, provider) {
502
+ const docs = await collection().find({ userId, provider }).sort({ updatedAt: -1 }).limit(32).toArray();
503
+ return docs.map((doc) => mapProviderTokenDoc(doc));
504
+ },
505
+ async upsertProviderToken(input) {
506
+ const now = new Date;
507
+ const id = input.existingId ?? input.id;
508
+ const doc = {
509
+ id,
510
+ userId: input.userId,
511
+ provider: input.provider,
512
+ accountEmail: input.accountEmail,
513
+ accountId: input.accountId,
514
+ accessToken: input.accessToken,
515
+ refreshToken: input.refreshToken,
516
+ tokenType: input.tokenType,
517
+ expiresAt: input.expiresAt,
518
+ scope: input.scope,
519
+ updatedAt: now,
520
+ ...input.existingId ? {} : { createdAt: now }
521
+ };
522
+ await collection().updateOne({ id }, { $set: doc }, { upsert: true });
523
+ const saved = await collection().findOne({ id });
524
+ return mapProviderTokenDoc(saved);
525
+ },
526
+ async deleteProviderTokens(input) {
527
+ const filter = {
528
+ userId: input.userId,
529
+ provider: input.provider
530
+ };
531
+ if (input.accountEmail) {
532
+ filter.accountEmail = input.accountEmail;
533
+ } else if (input.accountId) {
534
+ filter.accountId = input.accountId;
535
+ }
536
+ await collection().deleteMany(filter);
537
+ },
538
+ async deleteDuplicateProviderTokens(input) {
539
+ const normalizedEmail = normalizeAccountEmail(input.accountEmail);
540
+ const normalizedAccountId = normalizeAccountIdHint(input.accountId);
541
+ if (!normalizedEmail && !normalizedAccountId) {
542
+ return;
543
+ }
544
+ const orConditions = [];
545
+ if (normalizedEmail) {
546
+ orConditions.push({ accountEmail: normalizedEmail });
547
+ }
548
+ if (normalizedAccountId) {
549
+ orConditions.push({ accountId: normalizedAccountId });
550
+ }
551
+ await collection().deleteMany({
552
+ userId: input.userId,
553
+ provider: input.provider,
554
+ id: { $ne: input.keepId },
555
+ $or: orConditions
556
+ });
557
+ }
558
+ };
559
+ }
560
+ function createMongoTriggerDriver(db, collectionName) {
561
+ const collection = () => db.collection(collectionName);
562
+ return {
563
+ async createTrigger(input) {
564
+ const now = new Date;
565
+ const doc = {
566
+ id: input.id,
567
+ userId: input.userId,
568
+ name: input.name ?? null,
569
+ description: input.description ?? null,
570
+ toolName: input.toolName,
571
+ toolArguments: input.toolArguments,
572
+ scheduleType: input.scheduleType,
573
+ scheduleValue: input.scheduleValue,
574
+ status: input.status,
575
+ provider: input.provider ?? null,
576
+ nextRunAt: input.nextRunAt ?? null,
577
+ createdAt: now,
578
+ updatedAt: now
579
+ };
580
+ await collection().insertOne(doc);
581
+ return mapTriggerDoc(doc);
582
+ },
583
+ async getTriggerById(triggerId) {
584
+ const found = await collection().findOne({ id: triggerId });
585
+ return found ? mapTriggerDoc(found) : null;
586
+ },
587
+ async listTriggers(query) {
588
+ const filter = {};
589
+ if (query.userId)
590
+ filter.userId = query.userId;
591
+ if (query.status)
592
+ filter.status = query.status;
593
+ if (query.toolName)
594
+ filter.toolName = query.toolName;
595
+ const [docs, total] = await Promise.all([
596
+ collection().find(filter).sort({ updatedAt: -1 }).skip(query.offset).limit(query.limit).toArray(),
597
+ collection().countDocuments(filter)
598
+ ]);
599
+ return {
600
+ rows: docs.map((doc) => mapTriggerDoc(doc)),
601
+ total
602
+ };
603
+ },
604
+ async updateTrigger(triggerId, updates) {
605
+ const result = await collection().findOneAndUpdate({ id: triggerId }, { $set: updates }, { returnDocument: "after" });
606
+ return result ? mapTriggerDoc(result) : null;
607
+ },
608
+ async deleteTrigger(triggerId) {
609
+ await collection().deleteOne({ id: triggerId });
610
+ }
611
+ };
612
+ }
613
+ function createMongoDatabaseDriver(db, config) {
614
+ const names = {
615
+ ...DEFAULT_COLLECTIONS,
616
+ ...config.collectionNames
617
+ };
618
+ const driver = {
619
+ tokens: createMongoTokenDriver(db, names.providerTokens)
620
+ };
621
+ if (config.collectionNames?.triggers !== null) {
622
+ driver.triggers = createMongoTriggerDriver(db, names.triggers);
623
+ }
624
+ return driver;
625
+ }
626
+ function mongodbAdapter(db, config = {}) {
627
+ return createDatabaseAdapterFactory(() => createMongoDatabaseDriver(db, config), {
628
+ hooks: config.hooks,
629
+ debugLogs: config.debugLogs
630
+ });
631
+ }
632
+ function mongodbAdapterCallbacks(db, config = {}) {
633
+ return createDatabaseAdapterCallbacks({
634
+ driver: createMongoDatabaseDriver(db, config),
635
+ hooks: config.hooks,
636
+ debugLogs: config.debugLogs
637
+ });
638
+ }
639
+ export {
640
+ mongodbAdapterCallbacks,
641
+ mongodbAdapter,
642
+ createMongoDatabaseDriver
643
+ };
@@ -0,0 +1,18 @@
1
+ import type { DatabaseDriver, IntegrateAdapterHooks, IntegrateDatabaseAdapter } from "../types.js";
2
+ export type PrismaProvider = "sqlite" | "postgresql" | "mysql" | "sqlserver" | "cockroachdb" | "mongodb";
3
+ export interface PrismaIntegrateModelNames {
4
+ providerToken?: string;
5
+ trigger?: string;
6
+ }
7
+ export interface PrismaAdapterConfig {
8
+ provider: PrismaProvider;
9
+ modelNames?: PrismaIntegrateModelNames;
10
+ hooks?: IntegrateAdapterHooks;
11
+ debugLogs?: boolean;
12
+ }
13
+ type PrismaClientLike = Record<string, any>;
14
+ export declare function createPrismaDatabaseDriver(prisma: PrismaClientLike, config: PrismaAdapterConfig): DatabaseDriver;
15
+ export declare function prismaAdapter(prisma: PrismaClientLike, config: PrismaAdapterConfig): IntegrateDatabaseAdapter;
16
+ export declare function prismaAdapterCallbacks(prisma: PrismaClientLike, config: PrismaAdapterConfig): import("../types.js").IntegrateDatabaseCallbacks;
17
+ export {};
18
+ //# sourceMappingURL=prisma.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma.d.ts","sourceRoot":"","sources":["../../../../src/database/adapters/prisma.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,cAAc,EAGd,qBAAqB,EACrB,wBAAwB,EAMzB,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,cAAc,GACtB,QAAQ,GACR,YAAY,GACZ,OAAO,GACP,WAAW,GACX,aAAa,GACb,SAAS,CAAC;AAEd,MAAM,WAAW,yBAAyB;IACxC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,cAAc,CAAC;IACzB,UAAU,CAAC,EAAE,yBAAyB,CAAC;IACvC,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,KAAK,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAiO5C,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,mBAAmB,GAC1B,cAAc,CAehB;AAED,wBAAgB,aAAa,CAC3B,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,mBAAmB,GAC1B,wBAAwB,CAS1B;AAED,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,mBAAmB,oDAO5B"}