@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,159 @@
1
+ /**
2
+ * Add or update a contact in Loops
3
+ * This function tries to create a contact, and if the email already exists (409),
4
+ * it falls back to updating the contact instead.
5
+ */
6
+ export declare const addContact: import("convex/server").RegisteredAction<"public", {
7
+ apiKey: string;
8
+ contact: {
9
+ firstName?: string | undefined;
10
+ lastName?: string | undefined;
11
+ userId?: string | undefined;
12
+ source?: string | undefined;
13
+ subscribed?: boolean | undefined;
14
+ userGroup?: string | undefined;
15
+ email: string;
16
+ };
17
+ }, Promise<{
18
+ success: boolean;
19
+ id: string | undefined;
20
+ }>>;
21
+ /**
22
+ * Update an existing contact in Loops
23
+ */
24
+ export declare const updateContact: import("convex/server").RegisteredAction<"public", {
25
+ firstName?: string | undefined;
26
+ lastName?: string | undefined;
27
+ userId?: string | undefined;
28
+ source?: string | undefined;
29
+ subscribed?: boolean | undefined;
30
+ userGroup?: string | undefined;
31
+ dataVariables?: Record<string, any> | undefined;
32
+ email: string;
33
+ apiKey: string;
34
+ }, Promise<{
35
+ success: boolean;
36
+ }>>;
37
+ /**
38
+ * Send a transactional email using a transactional ID
39
+ */
40
+ export declare const sendTransactional: import("convex/server").RegisteredAction<"public", {
41
+ dataVariables?: Record<string, any> | undefined;
42
+ idempotencyKey?: string | undefined;
43
+ email: string;
44
+ transactionalId: string;
45
+ apiKey: string;
46
+ }, Promise<{
47
+ success: boolean;
48
+ messageId?: undefined;
49
+ } | {
50
+ success: boolean;
51
+ messageId: string;
52
+ }>>;
53
+ /**
54
+ * Send an event to Loops to trigger email workflows
55
+ */
56
+ export declare const sendEvent: import("convex/server").RegisteredAction<"public", {
57
+ eventProperties?: Record<string, any> | undefined;
58
+ email: string;
59
+ eventName: string;
60
+ apiKey: string;
61
+ }, Promise<{
62
+ success: boolean;
63
+ }>>;
64
+ /**
65
+ * Delete a contact from Loops
66
+ */
67
+ export declare const deleteContact: import("convex/server").RegisteredAction<"public", {
68
+ email: string;
69
+ apiKey: string;
70
+ }, Promise<{
71
+ success: boolean;
72
+ }>>;
73
+ /**
74
+ * Trigger a loop for a contact
75
+ * Note: Loops in Loops.so are triggered through events, not a direct API endpoint.
76
+ * This function uses the events endpoint to trigger the loop.
77
+ * The loop must be configured in the Loops dashboard to listen for events.
78
+ *
79
+ * IMPORTANT: Loops.so doesn't have a direct /loops/trigger endpoint.
80
+ * Loops are triggered by sending events. Make sure your loop in the dashboard
81
+ * is configured to trigger on an event name (e.g., "loop_trigger").
82
+ *
83
+ * If you need to trigger a specific loop, you should:
84
+ * 1. Configure the loop in the dashboard to listen for a specific event name
85
+ * 2. Use sendEvent() with that event name instead
86
+ *
87
+ * This function is kept for backwards compatibility but works by sending an event.
88
+ */
89
+ export declare const triggerLoop: import("convex/server").RegisteredAction<"public", {
90
+ eventName?: string | undefined;
91
+ dataVariables?: Record<string, any> | undefined;
92
+ email: string;
93
+ loopId: string;
94
+ apiKey: string;
95
+ }, Promise<{
96
+ success: boolean;
97
+ warning: string;
98
+ }>>;
99
+ /**
100
+ * Find a contact by email
101
+ * Retrieves contact information from Loops
102
+ * Note: Loops API may return either an object or an array
103
+ */
104
+ export declare const findContact: import("convex/server").RegisteredAction<"public", {
105
+ email: string;
106
+ apiKey: string;
107
+ }, Promise<{
108
+ success: boolean;
109
+ contact: Record<string, unknown> | undefined;
110
+ }>>;
111
+ /**
112
+ * Batch create contacts
113
+ * Creates multiple contacts sequentially using the single contact create endpoint.
114
+ * Note: Loops.so doesn't have a batch endpoint, so we create contacts one by one.
115
+ */
116
+ export declare const batchCreateContacts: import("convex/server").RegisteredAction<"public", {
117
+ contacts: {
118
+ firstName?: string | undefined;
119
+ lastName?: string | undefined;
120
+ userId?: string | undefined;
121
+ source?: string | undefined;
122
+ subscribed?: boolean | undefined;
123
+ userGroup?: string | undefined;
124
+ email: string;
125
+ }[];
126
+ apiKey: string;
127
+ }, Promise<{
128
+ success: boolean;
129
+ created: number;
130
+ failed: number;
131
+ results: {
132
+ email: string;
133
+ success: boolean;
134
+ error?: string;
135
+ }[];
136
+ }>>;
137
+ /**
138
+ * Unsubscribe a contact
139
+ * Unsubscribes a contact from receiving emails (they remain in the system)
140
+ * Uses the update endpoint with subscribed: false as per Loops API
141
+ */
142
+ export declare const unsubscribeContact: import("convex/server").RegisteredAction<"public", {
143
+ email: string;
144
+ apiKey: string;
145
+ }, Promise<{
146
+ success: boolean;
147
+ }>>;
148
+ /**
149
+ * Resubscribe a contact
150
+ * Resubscribes a previously unsubscribed contact
151
+ * Uses the update endpoint with subscribed: true as per Loops API
152
+ */
153
+ export declare const resubscribeContact: import("convex/server").RegisteredAction<"public", {
154
+ email: string;
155
+ apiKey: string;
156
+ }, Promise<{
157
+ success: boolean;
158
+ }>>;
159
+ //# sourceMappingURL=actions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../src/component/actions.ts"],"names":[],"mappings":"AAcA;;;;GAIG;AACH,eAAO,MAAM,UAAU;;;;;;;;;;;;;;GA4GrB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;;;GA8CxB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;GAoD5B,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,SAAS;;;;;;;GAuCpB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,aAAa;;;;;GAwBxB,CAAC;AAEH;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW;;;;;;;;;GAyDtB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,WAAW;;;;;aA0CD,0BAAqB,SAAS;GAGnD,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;eASA,MAAM;iBAAW,OAAO;gBAAU,MAAM;;GAwCtE,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,kBAAkB;;;;;GAyB7B,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,kBAAkB;;;;;GAyB7B,CAAC"}
@@ -0,0 +1,468 @@
1
+ import { v } from "convex/values";
2
+ import { api, internal } from "./_generated/api";
3
+ import { action } from "./_generated/server";
4
+ import { loopsFetch, sanitizeLoopsError } from "./helpers";
5
+ import { batchCreateResponseValidator, contactValidator, findContactResponseValidator, successResponseValidator, successWithIdResponseValidator, successWithMessageIdResponseValidator, successWithWarningResponseValidator, } from "./validators";
6
+ /**
7
+ * Add or update a contact in Loops
8
+ * This function tries to create a contact, and if the email already exists (409),
9
+ * it falls back to updating the contact instead.
10
+ */
11
+ export const addContact = action({
12
+ args: {
13
+ apiKey: v.string(),
14
+ contact: contactValidator,
15
+ },
16
+ returns: successWithIdResponseValidator,
17
+ handler: async (ctx, args) => {
18
+ const createResponse = await loopsFetch(args.apiKey, "/contacts/create", {
19
+ method: "POST",
20
+ json: args.contact,
21
+ });
22
+ if (!createResponse.ok) {
23
+ const errorText = await createResponse.text();
24
+ if (createResponse.status === 409) {
25
+ console.log(`Contact ${args.contact.email} already exists, updating instead`);
26
+ const findResponse = await loopsFetch(args.apiKey, `/contacts/find?email=${encodeURIComponent(args.contact.email)}`, { method: "GET" });
27
+ if (!findResponse.ok) {
28
+ const findErrorText = await findResponse.text();
29
+ console.error(`Failed to find existing contact [${findResponse.status}]:`, findErrorText);
30
+ }
31
+ const updateResponse = await loopsFetch(args.apiKey, "/contacts/update", {
32
+ method: "PUT",
33
+ json: {
34
+ email: args.contact.email,
35
+ firstName: args.contact.firstName,
36
+ lastName: args.contact.lastName,
37
+ userId: args.contact.userId,
38
+ source: args.contact.source,
39
+ subscribed: args.contact.subscribed,
40
+ userGroup: args.contact.userGroup,
41
+ },
42
+ });
43
+ if (!updateResponse.ok) {
44
+ const updateErrorText = await updateResponse.text();
45
+ console.error(`Loops API error [${updateResponse.status}]:`, updateErrorText);
46
+ throw sanitizeLoopsError(updateResponse.status, updateErrorText);
47
+ }
48
+ // Get contact ID if available
49
+ let contactId;
50
+ if (findResponse.ok) {
51
+ const findData = (await findResponse.json());
52
+ contactId = findData.id;
53
+ }
54
+ // Store/update in our database
55
+ await ctx.runMutation(internal.mutations.storeContact, {
56
+ email: args.contact.email,
57
+ firstName: args.contact.firstName,
58
+ lastName: args.contact.lastName,
59
+ userId: args.contact.userId,
60
+ source: args.contact.source,
61
+ subscribed: args.contact.subscribed,
62
+ userGroup: args.contact.userGroup,
63
+ loopsContactId: contactId,
64
+ });
65
+ return {
66
+ success: true,
67
+ id: contactId,
68
+ };
69
+ }
70
+ console.error(`Loops API error [${createResponse.status}]:`, errorText);
71
+ throw sanitizeLoopsError(createResponse.status, errorText);
72
+ }
73
+ // Contact was created successfully
74
+ const data = (await createResponse.json());
75
+ await ctx.runMutation(internal.mutations.storeContact, {
76
+ email: args.contact.email,
77
+ firstName: args.contact.firstName,
78
+ lastName: args.contact.lastName,
79
+ userId: args.contact.userId,
80
+ source: args.contact.source,
81
+ subscribed: args.contact.subscribed,
82
+ userGroup: args.contact.userGroup,
83
+ loopsContactId: data.id,
84
+ });
85
+ return {
86
+ success: true,
87
+ id: data.id,
88
+ };
89
+ },
90
+ });
91
+ /**
92
+ * Update an existing contact in Loops
93
+ */
94
+ export const updateContact = action({
95
+ args: {
96
+ apiKey: v.string(),
97
+ email: v.string(),
98
+ dataVariables: v.optional(v.record(v.string(), v.any())),
99
+ firstName: v.optional(v.string()),
100
+ lastName: v.optional(v.string()),
101
+ userId: v.optional(v.string()),
102
+ source: v.optional(v.string()),
103
+ subscribed: v.optional(v.boolean()),
104
+ userGroup: v.optional(v.string()),
105
+ },
106
+ returns: successResponseValidator,
107
+ handler: async (ctx, args) => {
108
+ const response = await loopsFetch(args.apiKey, "/contacts/update", {
109
+ method: "PUT",
110
+ json: {
111
+ email: args.email,
112
+ dataVariables: args.dataVariables,
113
+ firstName: args.firstName,
114
+ lastName: args.lastName,
115
+ userId: args.userId,
116
+ source: args.source,
117
+ subscribed: args.subscribed,
118
+ userGroup: args.userGroup,
119
+ },
120
+ });
121
+ if (!response.ok) {
122
+ const errorText = await response.text();
123
+ console.error(`Loops API error [${response.status}]:`, errorText);
124
+ throw sanitizeLoopsError(response.status, errorText);
125
+ }
126
+ await ctx.runMutation(internal.mutations.storeContact, {
127
+ email: args.email,
128
+ firstName: args.firstName,
129
+ lastName: args.lastName,
130
+ userId: args.userId,
131
+ source: args.source,
132
+ subscribed: args.subscribed,
133
+ userGroup: args.userGroup,
134
+ });
135
+ return { success: true };
136
+ },
137
+ });
138
+ /**
139
+ * Send a transactional email using a transactional ID
140
+ */
141
+ export const sendTransactional = action({
142
+ args: {
143
+ apiKey: v.string(),
144
+ transactionalId: v.string(),
145
+ email: v.string(),
146
+ dataVariables: v.optional(v.record(v.string(), v.any())),
147
+ idempotencyKey: v.optional(v.string()),
148
+ },
149
+ returns: successWithMessageIdResponseValidator,
150
+ handler: async (ctx, args) => {
151
+ const response = await loopsFetch(args.apiKey, "/transactional", {
152
+ headers: args.idempotencyKey === undefined
153
+ ? undefined
154
+ : {
155
+ "Idempotency-Key": args.idempotencyKey,
156
+ },
157
+ method: "POST",
158
+ json: {
159
+ transactionalId: args.transactionalId,
160
+ email: args.email,
161
+ dataVariables: args.dataVariables,
162
+ },
163
+ });
164
+ if (!(response.ok || response.status === 409)) {
165
+ const errorText = await response.text();
166
+ console.error(`Loops API error [${response.status}]:`, errorText);
167
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
168
+ operationType: "transactional",
169
+ email: args.email,
170
+ success: false,
171
+ transactionalId: args.transactionalId,
172
+ });
173
+ throw sanitizeLoopsError(response.status, errorText);
174
+ }
175
+ const data = (await response.json());
176
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
177
+ operationType: "transactional",
178
+ email: args.email,
179
+ success: true,
180
+ transactionalId: args.transactionalId,
181
+ messageId: data.messageId,
182
+ });
183
+ return data.messageId === undefined
184
+ ? { success: true }
185
+ : { success: true, messageId: data.messageId };
186
+ },
187
+ });
188
+ /**
189
+ * Send an event to Loops to trigger email workflows
190
+ */
191
+ export const sendEvent = action({
192
+ args: {
193
+ apiKey: v.string(),
194
+ email: v.string(),
195
+ eventName: v.string(),
196
+ eventProperties: v.optional(v.record(v.string(), v.any())),
197
+ },
198
+ returns: successResponseValidator,
199
+ handler: async (ctx, args) => {
200
+ const response = await loopsFetch(args.apiKey, "/events/send", {
201
+ method: "POST",
202
+ json: {
203
+ email: args.email,
204
+ eventName: args.eventName,
205
+ eventProperties: args.eventProperties,
206
+ },
207
+ });
208
+ if (!response.ok) {
209
+ const errorText = await response.text();
210
+ console.error(`Loops API error [${response.status}]:`, errorText);
211
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
212
+ operationType: "event",
213
+ email: args.email,
214
+ success: false,
215
+ eventName: args.eventName,
216
+ });
217
+ throw sanitizeLoopsError(response.status, errorText);
218
+ }
219
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
220
+ operationType: "event",
221
+ email: args.email,
222
+ success: true,
223
+ eventName: args.eventName,
224
+ });
225
+ return { success: true };
226
+ },
227
+ });
228
+ /**
229
+ * Delete a contact from Loops
230
+ */
231
+ export const deleteContact = action({
232
+ args: {
233
+ apiKey: v.string(),
234
+ email: v.string(),
235
+ },
236
+ returns: successResponseValidator,
237
+ handler: async (ctx, args) => {
238
+ const response = await loopsFetch(args.apiKey, "/contacts/delete", {
239
+ method: "POST",
240
+ json: { email: args.email },
241
+ });
242
+ if (!response.ok) {
243
+ const errorText = await response.text();
244
+ console.error(`Loops API error [${response.status}]:`, errorText);
245
+ throw sanitizeLoopsError(response.status, errorText);
246
+ }
247
+ await ctx.runMutation(internal.mutations.removeContact, {
248
+ email: args.email,
249
+ });
250
+ return { success: true };
251
+ },
252
+ });
253
+ /**
254
+ * Trigger a loop for a contact
255
+ * Note: Loops in Loops.so are triggered through events, not a direct API endpoint.
256
+ * This function uses the events endpoint to trigger the loop.
257
+ * The loop must be configured in the Loops dashboard to listen for events.
258
+ *
259
+ * IMPORTANT: Loops.so doesn't have a direct /loops/trigger endpoint.
260
+ * Loops are triggered by sending events. Make sure your loop in the dashboard
261
+ * is configured to trigger on an event name (e.g., "loop_trigger").
262
+ *
263
+ * If you need to trigger a specific loop, you should:
264
+ * 1. Configure the loop in the dashboard to listen for a specific event name
265
+ * 2. Use sendEvent() with that event name instead
266
+ *
267
+ * This function is kept for backwards compatibility but works by sending an event.
268
+ */
269
+ export const triggerLoop = action({
270
+ args: {
271
+ apiKey: v.string(),
272
+ loopId: v.string(),
273
+ email: v.string(),
274
+ dataVariables: v.optional(v.record(v.string(), v.any())),
275
+ eventName: v.optional(v.string()),
276
+ },
277
+ returns: successWithWarningResponseValidator,
278
+ handler: async (ctx, args) => {
279
+ // Loops.so doesn't have a /loops/trigger endpoint
280
+ // Loops are triggered through events. We'll use the events endpoint.
281
+ // Default event name if not provided
282
+ const eventName = args.eventName || `loop_${args.loopId}`;
283
+ try {
284
+ // Send event to trigger the loop
285
+ await ctx.runAction(api.actions.sendEvent, {
286
+ apiKey: args.apiKey,
287
+ email: args.email,
288
+ eventName,
289
+ eventProperties: {
290
+ ...args.dataVariables,
291
+ loopId: args.loopId, // Include loopId in event properties
292
+ },
293
+ });
294
+ // Log as loop operation
295
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
296
+ operationType: "loop",
297
+ email: args.email,
298
+ success: true,
299
+ loopId: args.loopId,
300
+ eventName,
301
+ });
302
+ return {
303
+ success: true,
304
+ warning: "Loops are triggered via events. Ensure your loop is configured to listen for this event.",
305
+ };
306
+ }
307
+ catch (error) {
308
+ // Log failed loop operation
309
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
310
+ operationType: "loop",
311
+ email: args.email,
312
+ success: false,
313
+ loopId: args.loopId,
314
+ eventName,
315
+ metadata: {
316
+ error: error instanceof Error ? error.message : String(error),
317
+ },
318
+ });
319
+ throw error;
320
+ }
321
+ },
322
+ });
323
+ /**
324
+ * Find a contact by email
325
+ * Retrieves contact information from Loops
326
+ * Note: Loops API may return either an object or an array
327
+ */
328
+ export const findContact = action({
329
+ args: {
330
+ apiKey: v.string(),
331
+ email: v.string(),
332
+ },
333
+ returns: findContactResponseValidator,
334
+ handler: async (_ctx, args) => {
335
+ const response = await loopsFetch(args.apiKey, `/contacts/find?email=${encodeURIComponent(args.email)}`, { method: "GET" });
336
+ if (!response.ok) {
337
+ if (response.status === 404) {
338
+ return { success: false, contact: undefined };
339
+ }
340
+ const errorText = await response.text();
341
+ console.error(`Loops API error [${response.status}]:`, errorText);
342
+ throw sanitizeLoopsError(response.status, errorText);
343
+ }
344
+ const data = (await response.json());
345
+ // Handle case where Loops returns an array instead of a single object
346
+ let contact = Array.isArray(data) ? data[0] : data;
347
+ // Convert null values to undefined for optional fields
348
+ if (contact) {
349
+ contact = Object.fromEntries(Object.entries(contact).map(([key, value]) => [
350
+ key,
351
+ value === null ? undefined : value,
352
+ ]));
353
+ }
354
+ return {
355
+ success: true,
356
+ contact: contact,
357
+ };
358
+ },
359
+ });
360
+ /**
361
+ * Batch create contacts
362
+ * Creates multiple contacts sequentially using the single contact create endpoint.
363
+ * Note: Loops.so doesn't have a batch endpoint, so we create contacts one by one.
364
+ */
365
+ export const batchCreateContacts = action({
366
+ args: {
367
+ apiKey: v.string(),
368
+ contacts: v.array(contactValidator),
369
+ },
370
+ returns: batchCreateResponseValidator,
371
+ handler: async (ctx, args) => {
372
+ let created = 0;
373
+ let failed = 0;
374
+ const results = [];
375
+ // Create contacts one by one since Loops.so doesn't have a batch endpoint
376
+ for (const contact of args.contacts) {
377
+ try {
378
+ // Use the addContact function which handles create/update logic
379
+ const result = await ctx.runAction(api.actions.addContact, {
380
+ apiKey: args.apiKey,
381
+ contact,
382
+ });
383
+ if (result.success) {
384
+ created++;
385
+ results.push({ email: contact.email, success: true });
386
+ }
387
+ else {
388
+ failed++;
389
+ results.push({
390
+ email: contact.email,
391
+ success: false,
392
+ error: "Unknown error",
393
+ });
394
+ }
395
+ }
396
+ catch (error) {
397
+ failed++;
398
+ results.push({
399
+ email: contact.email,
400
+ success: false,
401
+ error: error instanceof Error ? error.message : String(error),
402
+ });
403
+ }
404
+ }
405
+ return {
406
+ success: created > 0,
407
+ created,
408
+ failed,
409
+ results,
410
+ };
411
+ },
412
+ });
413
+ /**
414
+ * Unsubscribe a contact
415
+ * Unsubscribes a contact from receiving emails (they remain in the system)
416
+ * Uses the update endpoint with subscribed: false as per Loops API
417
+ */
418
+ export const unsubscribeContact = action({
419
+ args: {
420
+ apiKey: v.string(),
421
+ email: v.string(),
422
+ },
423
+ returns: successResponseValidator,
424
+ handler: async (ctx, args) => {
425
+ const response = await loopsFetch(args.apiKey, "/contacts/update", {
426
+ method: "PUT",
427
+ json: { email: args.email, subscribed: false },
428
+ });
429
+ if (!response.ok) {
430
+ const errorText = await response.text();
431
+ console.error(`Loops API error [${response.status}]:`, errorText);
432
+ throw sanitizeLoopsError(response.status, errorText);
433
+ }
434
+ await ctx.runMutation(internal.mutations.storeContact, {
435
+ email: args.email,
436
+ subscribed: false,
437
+ });
438
+ return { success: true };
439
+ },
440
+ });
441
+ /**
442
+ * Resubscribe a contact
443
+ * Resubscribes a previously unsubscribed contact
444
+ * Uses the update endpoint with subscribed: true as per Loops API
445
+ */
446
+ export const resubscribeContact = action({
447
+ args: {
448
+ apiKey: v.string(),
449
+ email: v.string(),
450
+ },
451
+ returns: successResponseValidator,
452
+ handler: async (ctx, args) => {
453
+ const response = await loopsFetch(args.apiKey, "/contacts/update", {
454
+ method: "PUT",
455
+ json: { email: args.email, subscribed: true },
456
+ });
457
+ if (!response.ok) {
458
+ const errorText = await response.text();
459
+ console.error(`Loops API error [${response.status}]:`, errorText);
460
+ throw sanitizeLoopsError(response.status, errorText);
461
+ }
462
+ await ctx.runMutation(internal.mutations.storeContact, {
463
+ email: args.email,
464
+ subscribed: true,
465
+ });
466
+ return { success: true };
467
+ },
468
+ });
@@ -0,0 +1,42 @@
1
+ import { TableAggregate } from "@convex-dev/aggregate";
2
+ import type { GenericMutationCtx, GenericQueryCtx } from "convex/server";
3
+ import type { DataModel, Doc } from "./_generated/dataModel";
4
+ /**
5
+ * Aggregate for counting contacts.
6
+ * Uses userGroup as namespace for efficient filtered counting.
7
+ * Key is null since we only need counts, not ordering.
8
+ */
9
+ export declare const contactAggregate: TableAggregate<{
10
+ Namespace: string | undefined;
11
+ Key: null;
12
+ DataModel: DataModel;
13
+ TableName: "contacts";
14
+ }>;
15
+ type MutationCtx = GenericMutationCtx<DataModel>;
16
+ type QueryCtx = GenericQueryCtx<DataModel>;
17
+ /**
18
+ * Insert a contact into the aggregate
19
+ */
20
+ export declare function aggregateInsert(ctx: MutationCtx, doc: Doc<"contacts">): Promise<void>;
21
+ /**
22
+ * Delete a contact from the aggregate
23
+ */
24
+ export declare function aggregateDelete(ctx: MutationCtx, doc: Doc<"contacts">): Promise<void>;
25
+ /**
26
+ * Replace a contact in the aggregate (when userGroup changes)
27
+ */
28
+ export declare function aggregateReplace(ctx: MutationCtx, oldDoc: Doc<"contacts">, newDoc: Doc<"contacts">): Promise<void>;
29
+ /**
30
+ * Count contacts by userGroup namespace
31
+ */
32
+ export declare function aggregateCountByUserGroup(ctx: QueryCtx, userGroup: string | undefined): Promise<number>;
33
+ /**
34
+ * Count all contacts across all userGroups
35
+ */
36
+ export declare function aggregateCountTotal(ctx: QueryCtx): Promise<number>;
37
+ /**
38
+ * Clear and reinitialize the aggregate (for backfill)
39
+ */
40
+ export declare function aggregateClear(ctx: MutationCtx, namespace?: string): Promise<void>;
41
+ export {};
42
+ //# sourceMappingURL=aggregates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregates.d.ts","sourceRoot":"","sources":["../../src/component/aggregates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAO7D;;;;GAIG;AACH,eAAO,MAAM,gBAAgB;eACjB,MAAM,GAAG,SAAS;SACxB,IAAI;eACE,SAAS;eACT,UAAU;EAIpB,CAAC;AAEH,KAAK,WAAW,GAAG,kBAAkB,CAAC,SAAS,CAAC,CAAC;AACjD,KAAK,QAAQ,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;AAE3C;;GAEG;AACH,wBAAsB,eAAe,CACpC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,GAAG,CAAC,UAAU,CAAC,GAClB,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;GAEG;AACH,wBAAsB,eAAe,CACpC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,GAAG,CAAC,UAAU,CAAC,GAClB,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CACrC,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC,EACvB,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC,GACrB,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;GAEG;AACH,wBAAsB,yBAAyB,CAC9C,GAAG,EAAE,QAAQ,EACb,SAAS,EAAE,MAAM,GAAG,SAAS,GAC3B,OAAO,CAAC,MAAM,CAAC,CAEjB;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAMxE;AAED;;GAEG;AACH,wBAAsB,cAAc,CACnC,GAAG,EAAE,WAAW,EAChB,SAAS,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,IAAI,CAAC,CAEf"}