@niama/loops 0.2.0

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 (74) hide show
  1. package/README.md +506 -0
  2. package/dist/client/index.d.ts +510 -0
  3. package/dist/client/index.d.ts.map +1 -0
  4. package/dist/client/index.js +464 -0
  5. package/dist/component/_generated/api.d.ts +232 -0
  6. package/dist/component/_generated/api.d.ts.map +1 -0
  7. package/dist/component/_generated/api.js +30 -0
  8. package/dist/component/_generated/component.d.ts +245 -0
  9. package/dist/component/_generated/component.d.ts.map +1 -0
  10. package/dist/component/_generated/component.js +9 -0
  11. package/dist/component/_generated/dataModel.d.ts +46 -0
  12. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  13. package/dist/component/_generated/dataModel.js +10 -0
  14. package/dist/component/_generated/server.d.ts +121 -0
  15. package/dist/component/_generated/server.d.ts.map +1 -0
  16. package/dist/component/_generated/server.js +77 -0
  17. package/dist/component/actions.d.ts +159 -0
  18. package/dist/component/actions.d.ts.map +1 -0
  19. package/dist/component/actions.js +468 -0
  20. package/dist/component/aggregates.d.ts +42 -0
  21. package/dist/component/aggregates.d.ts.map +1 -0
  22. package/dist/component/aggregates.js +54 -0
  23. package/dist/component/convex.config.d.ts +3 -0
  24. package/dist/component/convex.config.d.ts.map +1 -0
  25. package/dist/component/convex.config.js +5 -0
  26. package/dist/component/helpers.d.ts +16 -0
  27. package/dist/component/helpers.d.ts.map +1 -0
  28. package/dist/component/helpers.js +98 -0
  29. package/dist/component/http.d.ts +3 -0
  30. package/dist/component/http.d.ts.map +1 -0
  31. package/dist/component/http.js +208 -0
  32. package/dist/component/mutations.d.ts +55 -0
  33. package/dist/component/mutations.d.ts.map +1 -0
  34. package/dist/component/mutations.js +167 -0
  35. package/dist/component/queries.d.ts +171 -0
  36. package/dist/component/queries.d.ts.map +1 -0
  37. package/dist/component/queries.js +516 -0
  38. package/dist/component/schema.d.ts +63 -0
  39. package/dist/component/schema.d.ts.map +1 -0
  40. package/dist/component/schema.js +16 -0
  41. package/dist/component/tables/contacts.d.ts +16 -0
  42. package/dist/component/tables/contacts.d.ts.map +1 -0
  43. package/dist/component/tables/contacts.js +16 -0
  44. package/dist/component/tables/emailOperations.d.ts +17 -0
  45. package/dist/component/tables/emailOperations.d.ts.map +1 -0
  46. package/dist/component/tables/emailOperations.js +17 -0
  47. package/dist/component/validators.d.ts +338 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +167 -0
  50. package/dist/test.d.ts +78 -0
  51. package/dist/test.d.ts.map +1 -0
  52. package/dist/test.js +16 -0
  53. package/dist/types.d.ts +39 -0
  54. package/dist/types.d.ts.map +1 -0
  55. package/dist/types.js +0 -0
  56. package/package.json +112 -0
  57. package/src/client/index.ts +618 -0
  58. package/src/component/_generated/api.ts +253 -0
  59. package/src/component/_generated/component.ts +291 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +161 -0
  62. package/src/component/actions.ts +556 -0
  63. package/src/component/aggregates.ts +89 -0
  64. package/src/component/convex.config.ts +8 -0
  65. package/src/component/helpers.ts +130 -0
  66. package/src/component/http.ts +236 -0
  67. package/src/component/mutations.ts +192 -0
  68. package/src/component/queries.ts +604 -0
  69. package/src/component/schema.ts +17 -0
  70. package/src/component/tables/contacts.ts +17 -0
  71. package/src/component/tables/emailOperations.ts +23 -0
  72. package/src/component/validators.ts +197 -0
  73. package/src/test.ts +27 -0
  74. package/src/types.ts +62 -0
