@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,161 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ type GenericCtx =
111
+ | GenericActionCtx<DataModel>
112
+ | GenericMutationCtx<DataModel>
113
+ | GenericQueryCtx<DataModel>;
114
+
115
+ /**
116
+ * A set of services for use within Convex query functions.
117
+ *
118
+ * The query context is passed as the first argument to any Convex query
119
+ * function run on the server.
120
+ *
121
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
122
+ */
123
+ export type QueryCtx = GenericQueryCtx<DataModel>;
124
+
125
+ /**
126
+ * A set of services for use within Convex mutation functions.
127
+ *
128
+ * The mutation context is passed as the first argument to any Convex mutation
129
+ * function run on the server.
130
+ *
131
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
132
+ */
133
+ export type MutationCtx = GenericMutationCtx<DataModel>;
134
+
135
+ /**
136
+ * A set of services for use within Convex action functions.
137
+ *
138
+ * The action context is passed as the first argument to any Convex action
139
+ * function run on the server.
140
+ */
141
+ export type ActionCtx = GenericActionCtx<DataModel>;
142
+
143
+ /**
144
+ * An interface to read from the database within Convex query functions.
145
+ *
146
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
147
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
148
+ * building a query.
149
+ */
150
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
151
+
152
+ /**
153
+ * An interface to read from and write to the database within Convex mutation
154
+ * functions.
155
+ *
156
+ * Convex guarantees that all writes within a single mutation are
157
+ * executed atomically, so you never have to worry about partial writes leaving
158
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
159
+ * for the guarantees Convex provides your functions.
160
+ */
161
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,556 @@
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 {
6
+ batchCreateResponseValidator,
7
+ contactValidator,
8
+ findContactResponseValidator,
9
+ successResponseValidator,
10
+ successWithIdResponseValidator,
11
+ successWithMessageIdResponseValidator,
12
+ successWithWarningResponseValidator,
13
+ } from "./validators";
14
+
15
+ /**
16
+ * Add or update a contact in Loops
17
+ * This function tries to create a contact, and if the email already exists (409),
18
+ * it falls back to updating the contact instead.
19
+ */
20
+ export const addContact = action({
21
+ args: {
22
+ apiKey: v.string(),
23
+ contact: contactValidator,
24
+ },
25
+ returns: successWithIdResponseValidator,
26
+ handler: async (ctx, args) => {
27
+ const createResponse = await loopsFetch(args.apiKey, "/contacts/create", {
28
+ method: "POST",
29
+ json: args.contact,
30
+ });
31
+
32
+ if (!createResponse.ok) {
33
+ const errorText = await createResponse.text();
34
+
35
+ if (createResponse.status === 409) {
36
+ console.log(
37
+ `Contact ${args.contact.email} already exists, updating instead`,
38
+ );
39
+
40
+ const findResponse = await loopsFetch(
41
+ args.apiKey,
42
+ `/contacts/find?email=${encodeURIComponent(args.contact.email)}`,
43
+ { method: "GET" },
44
+ );
45
+
46
+ if (!findResponse.ok) {
47
+ const findErrorText = await findResponse.text();
48
+ console.error(
49
+ `Failed to find existing contact [${findResponse.status}]:`,
50
+ findErrorText,
51
+ );
52
+ }
53
+
54
+ const updateResponse = await loopsFetch(
55
+ args.apiKey,
56
+ "/contacts/update",
57
+ {
58
+ method: "PUT",
59
+ json: {
60
+ email: args.contact.email,
61
+ firstName: args.contact.firstName,
62
+ lastName: args.contact.lastName,
63
+ userId: args.contact.userId,
64
+ source: args.contact.source,
65
+ subscribed: args.contact.subscribed,
66
+ userGroup: args.contact.userGroup,
67
+ },
68
+ },
69
+ );
70
+
71
+ if (!updateResponse.ok) {
72
+ const updateErrorText = await updateResponse.text();
73
+ console.error(
74
+ `Loops API error [${updateResponse.status}]:`,
75
+ updateErrorText,
76
+ );
77
+ throw sanitizeLoopsError(updateResponse.status, updateErrorText);
78
+ }
79
+
80
+ // Get contact ID if available
81
+ let contactId: string | undefined;
82
+ if (findResponse.ok) {
83
+ const findData = (await findResponse.json()) as { id?: string };
84
+ contactId = findData.id;
85
+ }
86
+
87
+ // Store/update in our database
88
+ await ctx.runMutation(internal.mutations.storeContact, {
89
+ email: args.contact.email,
90
+ firstName: args.contact.firstName,
91
+ lastName: args.contact.lastName,
92
+ userId: args.contact.userId,
93
+ source: args.contact.source,
94
+ subscribed: args.contact.subscribed,
95
+ userGroup: args.contact.userGroup,
96
+ loopsContactId: contactId,
97
+ });
98
+
99
+ return {
100
+ success: true,
101
+ id: contactId,
102
+ };
103
+ }
104
+
105
+ console.error(`Loops API error [${createResponse.status}]:`, errorText);
106
+ throw sanitizeLoopsError(createResponse.status, errorText);
107
+ }
108
+
109
+ // Contact was created successfully
110
+ const data = (await createResponse.json()) as { id?: string };
111
+
112
+ await ctx.runMutation(internal.mutations.storeContact, {
113
+ email: args.contact.email,
114
+ firstName: args.contact.firstName,
115
+ lastName: args.contact.lastName,
116
+ userId: args.contact.userId,
117
+ source: args.contact.source,
118
+ subscribed: args.contact.subscribed,
119
+ userGroup: args.contact.userGroup,
120
+ loopsContactId: data.id,
121
+ });
122
+
123
+ return {
124
+ success: true,
125
+ id: data.id,
126
+ };
127
+ },
128
+ });
129
+
130
+ /**
131
+ * Update an existing contact in Loops
132
+ */
133
+ export const updateContact = action({
134
+ args: {
135
+ apiKey: v.string(),
136
+ email: v.string(),
137
+ dataVariables: v.optional(v.record(v.string(), v.any())),
138
+ firstName: v.optional(v.string()),
139
+ lastName: v.optional(v.string()),
140
+ userId: v.optional(v.string()),
141
+ source: v.optional(v.string()),
142
+ subscribed: v.optional(v.boolean()),
143
+ userGroup: v.optional(v.string()),
144
+ },
145
+ returns: successResponseValidator,
146
+ handler: async (ctx, args) => {
147
+ const response = await loopsFetch(args.apiKey, "/contacts/update", {
148
+ method: "PUT",
149
+ json: {
150
+ email: args.email,
151
+ dataVariables: args.dataVariables,
152
+ firstName: args.firstName,
153
+ lastName: args.lastName,
154
+ userId: args.userId,
155
+ source: args.source,
156
+ subscribed: args.subscribed,
157
+ userGroup: args.userGroup,
158
+ },
159
+ });
160
+
161
+ if (!response.ok) {
162
+ const errorText = await response.text();
163
+ console.error(`Loops API error [${response.status}]:`, errorText);
164
+ throw sanitizeLoopsError(response.status, errorText);
165
+ }
166
+
167
+ await ctx.runMutation(internal.mutations.storeContact, {
168
+ email: args.email,
169
+ firstName: args.firstName,
170
+ lastName: args.lastName,
171
+ userId: args.userId,
172
+ source: args.source,
173
+ subscribed: args.subscribed,
174
+ userGroup: args.userGroup,
175
+ });
176
+
177
+ return { success: true };
178
+ },
179
+ });
180
+
181
+ /**
182
+ * Send a transactional email using a transactional ID
183
+ */
184
+ export const sendTransactional = action({
185
+ args: {
186
+ apiKey: v.string(),
187
+ transactionalId: v.string(),
188
+ email: v.string(),
189
+ dataVariables: v.optional(v.record(v.string(), v.any())),
190
+ idempotencyKey: v.optional(v.string()),
191
+ },
192
+ returns: successWithMessageIdResponseValidator,
193
+ handler: async (ctx, args) => {
194
+ const response = await loopsFetch(args.apiKey, "/transactional", {
195
+ headers:
196
+ args.idempotencyKey === undefined
197
+ ? undefined
198
+ : {
199
+ "Idempotency-Key": args.idempotencyKey,
200
+ },
201
+ method: "POST",
202
+ json: {
203
+ transactionalId: args.transactionalId,
204
+ email: args.email,
205
+ dataVariables: args.dataVariables,
206
+ },
207
+ });
208
+
209
+ if (!(response.ok || response.status === 409)) {
210
+ const errorText = await response.text();
211
+ console.error(`Loops API error [${response.status}]:`, errorText);
212
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
213
+ operationType: "transactional",
214
+ email: args.email,
215
+ success: false,
216
+ transactionalId: args.transactionalId,
217
+ });
218
+
219
+ throw sanitizeLoopsError(response.status, errorText);
220
+ }
221
+
222
+ const data = (await response.json()) as { messageId?: string };
223
+
224
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
225
+ operationType: "transactional",
226
+ email: args.email,
227
+ success: true,
228
+ transactionalId: args.transactionalId,
229
+ messageId: data.messageId,
230
+ });
231
+
232
+ return data.messageId === undefined
233
+ ? { success: true }
234
+ : { success: true, messageId: data.messageId };
235
+ },
236
+ });
237
+
238
+ /**
239
+ * Send an event to Loops to trigger email workflows
240
+ */
241
+ export const sendEvent = action({
242
+ args: {
243
+ apiKey: v.string(),
244
+ email: v.string(),
245
+ eventName: v.string(),
246
+ eventProperties: v.optional(v.record(v.string(), v.any())),
247
+ },
248
+ returns: successResponseValidator,
249
+ handler: async (ctx, args) => {
250
+ const response = await loopsFetch(args.apiKey, "/events/send", {
251
+ method: "POST",
252
+ json: {
253
+ email: args.email,
254
+ eventName: args.eventName,
255
+ eventProperties: args.eventProperties,
256
+ },
257
+ });
258
+
259
+ if (!response.ok) {
260
+ const errorText = await response.text();
261
+ console.error(`Loops API error [${response.status}]:`, errorText);
262
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
263
+ operationType: "event",
264
+ email: args.email,
265
+ success: false,
266
+ eventName: args.eventName,
267
+ });
268
+ throw sanitizeLoopsError(response.status, errorText);
269
+ }
270
+
271
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
272
+ operationType: "event",
273
+ email: args.email,
274
+ success: true,
275
+ eventName: args.eventName,
276
+ });
277
+
278
+ return { success: true };
279
+ },
280
+ });
281
+
282
+ /**
283
+ * Delete a contact from Loops
284
+ */
285
+ export const deleteContact = action({
286
+ args: {
287
+ apiKey: v.string(),
288
+ email: v.string(),
289
+ },
290
+ returns: successResponseValidator,
291
+ handler: async (ctx, args) => {
292
+ const response = await loopsFetch(args.apiKey, "/contacts/delete", {
293
+ method: "POST",
294
+ json: { email: args.email },
295
+ });
296
+
297
+ if (!response.ok) {
298
+ const errorText = await response.text();
299
+ console.error(`Loops API error [${response.status}]:`, errorText);
300
+ throw sanitizeLoopsError(response.status, errorText);
301
+ }
302
+
303
+ await ctx.runMutation(internal.mutations.removeContact, {
304
+ email: args.email,
305
+ });
306
+
307
+ return { success: true };
308
+ },
309
+ });
310
+
311
+ /**
312
+ * Trigger a loop for a contact
313
+ * Note: Loops in Loops.so are triggered through events, not a direct API endpoint.
314
+ * This function uses the events endpoint to trigger the loop.
315
+ * The loop must be configured in the Loops dashboard to listen for events.
316
+ *
317
+ * IMPORTANT: Loops.so doesn't have a direct /loops/trigger endpoint.
318
+ * Loops are triggered by sending events. Make sure your loop in the dashboard
319
+ * is configured to trigger on an event name (e.g., "loop_trigger").
320
+ *
321
+ * If you need to trigger a specific loop, you should:
322
+ * 1. Configure the loop in the dashboard to listen for a specific event name
323
+ * 2. Use sendEvent() with that event name instead
324
+ *
325
+ * This function is kept for backwards compatibility but works by sending an event.
326
+ */
327
+ export const triggerLoop = action({
328
+ args: {
329
+ apiKey: v.string(),
330
+ loopId: v.string(),
331
+ email: v.string(),
332
+ dataVariables: v.optional(v.record(v.string(), v.any())),
333
+ eventName: v.optional(v.string()),
334
+ },
335
+ returns: successWithWarningResponseValidator,
336
+ handler: async (ctx, args) => {
337
+ // Loops.so doesn't have a /loops/trigger endpoint
338
+ // Loops are triggered through events. We'll use the events endpoint.
339
+ // Default event name if not provided
340
+ const eventName = args.eventName || `loop_${args.loopId}`;
341
+
342
+ try {
343
+ // Send event to trigger the loop
344
+ await ctx.runAction(api.actions.sendEvent, {
345
+ apiKey: args.apiKey,
346
+ email: args.email,
347
+ eventName,
348
+ eventProperties: {
349
+ ...args.dataVariables,
350
+ loopId: args.loopId, // Include loopId in event properties
351
+ },
352
+ });
353
+
354
+ // Log as loop operation
355
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
356
+ operationType: "loop",
357
+ email: args.email,
358
+ success: true,
359
+ loopId: args.loopId,
360
+ eventName,
361
+ });
362
+
363
+ return {
364
+ success: true,
365
+ warning:
366
+ "Loops are triggered via events. Ensure your loop is configured to listen for this event.",
367
+ };
368
+ } catch (error) {
369
+ // Log failed loop operation
370
+ await ctx.runMutation(internal.mutations.logEmailOperation, {
371
+ operationType: "loop",
372
+ email: args.email,
373
+ success: false,
374
+ loopId: args.loopId,
375
+ eventName,
376
+ metadata: {
377
+ error: error instanceof Error ? error.message : String(error),
378
+ },
379
+ });
380
+
381
+ throw error;
382
+ }
383
+ },
384
+ });
385
+
386
+ /**
387
+ * Find a contact by email
388
+ * Retrieves contact information from Loops
389
+ * Note: Loops API may return either an object or an array
390
+ */
391
+ export const findContact = action({
392
+ args: {
393
+ apiKey: v.string(),
394
+ email: v.string(),
395
+ },
396
+ returns: findContactResponseValidator,
397
+ handler: async (_ctx, args) => {
398
+ const response = await loopsFetch(
399
+ args.apiKey,
400
+ `/contacts/find?email=${encodeURIComponent(args.email)}`,
401
+ { method: "GET" },
402
+ );
403
+
404
+ if (!response.ok) {
405
+ if (response.status === 404) {
406
+ return { success: false, contact: undefined };
407
+ }
408
+ const errorText = await response.text();
409
+ console.error(`Loops API error [${response.status}]:`, errorText);
410
+ throw sanitizeLoopsError(response.status, errorText);
411
+ }
412
+
413
+ type LoopsContactRecord = Record<string, unknown>;
414
+ const data = (await response.json()) as
415
+ | LoopsContactRecord
416
+ | Array<LoopsContactRecord>;
417
+
418
+ // Handle case where Loops returns an array instead of a single object
419
+ let contact = Array.isArray(data) ? data[0] : data;
420
+
421
+ // Convert null values to undefined for optional fields
422
+ if (contact) {
423
+ contact = Object.fromEntries(
424
+ Object.entries(contact).map(([key, value]) => [
425
+ key,
426
+ value === null ? undefined : value,
427
+ ]),
428
+ ) as LoopsContactRecord;
429
+ }
430
+
431
+ return {
432
+ success: true,
433
+ contact: contact as LoopsContactRecord | undefined,
434
+ };
435
+ },
436
+ });
437
+
438
+ /**
439
+ * Batch create contacts
440
+ * Creates multiple contacts sequentially using the single contact create endpoint.
441
+ * Note: Loops.so doesn't have a batch endpoint, so we create contacts one by one.
442
+ */
443
+ export const batchCreateContacts = action({
444
+ args: {
445
+ apiKey: v.string(),
446
+ contacts: v.array(contactValidator),
447
+ },
448
+ returns: batchCreateResponseValidator,
449
+ handler: async (ctx, args) => {
450
+ let created = 0;
451
+ let failed = 0;
452
+ const results: Array<{ email: string; success: boolean; error?: string }> =
453
+ [];
454
+
455
+ // Create contacts one by one since Loops.so doesn't have a batch endpoint
456
+ for (const contact of args.contacts) {
457
+ try {
458
+ // Use the addContact function which handles create/update logic
459
+ const result = await ctx.runAction(api.actions.addContact, {
460
+ apiKey: args.apiKey,
461
+ contact,
462
+ });
463
+
464
+ if (result.success) {
465
+ created++;
466
+ results.push({ email: contact.email, success: true });
467
+ } else {
468
+ failed++;
469
+ results.push({
470
+ email: contact.email,
471
+ success: false,
472
+ error: "Unknown error",
473
+ });
474
+ }
475
+ } catch (error) {
476
+ failed++;
477
+ results.push({
478
+ email: contact.email,
479
+ success: false,
480
+ error: error instanceof Error ? error.message : String(error),
481
+ });
482
+ }
483
+ }
484
+
485
+ return {
486
+ success: created > 0,
487
+ created,
488
+ failed,
489
+ results,
490
+ };
491
+ },
492
+ });
493
+
494
+ /**
495
+ * Unsubscribe a contact
496
+ * Unsubscribes a contact from receiving emails (they remain in the system)
497
+ * Uses the update endpoint with subscribed: false as per Loops API
498
+ */
499
+ export const unsubscribeContact = action({
500
+ args: {
501
+ apiKey: v.string(),
502
+ email: v.string(),
503
+ },
504
+ returns: successResponseValidator,
505
+ handler: async (ctx, args) => {
506
+ const response = await loopsFetch(args.apiKey, "/contacts/update", {
507
+ method: "PUT",
508
+ json: { email: args.email, subscribed: false },
509
+ });
510
+
511
+ if (!response.ok) {
512
+ const errorText = await response.text();
513
+ console.error(`Loops API error [${response.status}]:`, errorText);
514
+ throw sanitizeLoopsError(response.status, errorText);
515
+ }
516
+
517
+ await ctx.runMutation(internal.mutations.storeContact, {
518
+ email: args.email,
519
+ subscribed: false,
520
+ });
521
+
522
+ return { success: true };
523
+ },
524
+ });
525
+
526
+ /**
527
+ * Resubscribe a contact
528
+ * Resubscribes a previously unsubscribed contact
529
+ * Uses the update endpoint with subscribed: true as per Loops API
530
+ */
531
+ export const resubscribeContact = action({
532
+ args: {
533
+ apiKey: v.string(),
534
+ email: v.string(),
535
+ },
536
+ returns: successResponseValidator,
537
+ handler: async (ctx, args) => {
538
+ const response = await loopsFetch(args.apiKey, "/contacts/update", {
539
+ method: "PUT",
540
+ json: { email: args.email, subscribed: true },
541
+ });
542
+
543
+ if (!response.ok) {
544
+ const errorText = await response.text();
545
+ console.error(`Loops API error [${response.status}]:`, errorText);
546
+ throw sanitizeLoopsError(response.status, errorText);
547
+ }
548
+
549
+ await ctx.runMutation(internal.mutations.storeContact, {
550
+ email: args.email,
551
+ subscribed: true,
552
+ });
553
+
554
+ return { success: true };
555
+ },
556
+ });