notifkit 0.1.15 → 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 (85) 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-BOmT69OH.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
  5. package/dist/{bulk-ZPiOJRx-.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-CCqcFDDe.mjs → main-6_bXQBDH.mjs} +21 -41
  9. package/dist/{main-BdZvBgV7.mjs → main-8nP3qmCT.mjs} +22 -48
  10. package/dist/{main-C0m9-Eos.mjs → main-B82bsFoy.mjs} +183 -334
  11. package/dist/{main-CTjaZ7ZD.mjs → main-CpaHF1Zw.mjs} +13 -15
  12. package/dist/{main-JEXBLP2A.mjs → main-DULD8-th.mjs} +8 -6
  13. package/dist/{main-C6S3EsJ3.mjs → main-ZW5RaiOK.mjs} +77 -64
  14. package/dist/{main-g33jpia4.mjs → main-g1KEcXXp.mjs} +676 -582
  15. package/dist/{main-24J4U8yP.mjs → main-mGIT8jv4.mjs} +4 -4
  16. package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
  17. package/dist/{src-9LXITcNi.mjs → src-BE_EUpZ6.mjs} +93 -93
  18. package/package.json +1 -1
  19. package/scripts/create-project.mjs +6 -2
  20. package/src/client.ts +3 -3
  21. package/src/config/index.ts +1 -0
  22. package/src/contracts/common.ts +2 -0
  23. package/src/contracts/envelope.ts +1 -1
  24. package/src/contracts/events/notification-created.ts +2 -0
  25. package/src/contracts/events/notification-delivered.ts +1 -1
  26. package/src/contracts/events/notification-failed.ts +1 -1
  27. package/src/contracts/events/notification-requested.ts +3 -2
  28. package/src/contracts/helpers.ts +1 -2
  29. package/src/contracts/index.ts +1 -0
  30. package/src/contracts/registry.ts +1 -0
  31. package/src/contracts/sdk.ts +8 -37
  32. package/src/db/schema.ts +8 -13
  33. package/src/idempotency/index.ts +6 -8
  34. package/src/metrics/index.ts +2 -0
  35. package/src/rate-limiter/api-rate-limiter.ts +208 -0
  36. package/src/rate-limiter/index.ts +3 -411
  37. package/src/rate-limiter/project-settings-cache.ts +99 -0
  38. package/src/rate-limiter/user-throttle.ts +100 -0
  39. package/src/redis/index.ts +10 -3
  40. package/src/repositories/admin-user.ts +83 -0
  41. package/src/repositories/contact.ts +359 -0
  42. package/src/repositories/index.ts +9 -1416
  43. package/src/repositories/preference.ts +35 -0
  44. package/src/repositories/project.ts +110 -0
  45. package/src/repositories/segment.ts +16 -0
  46. package/src/repositories/template.ts +72 -0
  47. package/src/repositories/types.ts +49 -0
  48. package/src/repositories/user.ts +644 -0
  49. package/src/repositories/workflow.ts +64 -0
  50. package/src/services/ai/main.ts +29 -71
  51. package/src/services/api/admin-static.ts +4 -1
  52. package/src/services/api/handlers/auth.ts +109 -0
  53. package/src/services/api/handlers/campaigns.ts +191 -0
  54. package/src/services/api/handlers/events.ts +99 -0
  55. package/src/services/api/handlers/notifications.ts +356 -0
  56. package/src/services/api/handlers/projects.ts +116 -0
  57. package/src/services/api/handlers/shared.ts +262 -0
  58. package/src/services/api/handlers/suppressions.ts +95 -0
  59. package/src/services/api/handlers/system.ts +314 -0
  60. package/src/services/api/handlers/templates.ts +97 -0
  61. package/src/services/api/handlers/unsubscribe.ts +215 -0
  62. package/src/services/api/handlers/users.ts +262 -0
  63. package/src/services/api/handlers/workflows.ts +150 -0
  64. package/src/services/api/handlers.ts +25 -2190
  65. package/src/services/api/health.ts +133 -0
  66. package/src/services/api/http.ts +12 -0
  67. package/src/services/api/main.ts +32 -322
  68. package/src/services/api/router.ts +1 -1
  69. package/src/services/api/webhooks.ts +172 -0
  70. package/src/services/delivery/main.ts +256 -498
  71. package/src/services/engine/main.ts +31 -247
  72. package/src/services/engine/quiet-hours.ts +151 -0
  73. package/src/services/engine/schedule-or-dispatch.ts +104 -0
  74. package/src/services/enricher/main.ts +9 -21
  75. package/src/services/events/main.ts +2 -2
  76. package/src/services/scheduler/main.ts +16 -25
  77. package/src/services/workflow/duration.ts +24 -0
  78. package/src/services/workflow/main.ts +6 -164
  79. package/src/services/workflow/timers.ts +157 -0
  80. package/src/shared/events.ts +3 -2
  81. package/src/templates/render.ts +1 -0
  82. package/src/workers/index.ts +7 -4
  83. package/src/workflows/sdk.ts +1 -0
  84. package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
  85. package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