@@ -0,0 +1,89 @@
1
+ import { TableAggregate } from "@convex-dev/aggregate";
2
+ import type { GenericMutationCtx, GenericQueryCtx } from "convex/server";
3
+ import type { DataModel, Doc } from "./_generated/dataModel";
4
+ import { components } from "./_generated/api";
5
+
6
+ // Cast components to the expected type for the aggregate library
7
+ // biome-ignore lint/suspicious/noExplicitAny: Component API type mismatch with aggregate library
8
+ const contactAggregateComponent = components.contactAggregate as any;
9
+
10
+ /**
11
+ * Aggregate for counting contacts.
12
+ * Uses userGroup as namespace for efficient filtered counting.
13
+ * Key is null since we only need counts, not ordering.
14
+ */
15
+ export const contactAggregate = new TableAggregate<{
16
+ Namespace: string | undefined;
17
+ Key: null;
18
+ DataModel: DataModel;
19
+ TableName: "contacts";
20
+ }>(contactAggregateComponent, {
21
+ namespace: (doc) => doc.userGroup,
22
+ sortKey: () => null,
23
+ });
24
+
25
+ type MutationCtx = GenericMutationCtx<DataModel>;
26
+ type QueryCtx = GenericQueryCtx<DataModel>;
27
+
28
+ /**
29
+ * Insert a contact into the aggregate
30
+ */
31
+ export async function aggregateInsert(
32
+ ctx: MutationCtx,
33
+ doc: Doc<"contacts">,
34
+ ): Promise<void> {
35
+ await contactAggregate.insertIfDoesNotExist(ctx, doc);
36
+ }
37
+
38
+ /**
39
+ * Delete a contact from the aggregate
40
+ */
41
+ export async function aggregateDelete(
42
+ ctx: MutationCtx,
43
+ doc: Doc<"contacts">,
44
+ ): Promise<void> {
45
+ await contactAggregate.deleteIfExists(ctx, doc);
46
+ }
47
+
48
+ /**
49
+ * Replace a contact in the aggregate (when userGroup changes)
50
+ */
51
+ export async function aggregateReplace(
52
+ ctx: MutationCtx,
53
+ oldDoc: Doc<"contacts">,
54
+ newDoc: Doc<"contacts">,
55
+ ): Promise<void> {
56
+ await contactAggregate.replaceOrInsert(ctx, oldDoc, newDoc);
57
+ }
58
+
59
+ /**
60
+ * Count contacts by userGroup namespace
61
+ */
62
+ export async function aggregateCountByUserGroup(
63
+ ctx: QueryCtx,
64
+ userGroup: string | undefined,
65
+ ): Promise<number> {
66
+ return await contactAggregate.count(ctx, { namespace: userGroup });
67
+ }
68
+
69
+ /**
70
+ * Count all contacts across all userGroups
71
+ */
72
+ export async function aggregateCountTotal(ctx: QueryCtx): Promise<number> {
73
+ let total = 0;
74
+ for await (const namespace of contactAggregate.iterNamespaces(ctx)) {
75
+ total += await contactAggregate.count(ctx, { namespace });
76
+ }
77
+ return total;
78
+ }
79
+
80
+ /**
81
+ * Clear and reinitialize the aggregate (for backfill)
82
+ */
83
+ export async function aggregateClear(
84
+ ctx: MutationCtx,
85
+ namespace?: string,
86
+ ): Promise<void> {
87
+ await contactAggregate.clear(ctx, { namespace });
88
+ }
89
+
@@ -0,0 +1,8 @@
1
+ import aggregate from "@convex-dev/aggregate/convex.config";
2
+ import { defineComponent } from "convex/server";
3
+
4
+ const component = defineComponent("loops");
5
+
6
+ component.use(aggregate, { name: "contactAggregate" });
7
+
8
+ export default component;
@@ -0,0 +1,130 @@
1
+ import type { HeadersInitParam } from "../types";
2
+
3
+ const allowedOrigin =
4
+ process.env.CONVEX_URL ??
5
+ process.env.NEXT_PUBLIC_CONVEX_URL ??
6
+ process.env.CONVEX_SITE_URL ??
7
+ process.env.NEXT_PUBLIC_CONVEX_SITE_URL ??
8
+ process.env.LOOPS_HTTP_ALLOWED_ORIGIN ??
9
+ process.env.CLIENT_ORIGIN ??
10
+ "*";
11
+
12
+ export const LOOPS_API_BASE_URL = "https://app.loops.so/api/v1";
13
+
14
+ export const sanitizeLoopsError = (
15
+ status: number,
16
+ _errorText: string,
17
+ ): Error => {
18
+ if (status === 401 || status === 403) {
19
+ return new Error("Authentication failed. Please check your API key.");
20
+ }
21
+ if (status === 404) {
22
+ return new Error("Resource not found.");
23
+ }
24
+ if (status === 429) {
25
+ return new Error("Rate limit exceeded. Please try again later.");
26
+ }
27
+ if (status >= 500) {
28
+ return new Error("Loops service error. Please try again later.");
29
+ }
30
+ return new Error(`Loops API error (${status}). Please try again.`);
31
+ };
32
+
33
+ export type LoopsRequestInit = Omit<RequestInit, "body"> & {
34
+ json?: unknown;
35
+ };
36
+
37
+ export const loopsFetch = async (
38
+ apiKey: string,
39
+ path: string,
40
+ init: LoopsRequestInit = {},
41
+ ) => {
42
+ const { json, ...rest } = init;
43
+ const headers = new Headers(rest.headers ?? {});
44
+ headers.set("Authorization", `Bearer ${apiKey}`);
45
+ if (json !== undefined && !headers.has("Content-Type")) {
46
+ headers.set("Content-Type", "application/json");
47
+ }
48
+
49
+ return fetch(`${LOOPS_API_BASE_URL}${path}`, {
50
+ ...rest,
51
+ headers,
52
+ // @ts-expect-error RequestInit in this build doesn't declare body
53
+ body: json !== undefined ? JSON.stringify(json) : rest.body,
54
+ });
55
+ };
56
+
57
+ export const buildCorsHeaders = (extra?: HeadersInitParam) => {
58
+ const headers = new Headers(extra ?? {});
59
+ headers.set("Access-Control-Allow-Origin", allowedOrigin);
60
+ headers.set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
61
+ headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
62
+ headers.set("Access-Control-Max-Age", "86400");
63
+ headers.set("Vary", "Origin");
64
+ return headers;
65
+ };
66
+
67
+ export const jsonResponse = (data: unknown, init?: ResponseInit) => {
68
+ const headers = buildCorsHeaders(
69
+ (init?.headers as HeadersInitParam | undefined) ?? undefined,
70
+ );
71
+ headers.set("Content-Type", "application/json");
72
+ return new Response(JSON.stringify(data), { ...init, headers });
73
+ };
74
+
75
+ export const emptyResponse = (init?: ResponseInit) => {
76
+ const headers = buildCorsHeaders(
77
+ (init?.headers as HeadersInitParam | undefined) ?? undefined,
78
+ );
79
+ return new Response(null, { ...init, headers });
80
+ };
81
+
82
+ export const readJsonBody = async <T>(request: Request): Promise<T> => {
83
+ try {
84
+ return (await request.json()) as T;
85
+ } catch (_error) {
86
+ throw new Error("Invalid JSON body");
87
+ }
88
+ };
89
+
90
+ export const booleanFromQuery = (value: string | null) => {
91
+ if (value === null) {
92
+ return undefined;
93
+ }
94
+ if (value === "true") {
95
+ return true;
96
+ }
97
+ if (value === "false") {
98
+ return false;
99
+ }
100
+ return undefined;
101
+ };
102
+
103
+ export const numberFromQuery = (value: string | null, fallback: number) => {
104
+ if (!value) {
105
+ return fallback;
106
+ }
107
+ const parsed = Number.parseInt(value, 10);
108
+ return Number.isNaN(parsed) ? fallback : parsed;
109
+ };
110
+
111
+ export const requireLoopsApiKey = () => {
112
+ const apiKey = process.env.LOOPS_API_KEY;
113
+ if (!apiKey) {
114
+ throw new Error(
115
+ "LOOPS_API_KEY environment variable must be set to use the HTTP API.",
116
+ );
117
+ }
118
+ return apiKey;
119
+ };
120
+
121
+ export const respondError = (error: unknown) => {
122
+ console.error("[loops:http]", error);
123
+ const message = error instanceof Error ? error.message : "Unexpected error";
124
+ const status =
125
+ error instanceof Error &&
126
+ error.message.includes("LOOPS_API_KEY environment variable")
127
+ ? 500
128
+ : 400;
129
+ return jsonResponse({ error: message }, { status });
130
+ };
@@ -0,0 +1,236 @@
1
+ import { httpRouter } from "convex/server";
2
+ import type {
3
+ ContactPayload,
4
+ DeleteContactPayload,
5
+ EventPayload,
6
+ TransactionalPayload,
7
+ TriggerPayload,
8
+ UpdateContactPayload,
9
+ } from "../types";
10
+ import { api } from "./_generated/api";
11
+ import { httpAction } from "./_generated/server";
12
+ import {
13
+ booleanFromQuery,
14
+ buildCorsHeaders,
15
+ emptyResponse,
16
+ jsonResponse,
17
+ numberFromQuery,
18
+ readJsonBody,
19
+ requireLoopsApiKey,
20
+ respondError,
21
+ } from "./helpers";
22
+
23
+ const http = httpRouter();
24
+
25
+ http.route({
26
+ pathPrefix: "/loops/",
27
+ method: "OPTIONS",
28
+ handler: httpAction(async (_ctx, request) => {
29
+ const headers = buildCorsHeaders();
30
+ const requestedHeaders = request.headers.get(
31
+ "Access-Control-Request-Headers",
32
+ );
33
+ if (requestedHeaders) {
34
+ headers.set("Access-Control-Allow-Headers", requestedHeaders);
35
+ }
36
+ const requestedMethod = request.headers.get(
37
+ "Access-Control-Request-Method",
38
+ );
39
+ if (requestedMethod) {
40
+ headers.set("Access-Control-Allow-Methods", `${requestedMethod},OPTIONS`);
41
+ }
42
+ return new Response(null, { status: 204, headers });
43
+ }),
44
+ });
45
+
46
+ http.route({
47
+ path: "/loops/contacts",
48
+ method: "POST",
49
+ handler: httpAction(async (ctx, request) => {
50
+ try {
51
+ const contact = await readJsonBody<ContactPayload>(request);
52
+ const data = await ctx.runAction(api.actions.addContact, {
53
+ apiKey: requireLoopsApiKey(),
54
+ contact,
55
+ });
56
+ return jsonResponse(data, { status: 201 });
57
+ } catch (error) {
58
+ return respondError(error);
59
+ }
60
+ }),
61
+ });
62
+
63
+ http.route({
64
+ path: "/loops/contacts",
65
+ method: "PUT",
66
+ handler: httpAction(async (ctx, request) => {
67
+ try {
68
+ const payload = await readJsonBody<UpdateContactPayload>(request);
69
+ if (!payload.email) {
70
+ throw new Error("email is required");
71
+ }
72
+ const data = await ctx.runAction(api.actions.updateContact, {
73
+ apiKey: requireLoopsApiKey(),
74
+ email: payload.email,
75
+ dataVariables: payload.dataVariables,
76
+ firstName: payload.firstName,
77
+ lastName: payload.lastName,
78
+ userId: payload.userId,
79
+ source: payload.source,
80
+ subscribed: payload.subscribed,
81
+ userGroup: payload.userGroup,
82
+ });
83
+ return jsonResponse(data);
84
+ } catch (error) {
85
+ return respondError(error);
86
+ }
87
+ }),
88
+ });
89
+
90
+ http.route({
91
+ path: "/loops/contacts",
92
+ method: "GET",
93
+ handler: httpAction(async (ctx, request) => {
94
+ try {
95
+ const url = new URL(request.url);
96
+ const email = url.searchParams.get("email");
97
+ if (email) {
98
+ const data = await ctx.runAction(api.actions.findContact, {
99
+ apiKey: requireLoopsApiKey(),
100
+ email,
101
+ });
102
+ return jsonResponse(data);
103
+ }
104
+
105
+ const data = await ctx.runQuery(api.queries.listContacts, {
106
+ userGroup: url.searchParams.get("userGroup") ?? undefined,
107
+ source: url.searchParams.get("source") ?? undefined,
108
+ subscribed: booleanFromQuery(url.searchParams.get("subscribed")),
109
+ limit: numberFromQuery(url.searchParams.get("limit"), 100),
110
+ cursor: url.searchParams.get("cursor") ?? null,
111
+ });
112
+ return jsonResponse(data);
113
+ } catch (error) {
114
+ return respondError(error);
115
+ }
116
+ }),
117
+ });
118
+
119
+ http.route({
120
+ path: "/loops/contacts",
121
+ method: "DELETE",
122
+ handler: httpAction(async (ctx, request) => {
123
+ try {
124
+ const payload = await readJsonBody<DeleteContactPayload>(request);
125
+ if (!payload.email) {
126
+ throw new Error("email is required");
127
+ }
128
+ await ctx.runAction(api.actions.deleteContact, {
129
+ apiKey: requireLoopsApiKey(),
130
+ email: payload.email,
131
+ });
132
+ return emptyResponse({ status: 204 });
133
+ } catch (error) {
134
+ return respondError(error);
135
+ }
136
+ }),
137
+ });
138
+
139
+ http.route({
140
+ path: "/loops/transactional",
141
+ method: "POST",
142
+ handler: httpAction(async (ctx, request) => {
143
+ try {
144
+ const payload = await readJsonBody<TransactionalPayload>(request);
145
+ if (!payload.transactionalId) {
146
+ throw new Error("transactionalId is required");
147
+ }
148
+ if (!payload.email) {
149
+ throw new Error("email is required");
150
+ }
151
+ const data = await ctx.runAction(api.actions.sendTransactional, {
152
+ apiKey: requireLoopsApiKey(),
153
+ transactionalId: payload.transactionalId,
154
+ email: payload.email,
155
+ dataVariables: payload.dataVariables,
156
+ idempotencyKey: payload.idempotencyKey,
157
+ });
158
+ return jsonResponse(data);
159
+ } catch (error) {
160
+ return respondError(error);
161
+ }
162
+ }),
163
+ });
164
+
165
+ http.route({
166
+ path: "/loops/events",
167
+ method: "POST",
168
+ handler: httpAction(async (ctx, request) => {
169
+ try {
170
+ const payload = await readJsonBody<EventPayload>(request);
171
+ if (!payload.email) {
172
+ throw new Error("email is required");
173
+ }
174
+ if (!payload.eventName) {
175
+ throw new Error("eventName is required");
176
+ }
177
+ const data = await ctx.runAction(api.actions.sendEvent, {
178
+ apiKey: requireLoopsApiKey(),
179
+ email: payload.email,
180
+ eventName: payload.eventName,
181
+ eventProperties: payload.eventProperties,
182
+ });
183
+ return jsonResponse(data);
184
+ } catch (error) {
185
+ return respondError(error);
186
+ }
187
+ }),
188
+ });
189
+
190
+ http.route({
191
+ path: "/loops/trigger",
192
+ method: "POST",
193
+ handler: httpAction(async (ctx, request) => {
194
+ try {
195
+ const payload = await readJsonBody<TriggerPayload>(request);
196
+ if (!payload.loopId) {
197
+ throw new Error("loopId is required");
198
+ }
199
+ if (!payload.email) {
200
+ throw new Error("email is required");
201
+ }
202
+ const data = await ctx.runAction(api.actions.triggerLoop, {
203
+ apiKey: requireLoopsApiKey(),
204
+ loopId: payload.loopId,
205
+ email: payload.email,
206
+ dataVariables: payload.dataVariables,
207
+ eventName: payload.eventName,
208
+ });
209
+ return jsonResponse(data);
210
+ } catch (error) {
211
+ return respondError(error);
212
+ }
213
+ }),
214
+ });
215
+
216
+ http.route({
217
+ path: "/loops/stats",
218
+ method: "GET",
219
+ handler: httpAction(async (ctx, request) => {
220
+ try {
221
+ const url = new URL(request.url);
222
+ const timeWindowMs = numberFromQuery(
223
+ url.searchParams.get("timeWindowMs"),
224
+ 86400000,
225
+ );
226
+ const data = await ctx.runQuery(api.queries.getEmailStats, {
227
+ timeWindowMs,
228
+ });
229
+ return jsonResponse(data);
230
+ } catch (error) {
231
+ return respondError(error);
232
+ }
233
+ }),
234
+ });
235
+
236
+ export default http;
@@ -0,0 +1,192 @@
1
+ import { v } from "convex/values";
2
+ import { paginator } from "convex-helpers/server/pagination";
3
+ import type { Doc } from "./_generated/dataModel";
4
+ import { internalMutation, mutation } from "./_generated/server";
5
+ import {
6
+ aggregateClear,
7
+ aggregateDelete,
8
+ aggregateInsert,
9
+ aggregateReplace,
10
+ } from "./aggregates";
11
+ import schema from "./schema";
12
+ import {
13
+ backfillResponseValidator,
14
+ operationTypeValidator,
15
+ } from "./validators";
16
+
17
+ /**
18
+ * Internal mutation to store/update a contact in the database
19
+ */
20
+ export const storeContact = internalMutation({
21
+ args: {
22
+ email: v.string(),
23
+ firstName: v.optional(v.string()),
24
+ lastName: v.optional(v.string()),
25
+ userId: v.optional(v.string()),
26
+ source: v.optional(v.string()),
27
+ subscribed: v.optional(v.boolean()),
28
+ userGroup: v.optional(v.string()),
29
+ loopsContactId: v.optional(v.string()),
30
+ },
31
+ returns: v.null(),
32
+ handler: async (ctx, args) => {
33
+ const now = Date.now();
34
+ const existing = await ctx.db
35
+ .query("contacts")
36
+ .withIndex("email", (q) => q.eq("email", args.email))
37
+ .unique();
38
+
39
+ if (existing) {
40
+ // Update the contact
41
+ await ctx.db.patch(existing._id, {
42
+ firstName: args.firstName,
43
+ lastName: args.lastName,
44
+ userId: args.userId,
45
+ source: args.source,
46
+ subscribed: args.subscribed ?? existing.subscribed,
47
+ userGroup: args.userGroup,
48
+ loopsContactId: args.loopsContactId,
49
+ updatedAt: now,
50
+ });
51
+
52
+ // Get the updated document and update aggregate if userGroup changed
53
+ const updated = await ctx.db.get(existing._id);
54
+ if (updated && existing.userGroup !== updated.userGroup) {
55
+ await aggregateReplace(ctx, existing, updated);
56
+ }
57
+ } else {
58
+ // Insert new contact
59
+ const id = await ctx.db.insert("contacts", {
60
+ email: args.email,
61
+ firstName: args.firstName,
62
+ lastName: args.lastName,
63
+ userId: args.userId,
64
+ source: args.source,
65
+ subscribed: args.subscribed ?? true,
66
+ userGroup: args.userGroup,
67
+ loopsContactId: args.loopsContactId,
68
+ createdAt: now,
69
+ updatedAt: now,
70
+ });
71
+
72
+ // Add to aggregate for counting
73
+ const newDoc = await ctx.db.get(id);
74
+ if (newDoc) {
75
+ await aggregateInsert(ctx, newDoc);
76
+ }
77
+ }
78
+ return null;
79
+ },
80
+ });
81
+
82
+ /**
83
+ * Internal mutation to delete a contact from the database
84
+ */
85
+ export const removeContact = internalMutation({
86
+ args: {
87
+ email: v.string(),
88
+ },
89
+ returns: v.null(),
90
+ handler: async (ctx, args) => {
91
+ const existing = await ctx.db
92
+ .query("contacts")
93
+ .withIndex("email", (q) => q.eq("email", args.email))
94
+ .unique();
95
+
96
+ if (existing) {
97
+ // Remove from aggregate first (before deleting the document)
98
+ await aggregateDelete(ctx, existing);
99
+ await ctx.db.delete(existing._id);
100
+ }
101
+ return null;
102
+ },
103
+ });
104
+
105
+ /**
106
+ * Internal mutation to log an email operation for monitoring
107
+ */
108
+ export const logEmailOperation = internalMutation({
109
+ args: {
110
+ operationType: operationTypeValidator,
111
+ email: v.string(),
112
+ actorId: v.optional(v.string()),
113
+ transactionalId: v.optional(v.string()),
114
+ campaignId: v.optional(v.string()),
115
+ loopId: v.optional(v.string()),
116
+ eventName: v.optional(v.string()),
117
+ success: v.boolean(),
118
+ messageId: v.optional(v.string()),
119
+ metadata: v.optional(v.record(v.string(), v.any())),
120
+ },
121
+ returns: v.null(),
122
+ handler: async (ctx, args) => {
123
+ const operationData: Omit<
124
+ Doc<"emailOperations">,
125
+ "_id" | "_creationTime"
126
+ > = {
127
+ operationType: args.operationType,
128
+ email: args.email,
129
+ timestamp: Date.now(),
130
+ success: args.success,
131
+ actorId: args.actorId,
132
+ transactionalId: args.transactionalId,
133
+ campaignId: args.campaignId,
134
+ loopId: args.loopId,
135
+ eventName: args.eventName,
136
+ messageId: args.messageId,
137
+ metadata: args.metadata,
138
+ };
139
+
140
+ await ctx.db.insert("emailOperations", operationData);
141
+ return null;
142
+ },
143
+ });
144
+
145
+ /**
146
+ * Backfill the contact aggregate with existing contacts.
147
+ * Run this mutation after upgrading to a version with aggregate support.
148
+ *
149
+ * This processes contacts in batches to avoid timeout issues with large datasets.
150
+ * Call repeatedly with the returned cursor until isDone is true.
151
+ *
152
+ * Usage:
153
+ * 1. First call with clear: true to reset the aggregate
154
+ * 2. Subsequent calls with the returned cursor until isDone is true
155
+ */
156
+ export const backfillContactAggregate = mutation({
157
+ args: {
158
+ cursor: v.optional(v.union(v.string(), v.null())),
159
+ batchSize: v.optional(v.number()),
160
+ clear: v.optional(v.boolean()),
161
+ },
162
+ returns: backfillResponseValidator,
163
+ handler: async (ctx, args) => {
164
+ const batchSize = args.batchSize ?? 100;
165
+
166
+ // Clear aggregate on first call if requested
167
+ if (args.clear && !args.cursor) {
168
+ await aggregateClear(ctx);
169
+ }
170
+
171
+ const paginationOpts = {
172
+ cursor: args.cursor ?? null,
173
+ numItems: Math.min(Math.max(1, batchSize), 500),
174
+ };
175
+
176
+ const result = await paginator(ctx.db, schema)
177
+ .query("contacts")
178
+ .order("asc")
179
+ .paginate(paginationOpts);
180
+
181
+ // Insert each contact into the aggregate
182
+ for (const contact of result.page) {
183
+ await aggregateInsert(ctx, contact);
184
+ }
185
+
186
+ return {
187
+ processed: result.page.length,
188
+ cursor: result.continueCursor,
189
+ isDone: result.isDone,
190
+ };
191
+ },
192
+ });