notifkit 0.1.14 → 0.1.16

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/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
  2. package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
  3. package/dashboard/dist/index.html +2 -2
  4. package/dist/{bootstrap-m107TukN.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
  5. package/dist/{bulk-xAd_biYV.mjs → bulk-CJ5QXiPa.mjs} +1 -1
  6. package/dist/index.d.mts +71 -27
  7. package/dist/index.mjs +2 -2
  8. package/dist/{main-CWIBUEc7.mjs → main-6_bXQBDH.mjs} +21 -41
  9. package/dist/{main-WkxXwP5q.mjs → main-8nP3qmCT.mjs} +29 -49
  10. package/dist/{main-HT5c6jyf.mjs → main-B82bsFoy.mjs} +183 -334
  11. package/dist/{main-C87TSAqM.mjs → main-CpaHF1Zw.mjs} +13 -15
  12. package/dist/{main-DRHL2bst.mjs → main-DULD8-th.mjs} +8 -6
  13. package/dist/{main-D_62f9fH.mjs → main-ZW5RaiOK.mjs} +77 -64
  14. package/dist/{main-5kVwbbnW.mjs → main-g1KEcXXp.mjs} +676 -582
  15. package/dist/{main-C0MjK1Au.mjs → main-mGIT8jv4.mjs} +4 -4
  16. package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
  17. package/dist/{src-DYqdD694.mjs → src-BE_EUpZ6.mjs} +93 -93
  18. package/package.json +1 -1
  19. package/scripts/create-admin.mjs +0 -0
  20. package/scripts/create-project.mjs +6 -2
  21. package/scripts/migrate.mjs +0 -0
  22. package/scripts/notifkit.mjs +0 -0
  23. package/src/client.ts +3 -3
  24. package/src/config/index.ts +1 -0
  25. package/src/contracts/common.ts +2 -0
  26. package/src/contracts/envelope.ts +1 -1
  27. package/src/contracts/events/notification-created.ts +2 -0
  28. package/src/contracts/events/notification-delivered.ts +1 -1
  29. package/src/contracts/events/notification-failed.ts +1 -1
  30. package/src/contracts/events/notification-requested.ts +3 -2
  31. package/src/contracts/helpers.ts +1 -2
  32. package/src/contracts/index.ts +1 -0
  33. package/src/contracts/registry.ts +1 -0
  34. package/src/contracts/sdk.ts +8 -37
  35. package/src/db/schema.ts +8 -13
  36. package/src/idempotency/index.ts +6 -8
  37. package/src/metrics/index.ts +2 -0
  38. package/src/rate-limiter/api-rate-limiter.ts +208 -0
  39. package/src/rate-limiter/index.ts +3 -411
  40. package/src/rate-limiter/project-settings-cache.ts +99 -0
  41. package/src/rate-limiter/user-throttle.ts +100 -0
  42. package/src/redis/index.ts +10 -3
  43. package/src/repositories/admin-user.ts +83 -0
  44. package/src/repositories/contact.ts +359 -0
  45. package/src/repositories/index.ts +9 -1416
  46. package/src/repositories/preference.ts +35 -0
  47. package/src/repositories/project.ts +110 -0
  48. package/src/repositories/segment.ts +16 -0
  49. package/src/repositories/template.ts +72 -0
  50. package/src/repositories/types.ts +49 -0
  51. package/src/repositories/user.ts +644 -0
  52. package/src/repositories/workflow.ts +64 -0
  53. package/src/services/ai/main.ts +29 -71
  54. package/src/services/api/admin-static.ts +4 -1
  55. package/src/services/api/handlers/auth.ts +109 -0
  56. package/src/services/api/handlers/campaigns.ts +191 -0
  57. package/src/services/api/handlers/events.ts +99 -0
  58. package/src/services/api/handlers/notifications.ts +356 -0
  59. package/src/services/api/handlers/projects.ts +116 -0
  60. package/src/services/api/handlers/shared.ts +262 -0
  61. package/src/services/api/handlers/suppressions.ts +95 -0
  62. package/src/services/api/handlers/system.ts +314 -0
  63. package/src/services/api/handlers/templates.ts +97 -0
  64. package/src/services/api/handlers/unsubscribe.ts +215 -0
  65. package/src/services/api/handlers/users.ts +262 -0
  66. package/src/services/api/handlers/workflows.ts +150 -0
  67. package/src/services/api/handlers.ts +25 -2190
  68. package/src/services/api/health.ts +133 -0
  69. package/src/services/api/http.ts +12 -0
  70. package/src/services/api/main.ts +32 -322
  71. package/src/services/api/router.ts +1 -1
  72. package/src/services/api/webhooks.ts +172 -0
  73. package/src/services/delivery/main.ts +256 -498
  74. package/src/services/engine/main.ts +31 -235
  75. package/src/services/engine/quiet-hours.ts +151 -0
  76. package/src/services/engine/schedule-or-dispatch.ts +104 -0
  77. package/src/services/enricher/main.ts +9 -21
  78. package/src/services/events/main.ts +2 -2
  79. package/src/services/scheduler/main.ts +16 -25
  80. package/src/services/workflow/duration.ts +24 -0
  81. package/src/services/workflow/main.ts +6 -164
  82. package/src/services/workflow/timers.ts +157 -0
  83. package/src/shared/events.ts +3 -2
  84. package/src/templates/render.ts +1 -0
  85. package/src/workers/index.ts +7 -4
  86. package/src/workflows/sdk.ts +1 -0
  87. package/dashboard/README.md +0 -29
  88. package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
  89. package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
@@ -1,1416 +1,9 @@
1
- import { eq, and, or, sql as drizzleSql, inArray, desc } from "drizzle-orm";
2
- import { LRUCache } from "@/shared/index.js";
3
- import type { Db } from "@/index.js";
4
- import type { Preferences, ContactChannel } from "@/contracts/index.js";
5
- import {
6
- users,
7
- userSegments,
8
- userContacts,
9
- userChannelPreferences,
10
- userTopicPreferences,
11
- contactTopicPreferences,
12
- quietHours,
13
- templates,
14
- projects,
15
- workflowInstances,
16
- workflowSteps,
17
- workflowWaiters,
18
- workflowDefinitions,
19
- projectApiKeys,
20
- suppressions,
21
- messageLogs,
22
- adminUsers,
23
- } from "@/db/schema.js";
24
-
25
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
26
-
27
- /**
28
- * Applied when a profile is read, not when it is written: an upsert that
29
- * leaves a field out must keep the stored value rather than reset it.
30
- */
31
- const DEFAULT_LANGUAGE = "en";
32
- const DEFAULT_TIMEZONE = "UTC";
33
-
34
- // ─── Domain types ───────────────────────────────────────────────────────────
35
-
36
- export interface UserProfile {
37
- userId: string; // Maps to externalId
38
- language?: string;
39
- timezone?: string;
40
- email?: string | null;
41
- }
42
-
43
- export interface UserRecord extends UserProfile {
44
- segments: string[];
45
- preferences: Preferences;
46
- }
47
-
48
- export interface UserContact {
49
- id: string; // uuid
50
- userId: string; // externalId
51
- channel: ContactChannel;
52
- target: string;
53
- preferences: Preferences;
54
- active: boolean;
55
- }
56
-
57
- export interface TemplateRecord {
58
- id: string;
59
- channel: string;
60
- topics: string[];
61
- content: unknown;
62
- /** Template-level AI prompts, merged with per-request ones by the engine. */
63
- aiPrompts?: Record<string, string> | null;
64
- }
65
-
66
- export type DevicePlatform = "fcm" | "apns" | "web";
67
-
68
- export interface DeviceToken {
69
- id: string;
70
- userId: string;
71
- deviceToken: string;
72
- platform: DevicePlatform;
73
- active: boolean;
74
- }
75
-
76
- export interface NotificationPreference {
77
- userId: string;
78
- eventType: string;
79
- optedIn: boolean;
80
- }
81
-
82
- // ─── UserRepository ─────────────────────────────────────────────────────────
83
-
84
- export class UserRepository {
85
- private readonly recordCache = new LRUCache<string, UserRecord>(5000, 30_000);
86
-
87
- constructor(private readonly db: Db) {}
88
-
89
- async findById(projectId: string, userId: string): Promise<UserProfile | null> {
90
- const rows = await this.db
91
- .select()
92
- .from(users)
93
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)))
94
- .limit(1);
95
-
96
- if (!rows[0]) return null;
97
- const attrs = rows[0].attributes as any;
98
- return {
99
- userId: rows[0].externalId,
100
- language: attrs.language ?? DEFAULT_LANGUAGE,
101
- timezone: attrs.timezone ?? DEFAULT_TIMEZONE,
102
- email: attrs.email,
103
- };
104
- }
105
-
106
- async findRecordById(projectId: string, userId: string): Promise<UserRecord | null> {
107
- const cacheKey = `${projectId}:${userId}`;
108
- const cached = this.recordCache.get(cacheKey);
109
- if (cached !== undefined) return cached;
110
-
111
- const records = await this.findRecordsByIds(projectId, [userId]);
112
- return records[0] ?? null;
113
- }
114
-
115
- async findRecordsByIds(projectId: string, userIds: string[]): Promise<UserRecord[]> {
116
- if (userIds.length === 0) return [];
117
-
118
- const results: UserRecord[] = [];
119
- const missingIds: string[] = [];
120
-
121
- for (const id of userIds) {
122
- const cacheKey = `${projectId}:${id}`;
123
- const cached = this.recordCache.get(cacheKey);
124
- if (cached !== undefined) {
125
- results.push(cached);
126
- } else {
127
- missingIds.push(id);
128
- }
129
- }
130
-
131
- if (missingIds.length === 0) {
132
- return results;
133
- }
134
-
135
- const usersRows = await this.db
136
- .select()
137
- .from(users)
138
- .where(and(inArray(users.externalId, missingIds), eq(users.projectId, projectId)));
139
-
140
- if (usersRows.length === 0) return results;
141
-
142
- const internalIds = usersRows.map((r) => r.id);
143
-
144
- const [segmentRows, topicRows, channelRows, qhRows] = await Promise.all([
145
- this.db.select().from(userSegments).where(inArray(userSegments.userId, internalIds)),
146
- this.db
147
- .select()
148
- .from(userTopicPreferences)
149
- .where(inArray(userTopicPreferences.userId, internalIds)),
150
- this.db
151
- .select()
152
- .from(userChannelPreferences)
153
- .where(inArray(userChannelPreferences.userId, internalIds)),
154
- this.db.select().from(quietHours).where(inArray(quietHours.userId, internalIds)),
155
- ]);
156
-
157
- const segmentsByUserId = new Map<string, string[]>();
158
- for (const r of segmentRows) {
159
- if (!segmentsByUserId.has(r.userId)) segmentsByUserId.set(r.userId, []);
160
- segmentsByUserId.get(r.userId)!.push(r.segment);
161
- }
162
-
163
- const topicsByUserId = new Map<string, Record<string, boolean>>();
164
- for (const r of topicRows) {
165
- if (!topicsByUserId.has(r.userId)) topicsByUserId.set(r.userId, {});
166
- topicsByUserId.get(r.userId)![r.topic] = r.enabled;
167
- }
168
-
169
- const channelsByUserId = new Map<string, Record<string, boolean>>();
170
- for (const r of channelRows) {
171
- if (!channelsByUserId.has(r.userId)) channelsByUserId.set(r.userId, {});
172
- channelsByUserId.get(r.userId)![r.channel] = r.enabled;
173
- }
174
-
175
- const qhByUserId = new Map<string, any[]>();
176
- for (const r of qhRows) {
177
- if (r.userId == null) continue;
178
- if (!qhByUserId.has(r.userId)) qhByUserId.set(r.userId, []);
179
- qhByUserId
180
- .get(r.userId)!
181
- .push({ start: r.startTime.slice(0, 5), end: r.endTime.slice(0, 5) });
182
- }
183
-
184
- for (const userRow of usersRows) {
185
- const attrs = userRow.attributes as any;
186
- const internalId = userRow.id;
187
-
188
- const record: UserRecord = {
189
- userId: userRow.externalId,
190
- language: attrs.language ?? DEFAULT_LANGUAGE,
191
- timezone: attrs.timezone ?? DEFAULT_TIMEZONE,
192
- email: attrs.email,
193
- segments: segmentsByUserId.get(internalId) || [],
194
- preferences: {
195
- channels: channelsByUserId.get(internalId) || {},
196
- topics: topicsByUserId.get(internalId) || {},
197
- quietHours: qhByUserId.get(internalId),
198
- },
199
- };
200
-
201
- this.recordCache.set(`${projectId}:${record.userId}`, record);
202
- results.push(record);
203
- }
204
-
205
- return results;
206
- }
207
-
208
- async upsertFull(
209
- projectId: string,
210
- user: {
211
- userId: string;
212
- language?: string;
213
- timezone?: string;
214
- email?: string | null;
215
- segments: string[];
216
- preferences: Preferences;
217
- },
218
- ): Promise<void> {
219
- await this.db.transaction(async (tx) => {
220
- await tx
221
- .insert(users)
222
- .values({
223
- projectId,
224
- externalId: user.userId,
225
- attributes: {
226
- language: user.language,
227
- timezone: user.timezone,
228
- email: user.email,
229
- },
230
- })
231
- .onConflictDoUpdate({
232
- target: [users.projectId, users.externalId],
233
- set: {
234
- attributes: {
235
- language: user.language,
236
- timezone: user.timezone,
237
- email: user.email,
238
- },
239
- updatedAt: new Date(),
240
- },
241
- });
242
-
243
- const internalIdRows = await tx
244
- .select({ id: users.id })
245
- .from(users)
246
- .where(and(eq(users.externalId, user.userId), eq(users.projectId, projectId)));
247
- const internalId = internalIdRows[0]?.id;
248
- if (!internalId) return;
249
-
250
- if (user.segments && user.segments.length > 0) {
251
- await tx
252
- .insert(userSegments)
253
- .values(user.segments.map((s) => ({ userId: internalId, segment: s })))
254
- .onConflictDoNothing();
255
- }
256
-
257
- if (user.preferences && user.preferences.topics) {
258
- const topicInserts = Object.entries(user.preferences.topics).map(([topic, enabled]) => ({
259
- userId: internalId,
260
- topic,
261
- enabled,
262
- }));
263
- if (topicInserts.length > 0) {
264
- await tx
265
- .insert(userTopicPreferences)
266
- .values(topicInserts)
267
- .onConflictDoUpdate({
268
- target: [userTopicPreferences.userId, userTopicPreferences.topic],
269
- set: { enabled: drizzleSql`excluded.enabled` },
270
- });
271
- }
272
- }
273
-
274
- if (user.preferences?.channels) {
275
- const channelInserts = Object.entries(user.preferences.channels).map(
276
- ([channel, enabled]) => ({
277
- userId: internalId,
278
- channel: channel as ContactChannel,
279
- enabled,
280
- }),
281
- );
282
- if (channelInserts.length > 0) {
283
- await tx
284
- .insert(userChannelPreferences)
285
- .values(channelInserts)
286
- .onConflictDoUpdate({
287
- target: [userChannelPreferences.userId, userChannelPreferences.channel],
288
- set: { enabled: drizzleSql`excluded.enabled` },
289
- });
290
- }
291
- }
292
-
293
- if (user.preferences?.quietHours !== undefined) {
294
- await tx.delete(quietHours).where(eq(quietHours.userId, internalId));
295
- if (user.preferences.quietHours.length > 0) {
296
- await tx.insert(quietHours).values(
297
- user.preferences.quietHours.map((window) => ({
298
- userId: internalId,
299
- startTime: window.start,
300
- endTime: window.end,
301
- })),
302
- );
303
- }
304
- }
305
- });
306
- this.recordCache.delete(`${projectId}:${user.userId}`);
307
- }
308
-
309
- async upsertManyFull(
310
- projectId: string,
311
- usersList: Array<{
312
- userId: string;
313
- language?: string;
314
- timezone?: string;
315
- email?: string | null;
316
- segments: string[];
317
- preferences: Preferences;
318
- }>,
319
- ): Promise<void> {
320
- if (usersList.length === 0) return;
321
-
322
- // ON CONFLICT DO UPDATE rejects the whole statement when two proposed rows
323
- // hit the same key, so an import naming one user twice failed outright.
324
- // The last occurrence wins, as it would had they been sent one by one.
325
- const uniqueUsers = [...new Map(usersList.map((u) => [u.userId, u])).values()];
326
- const winners = new Set(uniqueUsers);
327
-
328
- let attempts = 0;
329
- while (attempts < 3) {
330
- try {
331
- await this.db.transaction(async (tx) => {
332
- await tx
333
- .insert(users)
334
- .values(
335
- uniqueUsers.map((u) => ({
336
- projectId,
337
- externalId: u.userId,
338
- attributes: {
339
- language: u.language,
340
- timezone: u.timezone,
341
- email: u.email,
342
- },
343
- })),
344
- )
345
- .onConflictDoUpdate({
346
- target: [users.projectId, users.externalId],
347
- set: {
348
- // Merged, not replaced: a field the caller left out (absent
349
- // from the JSON) keeps its stored value.
350
- attributes: drizzleSql`${users.attributes} || excluded.attributes`,
351
- updatedAt: new Date(),
352
- },
353
- });
354
-
355
- const internalIdRows = await tx
356
- .select({ id: users.id, externalId: users.externalId })
357
- .from(users)
358
- .where(
359
- and(
360
- inArray(
361
- users.externalId,
362
- usersList.map((u) => u.userId),
363
- ),
364
- eq(users.projectId, projectId),
365
- ),
366
- );
367
-
368
- const idMap = new Map(internalIdRows.map((r) => [r.externalId, r.id]));
369
-
370
- const segmentInserts: any[] = [];
371
- const topicInserts: any[] = [];
372
- const channelInserts: any[] = [];
373
- const quietHoursInserts: any[] = [];
374
-
375
- for (const u of usersList) {
376
- const internalId = idMap.get(u.userId);
377
- if (!internalId) continue;
378
-
379
- if (u.segments && u.segments.length > 0) {
380
- for (const s of u.segments) {
381
- segmentInserts.push({ userId: internalId, segment: s });
382
- }
383
- }
384
-
385
- if (u.preferences?.topics) {
386
- for (const [topic, enabled] of Object.entries(u.preferences.topics)) {
387
- topicInserts.push({ userId: internalId, topic, enabled });
388
- }
389
- }
390
-
391
- if (u.preferences?.channels) {
392
- for (const [channel, enabled] of Object.entries(u.preferences.channels)) {
393
- channelInserts.push({
394
- userId: internalId,
395
- channel: channel as ContactChannel,
396
- enabled,
397
- });
398
- }
399
- }
400
-
401
- // Quiet hours are replaced, not merged, so only the winning row counts.
402
- if (
403
- winners.has(u) &&
404
- u.preferences?.quietHours &&
405
- u.preferences.quietHours.length > 0
406
- ) {
407
- for (const window of u.preferences.quietHours) {
408
- quietHoursInserts.push({
409
- userId: internalId,
410
- startTime: window.start,
411
- endTime: window.end,
412
- });
413
- }
414
- }
415
- }
416
-
417
- const segmentSet = new Set<string>();
418
- const dedupedSegmentInserts: any[] = [];
419
- for (const s of segmentInserts) {
420
- const key = `${s.userId}:${s.segment}`;
421
- if (!segmentSet.has(key)) {
422
- segmentSet.add(key);
423
- dedupedSegmentInserts.push(s);
424
- }
425
- }
426
-
427
- const topicMap = new Map<string, any>();
428
- for (const t of topicInserts) {
429
- topicMap.set(`${t.userId}:${t.topic}`, t);
430
- }
431
- const dedupedTopicInserts = Array.from(topicMap.values());
432
-
433
- const channelMap = new Map<string, any>();
434
- for (const c of channelInserts) {
435
- channelMap.set(`${c.userId}:${c.channel}`, c);
436
- }
437
- const dedupedChannelInserts = Array.from(channelMap.values());
438
-
439
- if (dedupedSegmentInserts.length > 0) {
440
- await tx.insert(userSegments).values(dedupedSegmentInserts).onConflictDoNothing();
441
- }
442
-
443
- if (dedupedTopicInserts.length > 0) {
444
- await tx
445
- .insert(userTopicPreferences)
446
- .values(dedupedTopicInserts)
447
- .onConflictDoUpdate({
448
- target: [userTopicPreferences.userId, userTopicPreferences.topic],
449
- set: { enabled: drizzleSql`excluded.enabled` },
450
- });
451
- }
452
-
453
- if (dedupedChannelInserts.length > 0) {
454
- await tx
455
- .insert(userChannelPreferences)
456
- .values(dedupedChannelInserts)
457
- .onConflictDoUpdate({
458
- target: [userChannelPreferences.userId, userChannelPreferences.channel],
459
- set: { enabled: drizzleSql`excluded.enabled` },
460
- });
461
- }
462
-
463
- const usersWithQuietHours = uniqueUsers.filter(
464
- (u) => u.preferences?.quietHours !== undefined,
465
- );
466
- const internalIdsToClearQuietHours = usersWithQuietHours
467
- .map((u) => idMap.get(u.userId))
468
- .filter(Boolean) as string[];
469
-
470
- if (internalIdsToClearQuietHours.length > 0) {
471
- await tx
472
- .delete(quietHours)
473
- .where(inArray(quietHours.userId, internalIdsToClearQuietHours));
474
- }
475
- if (quietHoursInserts.length > 0) {
476
- await tx.insert(quietHours).values(quietHoursInserts);
477
- }
478
- });
479
- for (const u of usersList) {
480
- this.recordCache.delete(`${projectId}:${u.userId}`);
481
- }
482
- return;
483
- } catch (err: any) {
484
- attempts++;
485
- if (attempts >= 3 || (err.code !== "40001" && err.code !== "40P01")) {
486
- throw err;
487
- }
488
- await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempts) * 100));
489
- }
490
- }
491
- }
492
-
493
- async updatePartial(
494
- projectId: string,
495
- userId: string,
496
- patch: {
497
- language?: string;
498
- timezone?: string;
499
- email?: string | null;
500
- segments?: string[];
501
- preferences?: Preferences;
502
- },
503
- ): Promise<boolean> {
504
- const existing = await this.findById(projectId, userId);
505
- if (!existing) return false;
506
-
507
- const attrs = {
508
- language: patch.language ?? existing.language,
509
- timezone: patch.timezone ?? existing.timezone,
510
- // `null` clears the email; only an absent field keeps the old one.
511
- email: patch.email !== undefined ? patch.email : existing.email,
512
- };
513
-
514
- await this.db.transaction(async (tx) => {
515
- await tx
516
- .update(users)
517
- .set({ attributes: attrs, updatedAt: new Date() })
518
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
519
-
520
- const internalIdRows = await tx
521
- .select({ id: users.id })
522
- .from(users)
523
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
524
- const internalId = internalIdRows[0]?.id;
525
- if (!internalId) return;
526
-
527
- if (patch.segments) {
528
- await tx.delete(userSegments).where(eq(userSegments.userId, internalId));
529
- if (patch.segments.length > 0) {
530
- await tx
531
- .insert(userSegments)
532
- .values(patch.segments.map((s) => ({ userId: internalId, segment: s })))
533
- .onConflictDoNothing();
534
- }
535
- }
536
-
537
- if (patch.preferences && patch.preferences.topics) {
538
- const topicInserts = Object.entries(patch.preferences.topics).map(([topic, enabled]) => ({
539
- userId: internalId,
540
- topic,
541
- enabled,
542
- }));
543
- if (topicInserts.length > 0) {
544
- await tx
545
- .insert(userTopicPreferences)
546
- .values(topicInserts)
547
- .onConflictDoUpdate({
548
- target: [userTopicPreferences.userId, userTopicPreferences.topic],
549
- set: { enabled: drizzleSql`excluded.enabled` },
550
- });
551
- }
552
- }
553
-
554
- if (patch.preferences?.channels) {
555
- const channelInserts = Object.entries(patch.preferences.channels).map(
556
- ([channel, enabled]) => ({
557
- userId: internalId,
558
- channel: channel as ContactChannel,
559
- enabled,
560
- }),
561
- );
562
- if (channelInserts.length > 0) {
563
- await tx
564
- .insert(userChannelPreferences)
565
- .values(channelInserts)
566
- .onConflictDoUpdate({
567
- target: [userChannelPreferences.userId, userChannelPreferences.channel],
568
- set: { enabled: drizzleSql`excluded.enabled` },
569
- });
570
- }
571
- }
572
-
573
- if (patch.preferences?.quietHours !== undefined) {
574
- await tx.delete(quietHours).where(eq(quietHours.userId, internalId));
575
- if (patch.preferences.quietHours.length > 0) {
576
- await tx.insert(quietHours).values(
577
- patch.preferences.quietHours.map((window) => ({
578
- userId: internalId,
579
- startTime: window.start,
580
- endTime: window.end,
581
- })),
582
- );
583
- }
584
- }
585
- });
586
-
587
- this.recordCache.delete(`${projectId}:${userId}`);
588
- return true;
589
- }
590
-
591
- async delete(projectId: string, userId: string): Promise<boolean> {
592
- this.recordCache.delete(`${projectId}:${userId}`);
593
- const result = await this.db
594
- .delete(users)
595
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)))
596
- .returning();
597
- return result.length > 0;
598
- }
599
-
600
- async list(
601
- projectId: string,
602
- limit: number,
603
- cursor?: string,
604
- filters?: {
605
- search?: string;
606
- segment?: string;
607
- language?: string;
608
- timezone?: string;
609
- channel?: string;
610
- },
611
- ): Promise<{ users: UserProfile[]; nextCursor: string | null }> {
612
- const conditions = [eq(users.projectId, projectId)];
613
-
614
- // The cursor is the id of the last row returned. Paging on created_at
615
- // alone skipped rows: a bulk import writes every user in one transaction,
616
- // so they share one created_at, and the millisecond cursor could not tell
617
- // them apart. (created_at, id) is unique and ordered.
618
- if (cursor && UUID_RE.test(cursor)) {
619
- conditions.push(
620
- drizzleSql`(${users.createdAt}, ${users.id}) < (SELECT c.created_at, c.id FROM ${users} c WHERE c.id = ${cursor})`,
621
- );
622
- }
623
-
624
- if (filters?.language) {
625
- conditions.push(drizzleSql`(${users.attributes}->>'language') = ${filters.language}`);
626
- }
627
-
628
- if (filters?.timezone) {
629
- conditions.push(drizzleSql`(${users.attributes}->>'timezone') = ${filters.timezone}`);
630
- }
631
-
632
- if (filters?.search) {
633
- // `%`, `_` and `\` in the search are literal, not wildcards.
634
- const term = `%${filters.search.trim().replace(/[\\%_]/g, "\\$&")}%`;
635
- conditions.push(
636
- drizzleSql`(${users.externalId} ILIKE ${term} OR (${users.attributes}->>'email') ILIKE ${term})`,
637
- );
638
- }
639
-
640
- if (filters?.segment) {
641
- conditions.push(
642
- drizzleSql`EXISTS (SELECT 1 FROM ${userSegments} WHERE ${userSegments.userId} = ${users.id} AND ${userSegments.segment} = ${filters.segment})`,
643
- );
644
- }
645
-
646
- if (filters?.channel) {
647
- conditions.push(
648
- drizzleSql`EXISTS (SELECT 1 FROM ${userContacts} WHERE ${userContacts.userId} = ${users.id} AND ${userContacts.channel} = ${filters.channel})`,
649
- );
650
- }
651
-
652
- const rows = await this.db
653
- .select()
654
- .from(users)
655
- .where(and(...conditions))
656
- .orderBy(desc(users.createdAt), desc(users.id))
657
- .limit(limit);
658
-
659
- const items = rows.map((r) => {
660
- const attrs = r.attributes as any;
661
- return {
662
- userId: r.externalId,
663
- language: attrs.language ?? DEFAULT_LANGUAGE,
664
- timezone: attrs.timezone ?? DEFAULT_TIMEZONE,
665
- email: attrs.email,
666
- createdAt: r.createdAt.getTime(),
667
- };
668
- });
669
-
670
- const nextCursor = rows.length === limit ? rows[rows.length - 1]!.id : null;
671
- return { users: items, nextCursor };
672
- }
673
-
674
- async findUsersBySegment(projectId: string, segmentName: string): Promise<string[]> {
675
- const rows = await this.db
676
- .select({ externalId: users.externalId })
677
- .from(users)
678
- .innerJoin(userSegments, eq(users.id, userSegments.userId))
679
- .where(and(eq(userSegments.segment, segmentName), eq(users.projectId, projectId)));
680
-
681
- return rows.map((r) => r.externalId);
682
- }
683
-
684
- async findUsersByTopic(projectId: string, topicName: string): Promise<string[]> {
685
- const rows = await this.db
686
- .select({ externalId: users.externalId })
687
- .from(users)
688
- .innerJoin(userTopicPreferences, eq(users.id, userTopicPreferences.userId))
689
- .where(
690
- and(
691
- eq(userTopicPreferences.topic, topicName),
692
- eq(userTopicPreferences.enabled, true),
693
- eq(users.projectId, projectId),
694
- ),
695
- );
696
-
697
- return rows.map((r) => r.externalId);
698
- }
699
- }
700
-
701
- // ─── PreferenceRepository ────────────────────────────────────────────────────
702
-
703
- export class PreferenceRepository {
704
- constructor(private readonly db: Db) {}
705
-
706
- async isOptedIn(projectId: string, userId: string, eventType: string): Promise<boolean> {
707
- const prefs = await this.findByUserId(projectId, userId);
708
- const pref = prefs.find((p) => p.eventType === eventType);
709
- return pref ? pref.optedIn : true;
710
- }
711
-
712
- async findByUserId(projectId: string, userId: string): Promise<NotificationPreference[]> {
713
- const internalUserIdRows = await this.db
714
- .select({ id: users.id })
715
- .from(users)
716
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
717
- const internalId = internalUserIdRows[0]?.id;
718
- if (!internalId) return [];
719
-
720
- const rows = await this.db
721
- .select()
722
- .from(userTopicPreferences)
723
- .where(eq(userTopicPreferences.userId, internalId));
724
-
725
- return rows.map((r) => ({
726
- userId,
727
- eventType: r.topic,
728
- optedIn: r.enabled,
729
- }));
730
- }
731
- }
732
-
733
- // ─── ContactRepository ───────────────────────────────────────────────────────
734
-
735
- export class ContactRepository {
736
- private readonly activeContactsCache = new LRUCache<string, UserContact[]>(5000, 30_000);
737
-
738
- constructor(private readonly db: Db) {}
739
-
740
- async findByUserId(projectId: string, userId: string): Promise<UserContact[]> {
741
- const internalUserIdRows = await this.db
742
- .select({ id: users.id })
743
- .from(users)
744
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
745
- const internalId = internalUserIdRows[0]?.id;
746
- if (!internalId) return [];
747
-
748
- const rows = await this.db
749
- .select()
750
- .from(userContacts)
751
- .where(eq(userContacts.userId, internalId));
752
- if (rows.length === 0) return [];
753
-
754
- const topicRows = await this.db
755
- .select()
756
- .from(contactTopicPreferences)
757
- .where(
758
- inArray(
759
- contactTopicPreferences.contactId,
760
- rows.map((r) => r.id),
761
- ),
762
- );
763
-
764
- const topicsByContact = new Map<string, Record<string, boolean>>();
765
- for (const t of topicRows) {
766
- if (!topicsByContact.has(t.contactId)) topicsByContact.set(t.contactId, {});
767
- topicsByContact.get(t.contactId)![t.topic] = t.enabled;
768
- }
769
-
770
- return rows.map((r) => ({
771
- id: r.id,
772
- userId,
773
- channel: r.channel as ContactChannel,
774
- target: r.target,
775
- preferences: { topics: topicsByContact.get(r.id) ?? {} },
776
- active: r.enabled,
777
- }));
778
- }
779
-
780
- /** Resolve active addressable contacts for a batch without an N+1 query. */
781
- async findActiveByUserIds(
782
- projectId: string,
783
- userIds: string[],
784
- ): Promise<Map<string, UserContact[]>> {
785
- const byUser = new Map<string, UserContact[]>();
786
- if (userIds.length === 0) return byUser;
787
-
788
- const missingIds: string[] = [];
789
- for (const userId of userIds) {
790
- const cacheKey = `${projectId}:${userId}`;
791
- const cached = this.activeContactsCache.get(cacheKey);
792
- if (cached !== undefined) {
793
- if (cached.length > 0) {
794
- byUser.set(userId, cached);
795
- }
796
- } else {
797
- missingIds.push(userId);
798
- }
799
- }
800
-
801
- if (missingIds.length === 0) {
802
- return byUser;
803
- }
804
-
805
- const rows = await this.db
806
- .select({
807
- userId: users.externalId,
808
- id: userContacts.id,
809
- channel: userContacts.channel,
810
- target: userContacts.target,
811
- enabled: userContacts.enabled,
812
- })
813
- .from(users)
814
- .innerJoin(userContacts, eq(users.id, userContacts.userId))
815
- .where(
816
- and(
817
- eq(users.projectId, projectId),
818
- inArray(users.externalId, missingIds),
819
- eq(userContacts.enabled, true),
820
- ),
821
- );
822
-
823
- // Per-address topic opt-outs (a user who wants marketing at home but not at
824
- // work). Without them the pipeline cannot honour an opt-out it accepted.
825
- const topicsByContact = new Map<string, Record<string, boolean>>();
826
- if (rows.length > 0) {
827
- const topicRows = await this.db
828
- .select()
829
- .from(contactTopicPreferences)
830
- .where(
831
- inArray(
832
- contactTopicPreferences.contactId,
833
- rows.map((r) => r.id),
834
- ),
835
- );
836
- for (const t of topicRows) {
837
- if (!topicsByContact.has(t.contactId)) topicsByContact.set(t.contactId, {});
838
- topicsByContact.get(t.contactId)![t.topic] = t.enabled;
839
- }
840
- }
841
-
842
- const fetchedByUser = new Map<string, UserContact[]>();
843
- for (const id of missingIds) {
844
- fetchedByUser.set(id, []);
845
- }
846
-
847
- for (const row of rows) {
848
- const contacts = fetchedByUser.get(row.userId) ?? [];
849
- const topics = topicsByContact.get(row.id);
850
- contacts.push({
851
- id: row.id,
852
- userId: row.userId,
853
- channel: row.channel as ContactChannel,
854
- target: row.target,
855
- preferences: topics ? { topics } : {},
856
- active: row.enabled,
857
- });
858
- fetchedByUser.set(row.userId, contacts);
859
- }
860
-
861
- for (const id of missingIds) {
862
- const contacts = fetchedByUser.get(id) ?? [];
863
- this.activeContactsCache.set(`${projectId}:${id}`, contacts);
864
- if (contacts.length > 0) {
865
- byUser.set(id, contacts);
866
- }
867
- }
868
-
869
- return byUser;
870
- }
871
-
872
- async upsert(
873
- projectId: string,
874
- userId: string,
875
- channel: ContactChannel,
876
- target: string,
877
- preferences: Preferences = {},
878
- ): Promise<void> {
879
- const internalUserIdRows = await this.db
880
- .select({ id: users.id })
881
- .from(users)
882
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
883
- const internalId = internalUserIdRows[0]?.id;
884
- if (!internalId) return;
885
-
886
- const inserted = await this.db
887
- .insert(userContacts)
888
- .values({
889
- userId: internalId,
890
- channel: channel as any,
891
- target,
892
- enabled: true,
893
- })
894
- .onConflictDoUpdate({
895
- target: [userContacts.userId, userContacts.channel, userContacts.target],
896
- // Re-adding a contact re-enables it; this is also how a device token
897
- // deactivated by an invalid-token response comes back.
898
- set: { enabled: true },
899
- })
900
- .returning({ id: userContacts.id });
901
-
902
- const contactId = inserted[0]?.id;
903
- if (!contactId) return;
904
-
905
- // Contact-level topic preferences were previously accepted by the API and
906
- // silently discarded.
907
- const topics = Object.entries(preferences.topics ?? {});
908
- if (topics.length > 0) {
909
- await this.db
910
- .insert(contactTopicPreferences)
911
- .values(topics.map(([topic, enabled]) => ({ contactId, topic, enabled })))
912
- .onConflictDoUpdate({
913
- target: [contactTopicPreferences.contactId, contactTopicPreferences.topic],
914
- set: { enabled: drizzleSql`excluded.enabled` },
915
- });
916
- }
917
- this.activeContactsCache.delete(`${projectId}:${userId}`);
918
- }
919
-
920
- async upsertMany(
921
- projectId: string,
922
- contactsList: Array<{
923
- userId: string;
924
- channel: ContactChannel;
925
- target: string;
926
- preferences?: Preferences;
927
- }>,
928
- ): Promise<void> {
929
- if (contactsList.length === 0) return;
930
-
931
- const internalUserIdRows = await this.db
932
- .select({ id: users.id, externalId: users.externalId })
933
- .from(users)
934
- .where(
935
- and(
936
- inArray(
937
- users.externalId,
938
- contactsList.map((c) => c.userId),
939
- ),
940
- eq(users.projectId, projectId),
941
- ),
942
- );
943
-
944
- const idMap = new Map(internalUserIdRows.map((r) => [r.externalId, r.id]));
945
-
946
- // The same address can arrive twice — as `email` and again in `contacts`
947
- // — and ON CONFLICT DO UPDATE rejects a statement that touches one row
948
- // twice. Keep one entry per address, merging their topic preferences.
949
- const byAddress = new Map<string, (typeof contactsList)[number]>();
950
- for (const c of contactsList) {
951
- if (!idMap.has(c.userId)) continue;
952
- const key = `${c.userId}\u0000${c.channel}\u0000${c.target}`;
953
- const seen = byAddress.get(key);
954
- byAddress.set(
955
- key,
956
- seen
957
- ? {
958
- ...c,
959
- preferences: {
960
- ...seen.preferences,
961
- ...c.preferences,
962
- topics: { ...seen.preferences?.topics, ...c.preferences?.topics },
963
- },
964
- }
965
- : c,
966
- );
967
- }
968
- const validContacts = [...byAddress.values()];
969
- if (validContacts.length === 0) return;
970
-
971
- const inserted = await this.db
972
- .insert(userContacts)
973
- .values(
974
- validContacts.map((c) => ({
975
- userId: idMap.get(c.userId)!,
976
- channel: c.channel as any,
977
- target: c.target,
978
- enabled: true,
979
- })),
980
- )
981
- .onConflictDoUpdate({
982
- target: [userContacts.userId, userContacts.channel, userContacts.target],
983
- set: { enabled: true },
984
- })
985
- .returning({
986
- id: userContacts.id,
987
- userId: userContacts.userId,
988
- channel: userContacts.channel,
989
- target: userContacts.target,
990
- });
991
-
992
- const contactIdMap = new Map();
993
- for (const row of inserted) {
994
- contactIdMap.set(`${row.userId}:${row.channel}:${row.target}`, row.id);
995
- }
996
-
997
- const topicInserts: any[] = [];
998
- for (const c of validContacts) {
999
- const internalId = idMap.get(c.userId)!;
1000
- const contactId = contactIdMap.get(`${internalId}:${c.channel}:${c.target}`);
1001
- if (!contactId || !c.preferences?.topics) continue;
1002
-
1003
- for (const [topic, enabled] of Object.entries(c.preferences.topics)) {
1004
- topicInserts.push({ contactId, topic, enabled });
1005
- }
1006
- }
1007
-
1008
- if (topicInserts.length > 0) {
1009
- await this.db
1010
- .insert(contactTopicPreferences)
1011
- .values(topicInserts)
1012
- .onConflictDoUpdate({
1013
- target: [contactTopicPreferences.contactId, contactTopicPreferences.topic],
1014
- set: { enabled: drizzleSql`excluded.enabled` },
1015
- });
1016
- }
1017
- for (const c of validContacts) {
1018
- this.activeContactsCache.delete(`${projectId}:${c.userId}`);
1019
- }
1020
- }
1021
-
1022
- /**
1023
- * Mark a contact unusable without destroying it — used when a provider
1024
- * reports an invalid push token. Deleting the row would lose the user's
1025
- * device permanently on what is often a transient provider response.
1026
- */
1027
- async deactivate(
1028
- projectId: string,
1029
- userId: string,
1030
- channel: ContactChannel,
1031
- target: string,
1032
- ): Promise<boolean> {
1033
- this.activeContactsCache.delete(`${projectId}:${userId}`);
1034
- const internalUserIdRows = await this.db
1035
- .select({ id: users.id })
1036
- .from(users)
1037
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
1038
- const internalId = internalUserIdRows[0]?.id;
1039
- if (!internalId) return false;
1040
-
1041
- const result = await this.db
1042
- .update(userContacts)
1043
- .set({ enabled: false })
1044
- .where(
1045
- and(
1046
- eq(userContacts.userId, internalId),
1047
- eq(userContacts.channel, channel as any),
1048
- eq(userContacts.target, target),
1049
- ),
1050
- )
1051
- .returning();
1052
- return result.length > 0;
1053
- }
1054
-
1055
- async delete(
1056
- projectId: string,
1057
- userId: string,
1058
- channel: ContactChannel,
1059
- target: string,
1060
- ): Promise<boolean> {
1061
- this.activeContactsCache.delete(`${projectId}:${userId}`);
1062
- const internalUserIdRows = await this.db
1063
- .select({ id: users.id })
1064
- .from(users)
1065
- .where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
1066
- const internalId = internalUserIdRows[0]?.id;
1067
- if (!internalId) return false;
1068
-
1069
- const result = await this.db
1070
- .delete(userContacts)
1071
- .where(
1072
- and(
1073
- eq(userContacts.userId, internalId),
1074
- eq(userContacts.channel, channel as any),
1075
- eq(userContacts.target, target),
1076
- ),
1077
- )
1078
- .returning();
1079
- return result.length > 0;
1080
- }
1081
- }
1082
-
1083
- // ─── TemplateRepository ──────────────────────────────────────────────────────
1084
-
1085
- export class TemplateRepository {
1086
- constructor(private readonly db: Db) {}
1087
-
1088
- async findById(projectId: string, id: string): Promise<TemplateRecord | null> {
1089
- const rows = await this.db
1090
- .select()
1091
- .from(templates)
1092
- .where(and(eq(templates.id, id), eq(templates.projectId, projectId)))
1093
- .limit(1);
1094
- if (!rows[0]) return null;
1095
- return {
1096
- id: rows[0].id,
1097
- channel: rows[0].channel,
1098
- content: rows[0].content,
1099
- topics: (rows[0].topics ?? []) as string[],
1100
- aiPrompts: rows[0].aiPrompts as Record<string, string> | null,
1101
- };
1102
- }
1103
-
1104
- async list(projectId: string): Promise<TemplateRecord[]> {
1105
- const rows = await this.db.select().from(templates).where(eq(templates.projectId, projectId));
1106
- return rows.map((r) => ({
1107
- id: r.id,
1108
- channel: r.channel,
1109
- content: r.content,
1110
- topics: (r.topics ?? []) as string[],
1111
- aiPrompts: r.aiPrompts as Record<string, string> | null,
1112
- }));
1113
- }
1114
-
1115
- async upsertMany(projectId: string, templateList: any[]): Promise<number> {
1116
- if (templateList.length === 0) return 0;
1117
-
1118
- const values = templateList.map((t) => ({
1119
- projectId,
1120
- id: t.id,
1121
- channel: t.channel as any,
1122
- topics: t.topics ?? [],
1123
- content: t.content,
1124
- aiPrompts: t.aiPrompts,
1125
- }));
1126
-
1127
- await this.db
1128
- .insert(templates)
1129
- .values(values)
1130
- .onConflictDoUpdate({
1131
- target: [templates.projectId, templates.id],
1132
- set: {
1133
- channel: drizzleSql`excluded.channel`,
1134
- topics: drizzleSql`excluded.topics`,
1135
- content: drizzleSql`excluded.content`,
1136
- aiPrompts: drizzleSql`excluded.ai_prompts`,
1137
- updatedAt: new Date(),
1138
- },
1139
- });
1140
-
1141
- return templateList.length;
1142
- }
1143
-
1144
- async delete(projectId: string, id: string): Promise<boolean> {
1145
- const result = await this.db
1146
- .delete(templates)
1147
- .where(and(eq(templates.id, id), eq(templates.projectId, projectId)))
1148
- .returning();
1149
- return result.length > 0;
1150
- }
1151
- }
1152
-
1153
- // ─── ProjectRepository ───────────────────────────────────────────────────────
1154
-
1155
- export class ProjectRepository {
1156
- constructor(private readonly db: Db) {}
1157
-
1158
- async list(): Promise<any[]> {
1159
- return this.db
1160
- .select({
1161
- id: projects.id,
1162
- name: projects.name,
1163
- rateLimitRpm: projects.rateLimitRpm,
1164
- throttleLimit: projects.throttleLimit,
1165
- throttleWindowHours: projects.throttleWindowHours,
1166
- createdAt: projects.createdAt,
1167
- })
1168
- .from(projects)
1169
- .orderBy(desc(projects.createdAt));
1170
- }
1171
-
1172
- async delete(id: string): Promise<boolean> {
1173
- return await this.db.transaction(async (tx) => {
1174
- const userRows = await tx.select({ id: users.id }).from(users).where(eq(users.projectId, id));
1175
- const userIds = userRows.map((u) => u.id);
1176
- if (userIds.length > 0) {
1177
- await tx.delete(userContacts).where(inArray(userContacts.userId, userIds));
1178
- await tx.delete(userSegments).where(inArray(userSegments.userId, userIds));
1179
- await tx.delete(userTopicPreferences).where(inArray(userTopicPreferences.userId, userIds));
1180
- await tx
1181
- .delete(userChannelPreferences)
1182
- .where(inArray(userChannelPreferences.userId, userIds));
1183
- await tx.delete(quietHours).where(inArray(quietHours.userId, userIds));
1184
- await tx.delete(users).where(eq(users.projectId, id));
1185
- }
1186
- await tx.delete(suppressions).where(eq(suppressions.projectId, id));
1187
- await tx.delete(messageLogs).where(eq(messageLogs.projectId, id));
1188
- await tx.delete(workflowInstances).where(eq(workflowInstances.projectId, id));
1189
- await tx.delete(workflowDefinitions).where(eq(workflowDefinitions.projectId, id));
1190
-
1191
- const result = await tx.delete(projects).where(eq(projects.id, id)).returning();
1192
- return result.length > 0;
1193
- });
1194
- }
1195
-
1196
- /**
1197
- * Throttle overrides only. Kept narrow because the engine calls this once per
1198
- * notification (behind a cache) and has no use for the rest of the row.
1199
- */
1200
- async findThrottleSettings(
1201
- id: string,
1202
- ): Promise<{ throttleLimit: number | null; throttleWindowHours: number | null } | null> {
1203
- const rows = await this.db
1204
- .select({
1205
- throttleLimit: projects.throttleLimit,
1206
- throttleWindowHours: projects.throttleWindowHours,
1207
- })
1208
- .from(projects)
1209
- .where(eq(projects.id, id))
1210
- .limit(1);
1211
-
1212
- return rows[0] ?? null;
1213
- }
1214
-
1215
- async updateSettings(
1216
- id: string,
1217
- settings: {
1218
- rateLimitRpm?: number | null;
1219
- throttleLimit?: number | null;
1220
- throttleWindowHours?: number | null;
1221
- },
1222
- ): Promise<boolean> {
1223
- const result = await this.db
1224
- .update(projects)
1225
- .set(settings)
1226
- .where(eq(projects.id, id))
1227
- .returning();
1228
- return result.length > 0;
1229
- }
1230
-
1231
- async createApiKey(
1232
- projectId: string,
1233
- keyHash: string,
1234
- role: "admin" | "read_only" = "admin",
1235
- ): Promise<{ id: string }> {
1236
- const result = await this.db
1237
- .insert(projectApiKeys)
1238
- .values({ projectId, keyHash, role })
1239
- .returning();
1240
- return { id: result[0]!.id };
1241
- }
1242
-
1243
- async listApiKeys(projectId: string): Promise<any[]> {
1244
- return this.db
1245
- .select({
1246
- id: projectApiKeys.id,
1247
- role: projectApiKeys.role,
1248
- createdAt: projectApiKeys.createdAt,
1249
- })
1250
- .from(projectApiKeys)
1251
- .where(eq(projectApiKeys.projectId, projectId))
1252
- .orderBy(desc(projectApiKeys.createdAt));
1253
- }
1254
-
1255
- async deleteApiKey(projectId: string, keyId: string): Promise<boolean> {
1256
- const result = await this.db
1257
- .delete(projectApiKeys)
1258
- .where(and(eq(projectApiKeys.id, keyId), eq(projectApiKeys.projectId, projectId)))
1259
- .returning();
1260
- return result.length > 0;
1261
- }
1262
- }
1263
-
1264
- // ─── WorkflowRepository ──────────────────────────────────────────────────────
1265
-
1266
- export class WorkflowRepository {
1267
- constructor(private readonly db: Db) {}
1268
-
1269
- async listDefinitions(projectId: string): Promise<any[]> {
1270
- return this.db
1271
- .select()
1272
- .from(workflowDefinitions)
1273
- .where(eq(workflowDefinitions.projectId, projectId))
1274
- .orderBy(desc(workflowDefinitions.createdAt));
1275
- }
1276
-
1277
- async getInstance(projectId: string, instanceId: string): Promise<any | null> {
1278
- const instances = await this.db
1279
- .select()
1280
- .from(workflowInstances)
1281
- .where(and(eq(workflowInstances.id, instanceId), eq(workflowInstances.projectId, projectId)))
1282
- .limit(1);
1283
- if (!instances[0]) return null;
1284
-
1285
- const steps = await this.db
1286
- .select()
1287
- .from(workflowSteps)
1288
- .where(eq(workflowSteps.instanceId, instanceId))
1289
- .orderBy(workflowSteps.createdAt);
1290
- const waiters = await this.db
1291
- .select()
1292
- .from(workflowWaiters)
1293
- .where(eq(workflowWaiters.instanceId, instanceId));
1294
-
1295
- return {
1296
- ...instances[0],
1297
- steps,
1298
- waiters,
1299
- };
1300
- }
1301
-
1302
- async cancelInstance(projectId: string, instanceId: string): Promise<boolean> {
1303
- return await this.db.transaction(async (tx) => {
1304
- const result = await tx
1305
- .update(workflowInstances)
1306
- .set({ status: "canceled" })
1307
- .where(
1308
- and(
1309
- eq(workflowInstances.id, instanceId),
1310
- eq(workflowInstances.projectId, projectId),
1311
- inArray(workflowInstances.status, ["pending", "running"]),
1312
- ),
1313
- )
1314
- .returning();
1315
- if (result.length === 0) return false;
1316
- await tx.delete(workflowWaiters).where(eq(workflowWaiters.instanceId, instanceId));
1317
- return true;
1318
- });
1319
- }
1320
- }
1321
-
1322
- // ─── SegmentRepository ───────────────────────────────────────────────────────
1323
-
1324
- export class SegmentRepository {
1325
- constructor(private readonly db: Db) {}
1326
-
1327
- async listSegments(projectId: string): Promise<string[]> {
1328
- const rows = await this.db.execute(drizzleSql`
1329
- SELECT DISTINCT s.segment
1330
- FROM user_segments s
1331
- JOIN users u ON u.id = s.user_id
1332
- WHERE u.project_id = ${projectId}
1333
- `);
1334
- return (rows as any[]).map((r) => r.segment);
1335
- }
1336
- }
1337
-
1338
- // ─── AdminUserRepository ───────────────────────────────────────────────────
1339
-
1340
- export interface AdminUserRecord {
1341
- id: string;
1342
- email: string;
1343
- username: string | null;
1344
- passwordHash: string;
1345
- role: string;
1346
- createdAt: Date;
1347
- updatedAt: Date;
1348
- }
1349
-
1350
- export class AdminUserRepository {
1351
- constructor(private readonly db: Db) {}
1352
-
1353
- async findByEmailOrUsername(identifier: string): Promise<AdminUserRecord | null> {
1354
- const normalized = identifier.trim().toLowerCase();
1355
- const rows = await this.db
1356
- .select()
1357
- .from(adminUsers)
1358
- .where(or(eq(adminUsers.email, normalized), eq(adminUsers.username, identifier.trim())))
1359
- .limit(1);
1360
- return (rows[0] as AdminUserRecord) ?? null;
1361
- }
1362
-
1363
- async findById(id: string): Promise<AdminUserRecord | null> {
1364
- const rows = await this.db.select().from(adminUsers).where(eq(adminUsers.id, id)).limit(1);
1365
- return (rows[0] as AdminUserRecord) ?? null;
1366
- }
1367
-
1368
- async create(data: {
1369
- email: string;
1370
- username?: string | null;
1371
- passwordHash: string;
1372
- role?: string;
1373
- }): Promise<AdminUserRecord> {
1374
- const rows = await this.db
1375
- .insert(adminUsers)
1376
- .values({
1377
- email: data.email.trim().toLowerCase(),
1378
- username: data.username ? data.username.trim() : null,
1379
- passwordHash: data.passwordHash,
1380
- role: data.role || "admin",
1381
- })
1382
- .returning();
1383
- return rows[0] as AdminUserRecord;
1384
- }
1385
-
1386
- async updatePassword(id: string, passwordHash: string): Promise<boolean> {
1387
- const rows = await this.db
1388
- .update(adminUsers)
1389
- .set({ passwordHash, updatedAt: new Date() })
1390
- .where(eq(adminUsers.id, id))
1391
- .returning();
1392
- return rows.length > 0;
1393
- }
1394
-
1395
- async list(): Promise<Omit<AdminUserRecord, "passwordHash">[]> {
1396
- const rows = await this.db
1397
- .select({
1398
- id: adminUsers.id,
1399
- email: adminUsers.email,
1400
- username: adminUsers.username,
1401
- role: adminUsers.role,
1402
- createdAt: adminUsers.createdAt,
1403
- updatedAt: adminUsers.updatedAt,
1404
- })
1405
- .from(adminUsers)
1406
- .orderBy(adminUsers.createdAt);
1407
- return rows as Omit<AdminUserRecord, "passwordHash">[];
1408
- }
1409
-
1410
- async count(): Promise<number> {
1411
- const rows = await this.db
1412
- .select({ count: drizzleSql<number>`count(*)::int` })
1413
- .from(adminUsers);
1414
- return rows[0]?.count ?? 0;
1415
- }
1416
- }
1
+ export * from "./types.js";
2
+ export * from "./user.js";
3
+ export * from "./preference.js";
4
+ export * from "./contact.js";
5
+ export * from "./template.js";
6
+ export * from "./project.js";
7
+ export * from "./workflow.js";
8
+ export * from "./segment.js";
9
+ export * from "./admin-user.js";