@@ -0,0 +1,97 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { SyncTemplatesSchema, PUBSUB_CHANNELS } from "@/contracts/index.js";
3
+ import { readJsonBody, sendJson, sendNoContent, sendValidationError } from "../http.js";
4
+ import type { RouteContext } from "../router.js";
5
+ import { type Deps, getQueryParam, parseLimit } from "./shared.js";
6
+
7
+ export function createTemplatesHandlers(deps: Deps) {
8
+ const { logger } = deps;
9
+
10
+ async function syncTemplates(
11
+ req: IncomingMessage,
12
+ res: ServerResponse,
13
+ ctx: RouteContext,
14
+ ): Promise<void> {
15
+ const parsed = SyncTemplatesSchema.safeParse(await readJsonBody(req));
16
+ if (!parsed.success) return sendValidationError(res, parsed.error);
17
+
18
+ const synced = await deps.templateRepo.upsertMany(
19
+ ctx.projectId!,
20
+ parsed.data.templates.map((t) => ({
21
+ id: t.id,
22
+ channel: t.channel,
23
+ topics: t.topic ?? [],
24
+ content: t.content,
25
+ aiPrompts: (t as any).aiPrompts,
26
+ })),
27
+ );
28
+
29
+ // Invalidate caches
30
+ for (const t of parsed.data.templates) {
31
+ await deps.redis.native.publish(
32
+ PUBSUB_CHANNELS.TEMPLATE_INVALIDATED,
33
+ `${ctx.projectId}:${t.id}`,
34
+ );
35
+ }
36
+
37
+ logger.info({ synced }, "templates synced");
38
+ sendJson(res, 200, { synced });
39
+ }
40
+
41
+ async function listTemplates(
42
+ req: IncomingMessage,
43
+ res: ServerResponse,
44
+ ctx: RouteContext,
45
+ ): Promise<void> {
46
+ const limit = parseLimit(ctx, undefined);
47
+ const channel = getQueryParam(ctx, "channel");
48
+ const topic = getQueryParam(ctx, "topic");
49
+ let templates = await deps.templateRepo.list(ctx.projectId!);
50
+ if (channel) {
51
+ templates = templates.filter((t: any) => t.channel === channel);
52
+ }
53
+ if (topic) {
54
+ templates = templates.filter((t: any) => t.topics?.includes(topic));
55
+ }
56
+ if (limit) {
57
+ templates = templates.slice(0, limit);
58
+ }
59
+ sendJson(res, 200, { templates });
60
+ }
61
+
62
+ async function getTemplate(
63
+ req: IncomingMessage,
64
+ res: ServerResponse,
65
+ ctx: RouteContext,
66
+ ): Promise<void> {
67
+ const templateId = ctx.params.id!;
68
+ const template = await deps.templateRepo.findById(ctx.projectId!, templateId);
69
+ if (!template) return sendJson(res, 404, { error: "template_not_found", id: templateId });
70
+
71
+ sendJson(res, 200, template);
72
+ }
73
+
74
+ async function deleteTemplate(
75
+ req: IncomingMessage,
76
+ res: ServerResponse,
77
+ ctx: RouteContext,
78
+ ): Promise<void> {
79
+ const templateId = ctx.params.id!;
80
+ const deleted = await deps.templateRepo.delete(ctx.projectId!, templateId);
81
+ if (!deleted) return sendJson(res, 404, { error: "template_not_found", id: templateId });
82
+
83
+ await deps.redis.native.publish(
84
+ PUBSUB_CHANNELS.TEMPLATE_INVALIDATED,
85
+ `${ctx.projectId}:${templateId}`,
86
+ );
87
+ logger.info({ templateId }, "template deleted");
88
+ sendNoContent(res);
89
+ }
90
+
91
+ return {
92
+ syncTemplates,
93
+ listTemplates,
94
+ getTemplate,
95
+ deleteTemplate,
96
+ };
97
+ }
@@ -0,0 +1,215 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { RouteContext } from "../router.js";
3
+ import { normaliseTarget } from "@/shared/index.js";
4
+ import { eq, and, sql } from "drizzle-orm";
5
+ import { suppressions, users as dbUsers, userTopicPreferences } from "@/db/schema.js";
6
+ import { readBaseConfig } from "@/config/index.js";
7
+ import { verifyUnsubscribeToken } from "@/unsubscribe/index.js";
8
+ import { type Deps } from "./shared.js";
9
+
10
+ export function createUnsubscribeHandlers(deps: Deps) {
11
+ const { logger } = deps;
12
+
13
+ // Both routes are unauthenticated: they are reached from a mail client, which
14
+ // has no API key. The signed token in the URL is the credential and it
15
+ // authorises exactly one thing for one address.
16
+
17
+ function sendHtml(res: ServerResponse, status: number, body: string): void {
18
+ res.writeHead(status, {
19
+ "Content-Type": "text/html; charset=utf-8",
20
+ // Nothing here should be cached by an inbox proxy or shared cache.
21
+ "Cache-Control": "no-store",
22
+ "X-Content-Type-Options": "nosniff",
23
+ "Referrer-Policy": "no-referrer",
24
+ });
25
+ res.end(body);
26
+ }
27
+
28
+ function escapeHtml(value: string): string {
29
+ return value
30
+ .replace(/&/g, "&amp;")
31
+ .replace(/</g, "&lt;")
32
+ .replace(/>/g, "&gt;")
33
+ .replace(/"/g, "&quot;");
34
+ }
35
+
36
+ function page(title: string, message: string): string {
37
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8">
38
+ <meta name="viewport" content="width=device-width,initial-scale=1">
39
+ <title>${escapeHtml(title)}</title>
40
+ <style>body{font:16px/1.6 system-ui,sans-serif;max-width:34rem;margin:12vh auto;padding:0 1.5rem;color:#111}
41
+ h1{font-size:1.4rem;margin:0 0 .75rem}p{margin:0 0 1rem;color:#444}
42
+ button{font:inherit;padding:.6rem 1.2rem;border:0;border-radius:6px;background:#111;color:#fff;cursor:pointer}
43
+ code{background:#f4f4f5;padding:.1rem .35rem;border-radius:4px}</style>
44
+ </head><body><h1>${escapeHtml(title)}</h1>${message}</body></html>`;
45
+ }
46
+
47
+ /**
48
+ * GET — the page a human lands on after clicking the link in the mail body.
49
+ *
50
+ * Deliberately does not unsubscribe anything. Corporate mail scanners and
51
+ * link prescanners issue a GET against every URL in a message; performing the
52
+ * opt-out here would unsubscribe people who never clicked. The mutation lives
53
+ * behind the POST.
54
+ */
55
+ async function unsubscribePage(
56
+ _req: IncomingMessage,
57
+ res: ServerResponse,
58
+ ctx: RouteContext,
59
+ ): Promise<void> {
60
+ const cfg = readBaseConfig();
61
+ const token = ctx.query.get("token") ?? "";
62
+ if (!cfg.UNSUBSCRIBE_SECRET) {
63
+ deps.logger.warn(
64
+ "UNSUBSCRIBE_SECRET is not configured — unable to verify unsubscribe tokens",
65
+ );
66
+ }
67
+ const claim = cfg.UNSUBSCRIBE_SECRET
68
+ ? verifyUnsubscribeToken(token, cfg.UNSUBSCRIBE_SECRET)
69
+ : null;
70
+
71
+ if (!claim) {
72
+ return sendHtml(
73
+ res,
74
+ 400,
75
+ page(
76
+ "This link is not valid",
77
+ "<p>It may have been altered in transit, or this server may have been reconfigured since the message was sent. Replying to the message and asking to be removed will still work.</p>",
78
+ ),
79
+ );
80
+ }
81
+
82
+ const what =
83
+ claim.topics.length > 0
84
+ ? `<code>${claim.topics.map(escapeHtml).join("</code>, <code>")}</code> messages`
85
+ : "all messages";
86
+
87
+ sendHtml(
88
+ res,
89
+ 200,
90
+ page(
91
+ "Unsubscribe",
92
+ `<p>Stop sending ${what} to <code>${escapeHtml(claim.target)}</code>?</p>
93
+ <form method="post" action="/v1/unsubscribe?token=${encodeURIComponent(token)}">
94
+ <button type="submit">Unsubscribe</button></form>`,
95
+ ),
96
+ );
97
+ }
98
+
99
+ /**
100
+ * POST — the real opt-out.
101
+ *
102
+ * Serves two callers with one handler: a mail client doing RFC 8058 one-click
103
+ * (body `List-Unsubscribe=One-Click`, token in the query string, no
104
+ * confirmation possible), and the form on the page above. Neither can carry a
105
+ * CSRF token, and the one-click spec forbids an interstitial, so the signed
106
+ * token is the whole of the authorisation.
107
+ */
108
+ async function unsubscribe(
109
+ req: IncomingMessage,
110
+ res: ServerResponse,
111
+ ctx: RouteContext,
112
+ ): Promise<void> {
113
+ // The one-click POST carries `List-Unsubscribe=One-Click` as its body and
114
+ // the token in the query string, so there is nothing here worth reading —
115
+ // but an unread body leaves bytes on a keep-alive socket. Discard it.
116
+ req.resume();
117
+
118
+ const cfg = readBaseConfig();
119
+ const token = ctx.query.get("token") ?? "";
120
+ if (!cfg.UNSUBSCRIBE_SECRET) {
121
+ deps.logger.warn(
122
+ "UNSUBSCRIBE_SECRET is not configured — unable to verify unsubscribe tokens",
123
+ );
124
+ }
125
+ const claim = cfg.UNSUBSCRIBE_SECRET
126
+ ? verifyUnsubscribeToken(token, cfg.UNSUBSCRIBE_SECRET)
127
+ : null;
128
+
129
+ if (!claim) {
130
+ return sendHtml(
131
+ res,
132
+ 400,
133
+ page(
134
+ "This link is not valid",
135
+ "<p>It may have been altered in transit, or this server may have been reconfigured since the message was sent.</p>",
136
+ ),
137
+ );
138
+ }
139
+
140
+ const target = normaliseTarget(claim.target);
141
+
142
+ try {
143
+ const userRows = await deps.db
144
+ .select({ id: dbUsers.id })
145
+ .from(dbUsers)
146
+ .where(and(eq(dbUsers.projectId, claim.projectId), eq(dbUsers.externalId, claim.userId)))
147
+ .limit(1);
148
+ const internalId = userRows[0]?.id;
149
+
150
+ if (claim.topics.length > 0 && internalId) {
151
+ // Scoped opt-out: silence this kind of mail and leave the rest,
152
+ // including anything transactional, working.
153
+ await deps.db
154
+ .insert(userTopicPreferences)
155
+ .values(claim.topics.map((topic) => ({ userId: internalId, topic, enabled: false })))
156
+ .onConflictDoUpdate({
157
+ target: [userTopicPreferences.userId, userTopicPreferences.topic],
158
+ set: { enabled: sql`excluded.enabled` },
159
+ });
160
+ } else {
161
+ // No topic to scope to, or the user record is gone. Either way the
162
+ // request has to be honoured, so fall back to suppressing the address
163
+ // outright — over-honouring an unsubscribe is the safe direction.
164
+ await deps.db
165
+ .insert(suppressions)
166
+ .values({
167
+ projectId: claim.projectId,
168
+ channel: claim.channel as any,
169
+ target,
170
+ reason: "unsubscribed",
171
+ source: "unsubscribe-link",
172
+ })
173
+ .onConflictDoNothing();
174
+ }
175
+
176
+ logger.info(
177
+ {
178
+ projectId: claim.projectId,
179
+ channel: claim.channel,
180
+ topics: claim.topics,
181
+ scoped: claim.topics.length > 0 && Boolean(internalId),
182
+ },
183
+ "unsubscribe honoured",
184
+ );
185
+ } catch (err) {
186
+ // A 5xx here means the mail client reports failure and, worse, the person
187
+ // believes they have opted out when they have not.
188
+ logger.error({ err, projectId: claim.projectId }, "unsubscribe failed to apply");
189
+ return sendHtml(
190
+ res,
191
+ 500,
192
+ page(
193
+ "Something went wrong",
194
+ "<p>We could not record that just now. Please try again in a moment.</p>",
195
+ ),
196
+ );
197
+ }
198
+
199
+ sendHtml(
200
+ res,
201
+ 200,
202
+ page(
203
+ "You're unsubscribed",
204
+ `<p>We've stopped sending ${
205
+ claim.topics.length > 0 ? "these messages" : "messages"
206
+ } to <code>${escapeHtml(claim.target)}</code>. It may take a few minutes to take effect for mail already on its way.</p>`,
207
+ ),
208
+ );
209
+ }
210
+
211
+ return {
212
+ unsubscribePage,
213
+ unsubscribe,
214
+ };
215
+ }
@@ -0,0 +1,262 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import {
3
+ AddUserSchema,
4
+ UpdateUserSchema,
5
+ BatchAddContactsSchema,
6
+ ContactChannelSchema,
7
+ PreferencesSchema,
8
+ } from "@/contracts/index.js";
9
+ import { readJsonBody, sendJson, sendNoContent, sendValidationError } from "../http.js";
10
+ import type { RouteContext } from "../router.js";
11
+ import { eq, desc, and, inArray } from "drizzle-orm";
12
+ import { messageLogs, deliveryOutbox } from "@/db/schema.js";
13
+ import { type Deps, contactsOf, persistUsers, getQueryParam, parseLimit } from "./shared.js";
14
+
15
+ export function createUsersHandlers(deps: Deps) {
16
+ const { logger } = deps;
17
+
18
+ async function addUser(
19
+ req: IncomingMessage,
20
+ res: ServerResponse,
21
+ ctx: RouteContext,
22
+ ): Promise<void> {
23
+ const parsed = AddUserSchema.safeParse(await readJsonBody(req));
24
+ if (!parsed.success) return sendValidationError(res, parsed.error);
25
+
26
+ await persistUsers(deps, [parsed.data], ctx.projectId!);
27
+ logger.info({ userId: parsed.data.id }, "user upserted");
28
+ sendJson(res, 201, { id: parsed.data.id });
29
+ }
30
+
31
+ async function updateUser(
32
+ req: IncomingMessage,
33
+ res: ServerResponse,
34
+ ctx: RouteContext,
35
+ ): Promise<void> {
36
+ const userId = ctx.params.id!;
37
+ const parsed = UpdateUserSchema.safeParse(await readJsonBody(req));
38
+ if (!parsed.success) return sendValidationError(res, parsed.error);
39
+ const patch = parsed.data;
40
+
41
+ const updated = await deps.userRepo.updatePartial(ctx.projectId!, userId, {
42
+ language: patch.language,
43
+ timezone: patch.timezone,
44
+ email: patch.email?.[0] ?? patch.contacts?.find((c) => c.channel === "email")?.target,
45
+ segments: patch.segments,
46
+ preferences: patch.preferences,
47
+ });
48
+ if (!updated) return sendJson(res, 404, { error: "user_not_found", id: userId });
49
+
50
+ // New contact values in the patch are added (existing ones are kept).
51
+ for (const c of contactsOf({ id: userId, ...patch })) {
52
+ if (c.preferences) {
53
+ await deps.contactRepo.upsert(ctx.projectId!, userId, c.channel, c.target, c.preferences);
54
+ } else {
55
+ await deps.contactRepo.upsert(ctx.projectId!, userId, c.channel, c.target);
56
+ }
57
+ }
58
+ logger.info({ userId }, "user updated");
59
+ sendJson(res, 200, { id: userId });
60
+ }
61
+
62
+ async function deleteUser(
63
+ _req: IncomingMessage,
64
+ res: ServerResponse,
65
+ ctx: RouteContext,
66
+ ): Promise<void> {
67
+ const userId = ctx.params.id!;
68
+ const deleted = await deps.userRepo.delete(ctx.projectId!, userId);
69
+ if (!deleted) return sendJson(res, 404, { error: "user_not_found", id: userId });
70
+ logger.info({ userId }, "user deleted");
71
+ sendNoContent(res);
72
+ }
73
+
74
+ async function addContact(
75
+ req: IncomingMessage,
76
+ res: ServerResponse,
77
+ ctx: RouteContext,
78
+ ): Promise<void> {
79
+ const userId = ctx.params.id!;
80
+ const body = await readJsonBody(req);
81
+ const parsed = BatchAddContactsSchema.safeParse(body);
82
+ if (!parsed.success) return sendValidationError(res, parsed.error);
83
+
84
+ const user = await deps.userRepo.findById(ctx.projectId!, userId);
85
+ if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
86
+
87
+ if (Array.isArray(parsed.data)) {
88
+ const contactsList = parsed.data.map((c) => ({
89
+ userId,
90
+ channel: c.channel,
91
+ target: c.target,
92
+ preferences: c.preferences ?? {},
93
+ }));
94
+ await deps.contactRepo.upsertMany(ctx.projectId!, contactsList);
95
+ logger.info({ userId, count: contactsList.length }, "contacts batch added");
96
+ sendJson(res, 201, {
97
+ userId,
98
+ contacts: contactsList.map((c) => ({ channel: c.channel, target: c.target })),
99
+ });
100
+ } else {
101
+ await deps.contactRepo.upsert(
102
+ ctx.projectId!,
103
+ userId,
104
+ parsed.data.channel,
105
+ parsed.data.target,
106
+ parsed.data.preferences ?? {},
107
+ );
108
+ logger.info({ userId, channel: parsed.data.channel }, "contact added");
109
+ sendJson(res, 201, { userId, channel: parsed.data.channel, target: parsed.data.target });
110
+ }
111
+ }
112
+
113
+ async function deleteContact(
114
+ _req: IncomingMessage,
115
+ res: ServerResponse,
116
+ ctx: RouteContext,
117
+ ): Promise<void> {
118
+ const userId = ctx.params.id!;
119
+ const channelResult = ContactChannelSchema.safeParse(ctx.params.channel);
120
+ if (!channelResult.success)
121
+ return sendJson(res, 400, { error: "invalid_channel", channel: ctx.params.channel });
122
+
123
+ const deleted = await deps.contactRepo.delete(
124
+ ctx.projectId!,
125
+ userId,
126
+ channelResult.data,
127
+ ctx.params.target!,
128
+ );
129
+ if (!deleted) return sendJson(res, 404, { error: "contact_not_found" });
130
+ logger.info({ userId, channel: channelResult.data }, "contact deleted");
131
+ sendNoContent(res);
132
+ }
133
+
134
+ async function getUser(
135
+ req: IncomingMessage,
136
+ res: ServerResponse,
137
+ ctx: RouteContext,
138
+ ): Promise<void> {
139
+ const userId = ctx.params.id!;
140
+ const user = await deps.userRepo.findRecordById(ctx.projectId!, userId);
141
+ if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
142
+
143
+ const contacts = await deps.contactRepo.findByUserId(ctx.projectId!, userId);
144
+ sendJson(res, 200, { ...user, contacts });
145
+ }
146
+
147
+ async function getUserPreferences(
148
+ req: IncomingMessage,
149
+ res: ServerResponse,
150
+ ctx: RouteContext,
151
+ ): Promise<void> {
152
+ const userId = ctx.params.id!;
153
+ const user = await deps.userRepo.findRecordById(ctx.projectId!, userId);
154
+ if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
155
+
156
+ sendJson(res, 200, user.preferences);
157
+ }
158
+
159
+ async function updateUserPreferences(
160
+ req: IncomingMessage,
161
+ res: ServerResponse,
162
+ ctx: RouteContext,
163
+ ): Promise<void> {
164
+ const userId = ctx.params.id!;
165
+ const parsed = PreferencesSchema.safeParse(await readJsonBody(req));
166
+ if (!parsed.success) return sendValidationError(res, parsed.error);
167
+
168
+ const updated = await deps.userRepo.updatePartial(ctx.projectId!, userId, {
169
+ preferences: parsed.data,
170
+ });
171
+ if (!updated) return sendJson(res, 404, { error: "user_not_found", id: userId });
172
+
173
+ logger.info({ userId }, "user preferences updated");
174
+ sendJson(res, 200, { id: userId, preferences: parsed.data });
175
+ }
176
+
177
+ async function listUsers(
178
+ req: IncomingMessage,
179
+ res: ServerResponse,
180
+ ctx: RouteContext,
181
+ ): Promise<void> {
182
+ const limit = parseLimit(ctx, 50);
183
+ const cursor = getQueryParam(ctx, "cursor");
184
+ const search = getQueryParam(ctx, "search");
185
+ const segment = getQueryParam(ctx, "segment");
186
+ const language = getQueryParam(ctx, "language");
187
+ const timezone = getQueryParam(ctx, "timezone");
188
+ const channel = getQueryParam(ctx, "channel");
189
+
190
+ const filters =
191
+ search || segment || language || timezone || channel
192
+ ? { search, segment, language, timezone, channel }
193
+ : undefined;
194
+
195
+ const result = await deps.userRepo.list(ctx.projectId!, limit, cursor, filters);
196
+ sendJson(res, 200, result);
197
+ }
198
+
199
+ async function getUserContacts(
200
+ req: IncomingMessage,
201
+ res: ServerResponse,
202
+ ctx: RouteContext,
203
+ ): Promise<void> {
204
+ const userId = ctx.params.id!;
205
+ const contacts = await deps.contactRepo.findByUserId(ctx.projectId!, userId);
206
+ sendJson(res, 200, { contacts });
207
+ }
208
+
209
+ async function listSegments(
210
+ req: IncomingMessage,
211
+ res: ServerResponse,
212
+ ctx: RouteContext,
213
+ ): Promise<void> {
214
+ const segments = await deps.segmentRepo.listSegments(ctx.projectId!);
215
+ sendJson(res, 200, { segments });
216
+ }
217
+
218
+ async function getUserDetails(
219
+ _req: IncomingMessage,
220
+ res: ServerResponse,
221
+ ctx: RouteContext,
222
+ ): Promise<void> {
223
+ const userId = ctx.params.id!;
224
+ const user = await deps.userRepo.findRecordById(ctx.projectId!, userId);
225
+ if (!user) return sendJson(res, 404, { error: "user_not_found", id: userId });
226
+
227
+ const contacts = await deps.contactRepo.findByUserId(ctx.projectId!, userId);
228
+ const contactTargets = contacts.map((c) => c.target);
229
+ let logs: any[] = [];
230
+ if (contactTargets.length > 0) {
231
+ // One statement: fetching every task id the addresses were ever sent and
232
+ // passing them back as parameters failed outright past 65,535 sends.
233
+ const sentTo = deps.db
234
+ .select({ taskId: deliveryOutbox.taskId })
235
+ .from(deliveryOutbox)
236
+ .where(inArray(deliveryOutbox.destination, contactTargets));
237
+ logs = await deps.db
238
+ .select()
239
+ .from(messageLogs)
240
+ .where(and(eq(messageLogs.projectId, ctx.projectId!), inArray(messageLogs.taskId, sentTo)))
241
+ .orderBy(desc(messageLogs.timestamp))
242
+ .limit(50);
243
+ }
244
+
245
+ sendJson(res, 200, { ...user, contacts, logs });
246
+ }
247
+
248
+ return {
249
+ addUser,
250
+ updateUser,
251
+ deleteUser,
252
+ addContact,
253
+ deleteContact,
254
+ getUser,
255
+ getUserDetails,
256
+ getUserPreferences,
257
+ updateUserPreferences,
258
+ listUsers,
259
+ getUserContacts,
260
+ listSegments,
261
+ };
262
+ }