@trycourier/courier-js 3.0.0 → 3.1.1

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.
package/dist/index.mjs CHANGED
@@ -1,6 +1,60 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ const freezeCourierApiUrls = (urls) => Object.freeze({
5
+ courier: Object.freeze({
6
+ ...urls.courier
7
+ }),
8
+ inbox: Object.freeze({
9
+ ...urls.inbox
10
+ })
11
+ });
12
+ const cloneCourierApiUrls = (urls) => ({
13
+ courier: {
14
+ ...urls.courier
15
+ },
16
+ inbox: {
17
+ ...urls.inbox
18
+ }
19
+ });
20
+ const COURIER_API_URLS_BY_REGION = {
21
+ us: freezeCourierApiUrls({
22
+ courier: {
23
+ rest: "https://api.courier.com",
24
+ graphql: "https://api.courier.com/client/q"
25
+ },
26
+ inbox: {
27
+ graphql: "https://inbox.courier.com/q",
28
+ webSocket: "wss://realtime.courier.io"
29
+ }
30
+ }),
31
+ eu: freezeCourierApiUrls({
32
+ courier: {
33
+ rest: "https://api.eu.courier.com",
34
+ graphql: "https://api.eu.courier.com/client/q"
35
+ },
36
+ inbox: {
37
+ graphql: "https://inbox.eu.courier.io/q",
38
+ webSocket: "wss://realtime.eu.courier.io"
39
+ }
40
+ })
41
+ };
42
+ const DEFAULT_COURIER_API_URLS = COURIER_API_URLS_BY_REGION.us;
43
+ const EU_COURIER_API_URLS = COURIER_API_URLS_BY_REGION.eu;
44
+ const getCourierApiUrlsForRegion = (region = "us") => cloneCourierApiUrls(COURIER_API_URLS_BY_REGION[region]);
45
+ const getCourierApiUrls = (urls) => {
46
+ const defaultUrls = DEFAULT_COURIER_API_URLS;
47
+ return {
48
+ courier: {
49
+ rest: (urls == null ? void 0 : urls.courier.rest) || defaultUrls.courier.rest,
50
+ graphql: (urls == null ? void 0 : urls.courier.graphql) || defaultUrls.courier.graphql
51
+ },
52
+ inbox: {
53
+ graphql: (urls == null ? void 0 : urls.inbox.graphql) || defaultUrls.inbox.graphql,
54
+ webSocket: (urls == null ? void 0 : urls.inbox.webSocket) || defaultUrls.inbox.webSocket
55
+ }
56
+ };
57
+ };
4
58
  var ClientAction = /* @__PURE__ */ ((ClientAction2) => {
5
59
  ClientAction2["Subscribe"] = "subscribe";
6
60
  ClientAction2["Unsubscribe"] = "unsubscribe";
@@ -27,16 +81,6 @@ var InboxMessageEvent = /* @__PURE__ */ ((InboxMessageEvent2) => {
27
81
  InboxMessageEvent2["Unread"] = "unread";
28
82
  return InboxMessageEvent2;
29
83
  })(InboxMessageEvent || {});
30
- const getCourierApiUrls = (urls) => ({
31
- courier: {
32
- rest: (urls == null ? void 0 : urls.courier.rest) || "https://api.courier.com",
33
- graphql: (urls == null ? void 0 : urls.courier.graphql) || "https://api.courier.com/client/q"
34
- },
35
- inbox: {
36
- graphql: (urls == null ? void 0 : urls.inbox.graphql) || "https://inbox.courier.com/q",
37
- webSocket: (urls == null ? void 0 : urls.inbox.webSocket) || "wss://realtime.courier.io"
38
- }
39
- });
40
84
  class Logger {
41
85
  constructor(showLogs) {
42
86
  __publicField(this, "PREFIX", "[COURIER]");
@@ -1237,6 +1281,9 @@ class InboxClient extends Client {
1237
1281
  if (filter.archived) {
1238
1282
  parts.push(`archived: ${filter.archived}`);
1239
1283
  }
1284
+ if (filter.from) {
1285
+ parts.push(`from: "${filter.from}"`);
1286
+ }
1240
1287
  return `{ ${parts.join(",")} }`;
1241
1288
  }
1242
1289
  /**
@@ -1263,35 +1310,6 @@ class InboxClient extends Client {
1263
1310
  return `id_${id.replace(/_/g, "__").replace(/-/g, "_")}`;
1264
1311
  }
1265
1312
  }
1266
- class PreferenceTransformer {
1267
- /**
1268
- * Transforms a single API response item to the CourierUserPreferencesTopic type
1269
- * @param item - The API response item
1270
- * @returns A CourierUserPreferencesTopic object
1271
- */
1272
- transformItem(item) {
1273
- return {
1274
- topicId: item.topic_id,
1275
- topicName: item.topic_name,
1276
- sectionId: item.section_id,
1277
- sectionName: item.section_name,
1278
- status: item.status,
1279
- defaultStatus: item.default_status,
1280
- hasCustomRouting: item.has_custom_routing,
1281
- customRouting: item.custom_routing || []
1282
- };
1283
- }
1284
- /**
1285
- * Transforms an array of API response items to CourierUserPreferencesTopic objects
1286
- * @param items - The API response items
1287
- * @returns A generator of CourierUserPreferencesTopic objects
1288
- */
1289
- *transform(items) {
1290
- for (const item of items) {
1291
- yield this.transformItem(item);
1292
- }
1293
- }
1294
- }
1295
1313
  function decode(clientKey) {
1296
1314
  const binaryString = atob(clientKey);
1297
1315
  const bytes = new Uint8Array(binaryString.length);
@@ -1308,52 +1326,89 @@ function encode(key) {
1308
1326
  return btoa(String.fromCharCode(...bytes));
1309
1327
  }
1310
1328
  class PreferenceClient extends Client {
1311
- constructor() {
1312
- super(...arguments);
1313
- __publicField(this, "transformer", new PreferenceTransformer());
1314
- }
1315
1329
  /**
1316
1330
  * Get all preferences for a user
1317
- * @param paginationCursor - Optional cursor for pagination
1331
+ * @param paginationCursor - Optional cursor for pagination (not used in GraphQL implementation)
1318
1332
  * @returns Promise resolving to user preferences
1319
- * @see https://www.courier.com/docs/api-reference/user-preferences/get-user-preferences
1320
1333
  */
1321
1334
  async getUserPreferences(props) {
1322
- let url = `${this.options.apiUrls.courier.rest}/users/${this.options.userId}/preferences`;
1323
- if (props == null ? void 0 : props.paginationCursor) {
1324
- url += `?cursor=${props.paginationCursor}`;
1325
- }
1326
- const json = await http({
1335
+ var _a, _b;
1336
+ const query = `
1337
+ query GetRecipientPreferences {
1338
+ recipientPreferences${this.options.tenantId ? `(accountId: "${this.options.tenantId}")` : ""} {
1339
+ nodes {
1340
+ templateId
1341
+ templateName
1342
+ sectionId
1343
+ sectionName
1344
+ defaultStatus
1345
+ status
1346
+ hasCustomRouting
1347
+ routingPreferences
1348
+ digestSchedule
1349
+ }
1350
+ }
1351
+ }
1352
+ `;
1353
+ const response = await graphql({
1327
1354
  options: this.options,
1328
- url,
1329
- method: "GET",
1355
+ url: this.options.apiUrls.courier.graphql,
1356
+ query,
1330
1357
  headers: {
1358
+ "x-courier-user-id": this.options.userId,
1359
+ "x-courier-client-key": "empty",
1360
+ // Empty for now. Will be removed in future.
1331
1361
  "Authorization": `Bearer ${this.options.accessToken}`
1332
1362
  }
1333
1363
  });
1334
- const data = json;
1364
+ const nodes = ((_b = (_a = response.data) == null ? void 0 : _a.recipientPreferences) == null ? void 0 : _b.nodes) || [];
1335
1365
  return {
1336
- items: [...this.transformer.transform(data.items)],
1337
- paging: data.paging
1366
+ items: nodes.map((node) => this.transformToTopic(node)),
1367
+ paging: {
1368
+ cursor: props == null ? void 0 : props.paginationCursor,
1369
+ more: false
1370
+ // GraphQL returns all preferences at once
1371
+ }
1338
1372
  };
1339
1373
  }
1340
1374
  /**
1341
1375
  * Get preferences for a specific topic
1342
1376
  * @param topicId - The ID of the topic to get preferences for
1343
1377
  * @returns Promise resolving to topic preferences
1344
- * @see https://www.courier.com/docs/api-reference/user-preferences/get-user-subscription-topic
1345
1378
  */
1346
1379
  async getUserPreferenceTopic(props) {
1347
- const json = await http({
1380
+ var _a;
1381
+ const query = `
1382
+ query GetRecipientPreferenceTopic {
1383
+ recipientPreference(templateId: "${props.topicId}"${this.options.tenantId ? `, accountId: "${this.options.tenantId}"` : ""}) {
1384
+ templateId
1385
+ templateName
1386
+ status
1387
+ hasCustomRouting
1388
+ routingPreferences
1389
+ digestSchedule
1390
+ sectionId
1391
+ sectionName
1392
+ defaultStatus
1393
+ }
1394
+ }
1395
+ `;
1396
+ const response = await graphql({
1348
1397
  options: this.options,
1349
- url: `${this.options.apiUrls.courier.rest}/users/${this.options.userId}/preferences/${props.topicId}`,
1350
- method: "GET",
1398
+ url: this.options.apiUrls.courier.graphql,
1399
+ query,
1351
1400
  headers: {
1401
+ "x-courier-user-id": this.options.userId,
1402
+ "x-courier-client-key": "empty",
1403
+ // Empty for now. Will be removed in future.
1352
1404
  "Authorization": `Bearer ${this.options.accessToken}`
1353
1405
  }
1354
1406
  });
1355
- const res = json;
1356
- return this.transformer.transformItem(res.topic);
1407
+ const node = (_a = response.data) == null ? void 0 : _a.recipientPreference;
1408
+ if (!node) {
1409
+ throw new Error(`Preference topic not found: ${props.topicId}`);
1410
+ }
1411
+ return this.transformToTopic(node);
1357
1412
  }
1358
1413
  /**
1359
1414
  * Update preferences for a specific topic
@@ -1362,24 +1417,31 @@ class PreferenceClient extends Client {
1362
1417
  * @param hasCustomRouting - Whether the topic has custom routing
1363
1418
  * @param customRouting - The custom routing channels for the topic
1364
1419
  * @returns Promise resolving when update is complete
1365
- * @see https://www.courier.com/docs/api-reference/user-preferences/update-or-create-user-preferences-for-subscription-topic
1366
1420
  */
1367
1421
  async putUserPreferenceTopic(props) {
1368
- const payload = {
1369
- topic: {
1370
- status: props.status,
1371
- has_custom_routing: props.hasCustomRouting,
1372
- custom_routing: props.customRouting
1422
+ const routingPreferences = props.customRouting.length > 0 ? `[${props.customRouting.join(", ")}]` : "[]";
1423
+ const query = `
1424
+ mutation UpdateRecipientPreferences {
1425
+ updatePreferences(
1426
+ templateId: "${props.topicId}",
1427
+ preferences: {
1428
+ status: ${props.status},
1429
+ hasCustomRouting: ${props.hasCustomRouting},
1430
+ routingPreferences: ${routingPreferences}
1431
+ }${this.options.tenantId ? `, accountId: "${this.options.tenantId}"` : ""}
1432
+ )
1373
1433
  }
1374
- };
1375
- await http({
1434
+ `;
1435
+ await graphql({
1376
1436
  options: this.options,
1377
- url: `${this.options.apiUrls.courier.rest}/users/${this.options.userId}/preferences/${props.topicId}`,
1378
- method: "PUT",
1437
+ url: this.options.apiUrls.courier.graphql,
1438
+ query,
1379
1439
  headers: {
1440
+ "x-courier-user-id": this.options.userId,
1441
+ "x-courier-client-key": "empty",
1442
+ // Empty for now. Will be removed in future.
1380
1443
  "Authorization": `Bearer ${this.options.accessToken}`
1381
- },
1382
- body: payload
1444
+ }
1383
1445
  });
1384
1446
  }
1385
1447
  /**
@@ -1392,6 +1454,21 @@ class PreferenceClient extends Client {
1392
1454
  const url = encode(`${rootTenantId}#${this.options.userId}${this.options.tenantId ? `#${this.options.tenantId}` : ""}#${false}`);
1393
1455
  return `https://view.notificationcenter.app/p/${url}`;
1394
1456
  }
1457
+ /**
1458
+ * Transform a GraphQL RecipientPreference node to CourierUserPreferencesTopic
1459
+ */
1460
+ transformToTopic(node) {
1461
+ return {
1462
+ topicId: node.templateId,
1463
+ topicName: node.templateName || "",
1464
+ sectionId: node.sectionId || "",
1465
+ sectionName: node.sectionName || "",
1466
+ status: node.status || "UNKNOWN",
1467
+ defaultStatus: node.defaultStatus || "UNKNOWN",
1468
+ hasCustomRouting: node.hasCustomRouting || false,
1469
+ customRouting: node.routingPreferences || []
1470
+ };
1471
+ }
1395
1472
  }
1396
1473
  class TokenClient extends Client {
1397
1474
  /**
@@ -1562,7 +1639,7 @@ const _CourierClient = class _CourierClient extends Client {
1562
1639
  ...props,
1563
1640
  showLogs,
1564
1641
  connectionId,
1565
- apiUrls: props.apiUrls || getCourierApiUrls(),
1642
+ apiUrls: props.apiUrls || getCourierApiUrlsForRegion("us"),
1566
1643
  accessToken: props.jwt ?? props.publicApiKey
1567
1644
  };
1568
1645
  const courierUserAgent = new CourierUserAgent(
@@ -1609,7 +1686,7 @@ __publicField(_CourierClient, "COURIER_JS_NAME", "courier-js");
1609
1686
  * User agent reporting version of the courier-js package.
1610
1687
  * Inlined from package.json at build time.
1611
1688
  */
1612
- __publicField(_CourierClient, "COURIER_JS_VERSION", "3.0.0");
1689
+ __publicField(_CourierClient, "COURIER_JS_VERSION", "3.1.1");
1613
1690
  let CourierClient = _CourierClient;
1614
1691
  class AuthenticationListener {
1615
1692
  constructor(callback) {
@@ -1737,11 +1814,15 @@ export {
1737
1814
  BrandClient,
1738
1815
  Courier,
1739
1816
  CourierClient,
1817
+ DEFAULT_COURIER_API_URLS,
1818
+ EU_COURIER_API_URLS,
1740
1819
  InboxClient,
1741
1820
  InboxMessageEvent,
1742
1821
  ListClient,
1743
1822
  PreferenceClient,
1744
1823
  TokenClient,
1745
- TrackingClient
1824
+ TrackingClient,
1825
+ getCourierApiUrls,
1826
+ getCourierApiUrlsForRegion
1746
1827
  };
1747
1828
  //# sourceMappingURL=index.mjs.map