-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
741 lines (692 loc) · 18.2 KB
/
index.ts
File metadata and controls
741 lines (692 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
interface QueryOptions {
path: `v1/${string}`;
method?: "GET" | "POST" | "PUT";
payload?: Record<string, unknown>;
params?: Record<string, string>;
headers?: Record<string, string>;
}
interface ApiKeySuccessResponse {
success: true;
teamName: string;
}
interface ApiKeyErrorResponse {
error: "Invalid API key";
}
interface ContactSuccessResponse {
success: true;
/** The ID of the contact. */
id: string;
}
interface DeleteSuccessResponse {
success: true;
message: "Contact deleted.";
}
interface ErrorResponse {
success: false;
message: string;
}
type Contact = {
/**
* The contact's ID.
*/
id: string;
/**
* The contact's email address.
*/
email: string;
/**
* The contact's first name.
*/
firstName: string | null;
/**
* The contact's last name.
*/
lastName: string | null;
/**
* The source the contact was created from.
*/
source: string;
/**
* Whether the contact will receive campaign and loops emails.
*/
subscribed: boolean;
/**
* The contact's user group (used to segemnt users when sending emails).
*/
userGroup: string;
/**
* A unique user ID (for example, from an external application).
*/
userId: string | null;
/**
* Mailing lists the contact is subscribed to.
* @see https://loops.so/docs/contacts/mailing-lists
*/
mailingLists: Record<string, true>;
/**
* The contact's double opt-in status.
* @see https://loops.so/docs/contacts/double-opt-in
*/
optInStatus: "pending" | "accepted" | "rejected" | null;
} & Record<string, string | number | boolean | null>;
interface ContactPropertySuccessResponse {
success: boolean;
}
interface EventSuccessResponse {
success: boolean;
}
interface TransactionalSuccess {
success: true;
}
interface TransactionalError {
type: "error";
success: false;
path: string;
message: string;
}
interface TransactionalNestedError {
type: "nestedError";
success: false;
error: {
path: string;
message: string;
};
transactionalId?: string;
}
type ContactProperties = Record<string, string | number | boolean | null>;
type EventProperties = Record<string, string | number | boolean>;
type MailingLists = Record<string, boolean>;
type TransactionalVariables = Record<
string,
string | number | Array<Record<string, string | number>>
>;
interface TransactionalAttachment {
/**
* The file name, shown in email clients.
*/
filename: string;
/**
* MIME type of the file.
*/
contentType: string;
/**
* Base64-encoded content of the file.
*/
data: string;
}
interface MailingList {
/**
* The ID of the list.
*/
id: string;
/**
* The name of the list.
*/
name: string;
/**
* The list's description.
*/
description: string | null;
/**
* Whether the list is public (true) or private (false).
* @see https://loops.so/docs/contacts/mailing-lists#list-visibility
*/
isPublic: boolean;
}
interface PaginationData {
/**
* Total results found.
*/
totalResults: number;
/**
* The number of results returned in this response.
*/
returnedResults: number;
/**
* The maximum number of results requested.
*/
perPage: number;
/**
* Total number of pages.
*/
totalPages: number;
/**
* The next cursor (for retrieving the next page of results using the `cursor` parameter), or `null` if there are no further pages.
*/
nextCursor: string | null;
/**
* The URL of the next page of results, or `null` if there are no further pages.
*/
nextPage: string | null;
}
interface TransactionalEmail {
/** The ID of the transactional email. */
id: string;
/**
* The name of the transactional email.
*/
name: string;
/**
* The date the email was last updated in ECMA-262 date-time format.
* @see https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-time-string-format
*/
lastUpdated: string;
/**
* Data variables in the transactional email.
*/
dataVariables: string[];
}
interface ContactProperty {
/**
* The property's name.
*/
key: string;
/**
* The human-friendly label for this property.
*/
label: string;
/**
* The type of property.
*/
type: "string" | "number" | "boolean" | "date";
}
interface ListTransactionalsResponse {
pagination: PaginationData;
data: TransactionalEmail[];
}
class RateLimitExceededError extends Error {
limit: number;
remaining: number;
constructor(limit: number, remaining: number) {
super(`Rate limit of ${limit} requests per second exceeded.`);
this.name = "RateLimitExceededError";
this.limit = limit;
this.remaining = remaining;
}
}
class APIError extends Error {
statusCode: number;
json:
| ErrorResponse
| TransactionalError
| TransactionalNestedError
| ApiKeyErrorResponse
| null;
rawBody?: string;
constructor(
statusCode: number,
json:
| ErrorResponse
| TransactionalError
| TransactionalNestedError
| ApiKeyErrorResponse
| null,
rawBody?: string
) {
let message: string | undefined;
if (json !== null) {
if (
"error" in json &&
typeof json.error === "object" &&
json.error?.message
) {
message = json.error.message;
} else if ("error" in json && typeof json.error === "string") {
message = json.error;
} else if ("message" in json && typeof json.message === "string") {
message = json.message;
}
}
super(`${statusCode}${message ? ` - ${message}` : ""}`);
this.name = "APIError";
this.statusCode = statusCode;
this.json = json;
this.rawBody = rawBody;
// This captures the proper stack trace in most environments
if ((Error as any).captureStackTrace) {
(Error as any).captureStackTrace(this, APIError);
}
}
}
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
class LoopsClient {
apiKey: string;
apiRoot = "https://app.loops.so/api/";
constructor(apiKey: string) {
if (!apiKey) {
throw new Error("API key is required");
}
this.apiKey = apiKey;
}
/**
* Creates and sends a query to the Loops API.
*
* @param {Object} params
* @param {string} params.path Endpoint path
* @param {string} params.method HTTP method
* @param {Object} params.headers Additional headers to send with the request
* @param {Object} params.payload Payload for PUT and POST requests
* @param {Object} params.params URL query parameters
*/
private async _makeQuery<T>({
path,
method = "GET",
headers,
payload,
params,
}: QueryOptions): Promise<T> {
const h = new Headers();
h.set("Authorization", `Bearer ${this.apiKey}`);
h.set("Content-Type", "application/json");
if (headers) {
Object.entries(headers).forEach(([key, value]) => {
if (value !== "" && value !== undefined && value !== null) {
h.set(key, value as string);
}
});
}
const url = new URL(path, this.apiRoot);
if (params && method === "GET") {
Object.entries(params).forEach(([key, value]) =>
url.searchParams.append(key, value as string)
);
}
const response = await fetch(url.href, {
method,
headers: h,
body: payload ? JSON.stringify(payload) : undefined,
});
if (response.status === 429) {
const limit = parseInt(
response.headers.get("x-ratelimit-limit") || "10",
10
);
const remaining = parseInt(
response.headers.get("x-ratelimit-remaining") || "10",
10
);
throw new RateLimitExceededError(limit, remaining);
}
const text = await response.text();
let json = null;
try {
json = JSON.parse(text);
} catch {
// JSON parsing failed
}
// All other status codes from API, throw an error
if (!response.ok) {
throw new APIError(response.status, json, json === null ? text : undefined);
}
if (json === null) {
throw new APIError(response.status, null, text);
}
return json;
}
/**
* Test an API key.
*
* @see https://loops.so/docs/api-reference/api-key
*
* @returns {Object} Success response (JSON)
*/
async testApiKey(): Promise<ApiKeySuccessResponse> {
return this._makeQuery({
path: "v1/api-key",
});
}
/**
* Create a new contact.
*
* @param {Object} params
* @param {string} params.email The email address of the contact.
* @param {Object} [params.properties] All other contact properties, including custom properties.
* @param {Object} [params.mailingLists] An object of mailing list IDs and boolean subscription statuses.
*
* @see https://loops.so/docs/api-reference/create-contact
*
* @returns {Object} Contact record (JSON)
*/
async createContact({
email,
properties,
mailingLists,
}: {
email: string;
properties?: ContactProperties;
mailingLists?: MailingLists;
}): Promise<ContactSuccessResponse> {
const payload = { ...properties, mailingLists } as {
email?: string;
mailingLists?: MailingLists;
} & ContactProperties;
payload["email"] = email;
return this._makeQuery({
path: "v1/contacts/create",
method: "POST",
payload,
});
}
/**
* Update a contact.
*
* @param {Object} params
* @param {string} [params.email] The email address of the contact.
* @param {string} [params.userId] The user ID of the contact.
* @param {Object} [params.properties] All other contact properties, including custom properties.
* @param {Object} [params.mailingLists] An object of mailing list IDs and boolean subscription statuses.
*
* @see https://loops.so/docs/api-reference/update-contact
*
* @returns {Object} Contact record (JSON)
*/
async updateContact({
email,
userId,
properties,
mailingLists,
}: {
email?: string;
userId?: string;
properties?: ContactProperties;
mailingLists?: MailingLists;
}): Promise<ContactSuccessResponse> {
if (!userId && !email)
throw new ValidationError(
"You must provide an `email` or `userId` value."
);
const payload = {
...properties,
mailingLists,
} as {
email?: string;
userId?: string;
mailingLists?: MailingLists;
} & ContactProperties;
if (email) payload["email"] = email;
if (userId) payload["userId"] = userId;
return this._makeQuery({
path: "v1/contacts/update",
method: "PUT",
payload,
});
}
/**
* Find a contact by email address or user ID.
*
* @param {Object} params
* @param {string} [params.email] The email address of the contact.
* @param {string} [params.userId] The user ID of the contact.
*
* @see https://loops.so/docs/api-reference/find-contact
*
* @returns {Object} List of contact records (JSON)
*/
async findContact({
email,
userId,
}: {
email?: string;
userId?: string;
}): Promise<Contact[]> {
if (email && userId)
throw new ValidationError("Only one parameter is permitted.");
if (!email && !userId)
throw new ValidationError(
"You must provide an `email` or `userId` value."
);
const params: { email?: string; userId?: string } = {};
if (email) params["email"] = email;
else if (userId) params["userId"] = userId;
return this._makeQuery({
path: "v1/contacts/find",
params,
});
}
/**
* Delete a contact by email or user ID.
*
* @param {Object} params
* @param {string} [params.email] The email address of the contact.
* @param {string} [params.userId] The user ID of the contact.
*
* @see https://loops.so/docs/api-reference/delete-contact
*
* @returns {Object} Confirmation (JSON)
*/
async deleteContact({
email,
userId,
}: {
email?: string;
userId?: string;
}): Promise<DeleteSuccessResponse> {
if (email && userId)
throw new ValidationError("Only one parameter is permitted.");
if (!email && !userId)
throw new ValidationError(
"You must provide an `email` or `userId` value."
);
const payload: { email?: string; userId?: string } = {};
if (email) payload["email"] = email;
else if (userId) payload["userId"] = userId;
return this._makeQuery({
path: "v1/contacts/delete",
method: "POST",
payload,
});
}
/**
* Create a new contact property.
*
* @param {string} name The name of the property. Should be in camelCase like "planName".
* @param {"string" | "number" | "boolean" | "date"} type The property's value type.
*
* @see https://loops.so/docs/api-reference/create-contact-property
*
* @returns {Object} Contact property record (JSON)
*/
async createContactProperty(
name: string,
type: "string" | "number" | "boolean" | "date"
): Promise<ContactPropertySuccessResponse> {
return this._makeQuery({
path: "v1/contacts/properties",
method: "POST",
payload: {
name,
type,
},
});
}
/**
* Get contact properties.
*
* @param {"all" | "custom"} [list] Return all or just custom properties.
*
* @see https://loops.so/docs/api-reference/list-contact-properties
*
* @returns {Object} List of contact properties (JSON)
*/
async getCustomProperties(
list?: "all" | "custom"
): Promise<ContactProperty[]> {
return this._makeQuery({
path: "v1/contacts/properties",
params: { list: list || "all" },
});
}
/**
* Get mailing lists.
*
* @see https://loops.so/docs/api-reference/list-mailing-lists
*
* @returns {Object} List of mailing lists (JSON)
*/
async getMailingLists(): Promise<MailingList[]> {
return this._makeQuery({
path: "v1/lists",
});
}
/**
* Send an event.
*
* @param {Object} params
* @param {string} [params.email] The email address of the contact.
* @param {string} [params.userId] The user ID of the contact.
* @param {string} params.eventName The name of the event.
* @param {Object} [params.contactProperties] Properties to update the contact with, including custom properties.
* @param {Object} [params.eventProperties] Event properties, made available in emails triggered by the event.
* @param {Object} [params.mailingLists] An object of mailing list IDs and boolean subscription statuses.
* @param {Object} [params.headers] Additional headers to send with the request.
*
* @see https://loops.so/docs/api-reference/send-event
*
* @returns {Object} Response (JSON)
*/
async sendEvent({
email,
userId,
eventName,
contactProperties,
eventProperties,
mailingLists,
headers,
}: {
email?: string;
userId?: string;
eventName: string;
contactProperties?: ContactProperties;
eventProperties?: EventProperties;
mailingLists?: MailingLists;
headers?: Record<string, string>;
}): Promise<EventSuccessResponse> {
if (!userId && !email)
throw new ValidationError(
"You must provide an `email` or `userId` value."
);
const payload: {
email?: string;
userId?: string;
eventName: string;
eventProperties?: EventProperties;
mailingLists?: MailingLists;
} = {
eventName,
...contactProperties,
eventProperties,
mailingLists,
};
if (email) payload["email"] = email;
if (userId) payload["userId"] = userId;
return this._makeQuery({
path: "v1/events/send",
method: "POST",
headers,
payload,
});
}
/**
* Send a transactional email.
*
* @param {Object} params
* @param {string} params.transactionalId The ID of the transactional email to send.
* @param {string} params.email The email address of the recipient.
* @param {boolean} [params.addToAudience] Create a contact in your audience using the provided email address (if one doesn't already exist).
* @param {Object} [params.dataVariables] Data variables as defined by the transational email template.
* @param {Object[]} [params.attachments] File(s) to be sent along with the email message.
* @param {Object} [params.headers] Additional headers to send with the request.
*
* @see https://loops.so/docs/api-reference/send-transactional-email
*
* @returns {Object} Confirmation (JSON)
*/
async sendTransactionalEmail({
transactionalId,
email,
addToAudience,
dataVariables,
attachments,
headers,
}: {
transactionalId: string;
email: string;
addToAudience?: boolean;
dataVariables?: TransactionalVariables;
attachments?: Array<TransactionalAttachment>;
headers?: Record<string, string>;
}): Promise<TransactionalSuccess> {
const payload = {
transactionalId,
email,
addToAudience,
dataVariables,
attachments,
};
return this._makeQuery({
path: "v1/transactional",
method: "POST",
headers,
payload,
});
}
/**
* List published transactional emails.
*
* @param {Object} params
* @param {number} [params.perPage] How many results to return in each request. Must be between 10 and 50. Defaults to 20.
* @param {string} [params.cursor] A cursor, to return a specific page of results. Cursors can be found from the `pagination.nextCursor` value in each response.
*
* @see https://loops.so/docs/api-reference/list-transactional-emails
*
* @returns {Object} List of transactional emails (JSON)
*/
async getTransactionalEmails({
perPage,
cursor,
}: {
perPage?: number;
cursor?: string;
} = {}): Promise<ListTransactionalsResponse> {
let params: { perPage: string; cursor?: string } = {
perPage: (perPage || 20).toString(),
};
if (cursor) params["cursor"] = cursor;
return this._makeQuery({
path: "v1/transactional",
params,
});
}
}
export {
LoopsClient,
RateLimitExceededError,
APIError,
ValidationError,
ApiKeySuccessResponse,
ApiKeyErrorResponse,
ContactSuccessResponse,
DeleteSuccessResponse,
ErrorResponse,
Contact,
ContactProperty,
ContactPropertySuccessResponse,
EventSuccessResponse,
TransactionalSuccess,
TransactionalError,
TransactionalNestedError,
ContactProperties,
EventProperties,
TransactionalVariables,
TransactionalAttachment,
MailingList,
PaginationData,
TransactionalEmail,
ListTransactionalsResponse,
MailingLists,
};