@15gifts/sdk 0.13.0 → 0.13.2

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.d.mts CHANGED
@@ -455,6 +455,12 @@ interface components {
455
455
  name: string;
456
456
  /** Price */
457
457
  price: string;
458
+ /**
459
+ * Quantity
460
+ * @description How many of this extra are there?
461
+ * @default 1
462
+ */
463
+ quantity: number;
458
464
  };
459
465
  /**
460
466
  * ProductPriceDetails
@@ -508,7 +514,7 @@ interface components {
508
514
  priceDetails?: components["schemas"]["ProductPriceDetails"] | null;
509
515
  /**
510
516
  * Category
511
- * @description Foe example, `tv`, `internet`, `phone`. It can be used to show an icon in the UI.
517
+ * @description For example, `tv`, `internet`, `phone`. It can be used to show an icon in the UI.
512
518
  */
513
519
  category?: string | null;
514
520
  /**
@@ -516,6 +522,12 @@ interface components {
516
522
  * @description Extras are additional products that are bundled with the main product.
517
523
  */
518
524
  extras?: components["schemas"]["ProductExtra"][] | null;
525
+ /**
526
+ * Quantity
527
+ * @description How many of this product are there?
528
+ * @default 1
529
+ */
530
+ quantity: number;
519
531
  };
520
532
  /** Recommendation */
521
533
  Recommendation: {
@@ -770,7 +782,25 @@ interface paths {
770
782
  post: {
771
783
  parameters: {
772
784
  query?: never;
773
- header?: never;
785
+ header?: {
786
+ /**
787
+ * @description A 36 character hash, 5 segments, separated by dashes that uniquely identifies a page view (page-shown event)
788
+ * @example 1a1a1a1a-1a1a-1a1a-1a1a-1a1a1a1a1a1a
789
+ */
790
+ "x-page-view-id"?: string;
791
+ /** @description Web Analytics Platform User ID */
792
+ "x-web-analytics-platform-user-id"?: string;
793
+ /**
794
+ * @description The version of the frontend application that is making the request
795
+ * @example 1.0.0
796
+ */
797
+ "x-frontend-version"?: string;
798
+ /**
799
+ * @description The version of the SDK that is making the request
800
+ * @example 1.0.0
801
+ */
802
+ "x-sdk-version"?: string;
803
+ };
774
804
  path?: never;
775
805
  cookie?: never;
776
806
  };
@@ -988,85 +1018,6 @@ interface paths {
988
1018
  environment?: "development" | "ephemeral" | "local" | "production" | "staging" | "test" | "uat";
989
1019
  /** @description A JWT used to identify the user in the system, can be obtained from the identity endpoint */
990
1020
  identityToken: string;
991
- } | {
992
- /**
993
- * @description The customer that the event occurred on
994
- * @enum {string}
995
- */
996
- customerId: "spectrum";
997
- /** @description The timestamp describing the time the event occurred. This should conform to ISO 8601 standards and be in UTC */
998
- eventAt?: string;
999
- /** @description A JWT used to identify the user in the system, can be obtained from the identity endpoint */
1000
- identityToken: string;
1001
- /** @description The ID for the sale, a unique value we can correlate with customer records. */
1002
- saleId: string;
1003
- /**
1004
- * @description The type of user, for example, existing or prospect.
1005
- * @enum {string}
1006
- */
1007
- userType: "existing" | "prospect";
1008
- /** @description The browser the user is using, e.g. Chrome, Firefox, Safari, etc. */
1009
- browser?: string;
1010
- /** @description The user agent string e.g. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" */
1011
- userAgent?: string;
1012
- /** @description The device screen width in pixels - window.screen.width in JS. This is a user level property that should never change. */
1013
- screenWidth?: number;
1014
- /** @description The device screen height in pixels - window.screen.height in JS. This is a user level property that should never change. */
1015
- screenHeight?: number;
1016
- /**
1017
- * @description The size of the device's screen, based off the actual user experience it will generate, assuming the browser window takes up the whole screen.
1018
- *
1019
- * Based off https://15gifts.atlassian.net/wiki/spaces/AI/pages/3981443139/Breakpoints+for+mobile+desktop
1020
- *
1021
- * screen_width <= 480px = 'mobile'
1022
- * screen_width > 480px = 'large'
1023
- * @enum {string}
1024
- */
1025
- screenSize?: "mobile" | "large";
1026
- /** @description "A code that represents what currency the product price is listed in e.g. USD, GBP. This should match the ISO 4217 standard - see https://www.iban.com/currency-codes. */
1027
- currencyCode?: string;
1028
- /** @description The host/domain of the URL at the time the event is fired */
1029
- siteHost: string;
1030
- /** @description The path of the URL (including an initial `/`) at the time the event is fired */
1031
- sitePath?: string;
1032
- /** @description The query string of the URL (including an initial `?`) at the time the event is fired */
1033
- siteQueryString?: string;
1034
- /** @description The language of the part of the site the sales data is coming from in ISO 639-1 format e.g. 'en-us', 'es-us' etc. */
1035
- language?: string;
1036
- /** @description The recurring payment due per payment period */
1037
- priceRecurring: number;
1038
- /** @description An ISO-8601 duration that represents the period of time that the priceRecurring payment recurs over */
1039
- priceRecurringPeriod: string;
1040
- /** @description The upfront price the user has to pay for the product. */
1041
- priceUpfront?: number;
1042
- /** @description The full basket value of the sale, inclusive of any offers. */
1043
- totalValueOfSale?: number;
1044
- /** @description The taxes the user has to pay relating to the priceUpfront of the product(s) */
1045
- totalUpfrontTax?: number;
1046
- /** @description The taxes the user has to pay relating to the priceRecurring of the product(s), due per payment period */
1047
- totalRecurringTax?: number;
1048
- totalTaxOnSale?: number;
1049
- /** @description A list containing separate line items for each product sold. */
1050
- productsSold: {
1051
- /** @description The ID or SKU of a product that is provided by the customer */
1052
- siteProductId: string;
1053
- /** @description The name of the product */
1054
- siteProductName: string;
1055
- /** @description The category of products the product belongs to. */
1056
- siteProductType: string;
1057
- /** @description An ISO-8601 duration that represents the contract length */
1058
- productContractLength: string;
1059
- /** @description An integer representing how many of this particular product the user is purchasing */
1060
- quantity: number;
1061
- /** @description The upfront price the user has to pay for the product. */
1062
- productPriceUpfront: number;
1063
- /** @description The recurring payment per payment period for the product */
1064
- productPricePerPeriod: number;
1065
- /** @description An ISO-8601 duration that represents the period of time that the productPricePerPeriod payment recurs over */
1066
- productRecurringPaymentPeriod: string;
1067
- /** @description The ID or SKU of a bundle that the product (and other products being purchased at the same time) are part of */
1068
- bundleId?: string;
1069
- }[];
1070
1021
  } | {
1071
1022
  /**
1072
1023
  * @description The customer that the event occurred on
@@ -1128,7 +1079,7 @@ interface paths {
1128
1079
  /** @description A list containing separate line items for each product sold. */
1129
1080
  productsSold: {
1130
1081
  /** @description The ID or SKU of a product that is provided by the customer */
1131
- siteProductId: string;
1082
+ siteProductId?: string;
1132
1083
  /** @description The name of the product */
1133
1084
  siteProductName: string;
1134
1085
  /** @description The category of products the product belongs to. */
@@ -1207,7 +1158,7 @@ interface paths {
1207
1158
  /** @description A list containing separate line items for each product sold. */
1208
1159
  productsSold: {
1209
1160
  /** @description The ID or SKU of a product that is provided by the customer */
1210
- siteProductId: string;
1161
+ siteProductId?: string;
1211
1162
  /** @description The name of the product */
1212
1163
  siteProductName: string;
1213
1164
  /** @description The category of products the product belongs to. */
@@ -1284,7 +1235,7 @@ interface paths {
1284
1235
  };
1285
1236
  };
1286
1237
  };
1287
- /** @description Validation error response */
1238
+ /** @description Default Response */
1288
1239
  422: {
1289
1240
  headers: {
1290
1241
  [name: string]: unknown;
@@ -1309,7 +1260,10 @@ interface paths {
1309
1260
  /** @description The comparison that caused the error */
1310
1261
  comparison?: string;
1311
1262
  };
1312
- }[];
1263
+ }[] | {
1264
+ /** @description The error message */
1265
+ message?: string;
1266
+ };
1313
1267
  };
1314
1268
  };
1315
1269
  };
@@ -1439,6 +1393,8 @@ interface paths {
1439
1393
  conversation_id?: string;
1440
1394
  /** @description An integer representing the rank of the corresponding feedback score. It should always start at 0, even if the number of options changes. */
1441
1395
  feedback_score_num?: number;
1396
+ /** @description A hashed IP address for the user. Hashing Algorithm and Salt are in 1Password. */
1397
+ ip_address_hashed?: string;
1442
1398
  /** @description Describes the reason the tool ui was closed. When the value is 'customer_triggered' it's because it's been programmatically closed by the customer (by running window.axiom.integrations.hide() or window.axiom.integrations.minimise()). When it's 'user_close_click' it's because the actual end user has closed it manually by clicking. */
1443
1399
  tool_ui_closed_reason?: string;
1444
1400
  /** @description The turn number in the conversation. This links each user message to a corresponding assistant response. If there is an opening message from the assistant, this would have a message_turn of 1. Then the first message a user sends would have a message_turn of 2. The first actual response the assistant sends would have a message_turn of 2.
@@ -1462,7 +1418,11 @@ interface paths {
1462
1418
  message_text?: string;
1463
1419
  /** @description List of objects that represents the options for single & multiselect questions. */
1464
1420
  message_select_options?: unknown[];
1465
- /** @description true or false depending on whether the users message caused the assistant to provide a guardrail response */
1421
+ /** @description true or false depending on whether the users message caused the assistant to provide a fallback guardrail response.
1422
+ *
1423
+ * This happens for most guardrails, but in the case of pii-masking it will be false, because it strips the PII from the conversation history and continues the conversation as normal.
1424
+ *
1425
+ * To check whether the guardrail was triggered, use the is_guardrail_triggered property. */
1466
1426
  is_user_message_guardrailed?: boolean;
1467
1427
  /** @description A list of all guardrails checked for in the corresponding turn associated with the assistant_message-submitted event this property is part of. Includes whether they were triggered and some meaningful way of measuring how close to being triggered/not triggered they were, as well as categorising into input/output guardrails. */
1468
1428
  guardrails?: unknown[];
@@ -1532,6 +1492,8 @@ interface paths {
1532
1492
  slots?: unknown[];
1533
1493
  /** @description Describes the reason the entry point was closed. When the value is 'customer_triggered' it's because it's been programmatically closed by the customer (by running window.axiom.integrations.hide()). When it's 'user_close_click' it's because the actual end user has closed it manually by clicking. */
1534
1494
  entry_point_closed_reason?: string;
1495
+ /** @description A categorical property to denote which party was responsible for suppression. This is useful for accurately calculating control conversion rates, it allows us to count how many users were suppressed before humara loading, and how many were put in a control group. */
1496
+ suppressed_by?: unknown[];
1535
1497
  /** @description A list of objects for recommendations sent in a conversation api message. */
1536
1498
  recommendation_set?: unknown[];
1537
1499
  /** @description This is a score that evaluates how much progress has been made through the discovery phase of the conversation. A higher score means more information has been discovered. This value is generated by the recommender.
@@ -1853,6 +1815,7 @@ declare class Client {
1853
1815
  feedback_score_text?: string;
1854
1816
  conversation_id?: string;
1855
1817
  feedback_score_num?: number;
1818
+ ip_address_hashed?: string;
1856
1819
  tool_ui_closed_reason?: string;
1857
1820
  conversation_turn_num?: number;
1858
1821
  conversation_turn_id?: string;
@@ -1889,6 +1852,7 @@ declare class Client {
1889
1852
  experiment_variation_name?: string;
1890
1853
  slots?: unknown[];
1891
1854
  entry_point_closed_reason?: string;
1855
+ suppressed_by?: unknown[];
1892
1856
  recommendation_set?: unknown[];
1893
1857
  discovery_progress_score?: number;
1894
1858
  };
package/dist/index.d.ts CHANGED
@@ -455,6 +455,12 @@ interface components {
455
455
  name: string;
456
456
  /** Price */
457
457
  price: string;
458
+ /**
459
+ * Quantity
460
+ * @description How many of this extra are there?
461
+ * @default 1
462
+ */
463
+ quantity: number;
458
464
  };
459
465
  /**
460
466
  * ProductPriceDetails
@@ -508,7 +514,7 @@ interface components {
508
514
  priceDetails?: components["schemas"]["ProductPriceDetails"] | null;
509
515
  /**
510
516
  * Category
511
- * @description Foe example, `tv`, `internet`, `phone`. It can be used to show an icon in the UI.
517
+ * @description For example, `tv`, `internet`, `phone`. It can be used to show an icon in the UI.
512
518
  */
513
519
  category?: string | null;
514
520
  /**
@@ -516,6 +522,12 @@ interface components {
516
522
  * @description Extras are additional products that are bundled with the main product.
517
523
  */
518
524
  extras?: components["schemas"]["ProductExtra"][] | null;
525
+ /**
526
+ * Quantity
527
+ * @description How many of this product are there?
528
+ * @default 1
529
+ */
530
+ quantity: number;
519
531
  };
520
532
  /** Recommendation */
521
533
  Recommendation: {
@@ -770,7 +782,25 @@ interface paths {
770
782
  post: {
771
783
  parameters: {
772
784
  query?: never;
773
- header?: never;
785
+ header?: {
786
+ /**
787
+ * @description A 36 character hash, 5 segments, separated by dashes that uniquely identifies a page view (page-shown event)
788
+ * @example 1a1a1a1a-1a1a-1a1a-1a1a-1a1a1a1a1a1a
789
+ */
790
+ "x-page-view-id"?: string;
791
+ /** @description Web Analytics Platform User ID */
792
+ "x-web-analytics-platform-user-id"?: string;
793
+ /**
794
+ * @description The version of the frontend application that is making the request
795
+ * @example 1.0.0
796
+ */
797
+ "x-frontend-version"?: string;
798
+ /**
799
+ * @description The version of the SDK that is making the request
800
+ * @example 1.0.0
801
+ */
802
+ "x-sdk-version"?: string;
803
+ };
774
804
  path?: never;
775
805
  cookie?: never;
776
806
  };
@@ -988,85 +1018,6 @@ interface paths {
988
1018
  environment?: "development" | "ephemeral" | "local" | "production" | "staging" | "test" | "uat";
989
1019
  /** @description A JWT used to identify the user in the system, can be obtained from the identity endpoint */
990
1020
  identityToken: string;
991
- } | {
992
- /**
993
- * @description The customer that the event occurred on
994
- * @enum {string}
995
- */
996
- customerId: "spectrum";
997
- /** @description The timestamp describing the time the event occurred. This should conform to ISO 8601 standards and be in UTC */
998
- eventAt?: string;
999
- /** @description A JWT used to identify the user in the system, can be obtained from the identity endpoint */
1000
- identityToken: string;
1001
- /** @description The ID for the sale, a unique value we can correlate with customer records. */
1002
- saleId: string;
1003
- /**
1004
- * @description The type of user, for example, existing or prospect.
1005
- * @enum {string}
1006
- */
1007
- userType: "existing" | "prospect";
1008
- /** @description The browser the user is using, e.g. Chrome, Firefox, Safari, etc. */
1009
- browser?: string;
1010
- /** @description The user agent string e.g. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" */
1011
- userAgent?: string;
1012
- /** @description The device screen width in pixels - window.screen.width in JS. This is a user level property that should never change. */
1013
- screenWidth?: number;
1014
- /** @description The device screen height in pixels - window.screen.height in JS. This is a user level property that should never change. */
1015
- screenHeight?: number;
1016
- /**
1017
- * @description The size of the device's screen, based off the actual user experience it will generate, assuming the browser window takes up the whole screen.
1018
- *
1019
- * Based off https://15gifts.atlassian.net/wiki/spaces/AI/pages/3981443139/Breakpoints+for+mobile+desktop
1020
- *
1021
- * screen_width <= 480px = 'mobile'
1022
- * screen_width > 480px = 'large'
1023
- * @enum {string}
1024
- */
1025
- screenSize?: "mobile" | "large";
1026
- /** @description "A code that represents what currency the product price is listed in e.g. USD, GBP. This should match the ISO 4217 standard - see https://www.iban.com/currency-codes. */
1027
- currencyCode?: string;
1028
- /** @description The host/domain of the URL at the time the event is fired */
1029
- siteHost: string;
1030
- /** @description The path of the URL (including an initial `/`) at the time the event is fired */
1031
- sitePath?: string;
1032
- /** @description The query string of the URL (including an initial `?`) at the time the event is fired */
1033
- siteQueryString?: string;
1034
- /** @description The language of the part of the site the sales data is coming from in ISO 639-1 format e.g. 'en-us', 'es-us' etc. */
1035
- language?: string;
1036
- /** @description The recurring payment due per payment period */
1037
- priceRecurring: number;
1038
- /** @description An ISO-8601 duration that represents the period of time that the priceRecurring payment recurs over */
1039
- priceRecurringPeriod: string;
1040
- /** @description The upfront price the user has to pay for the product. */
1041
- priceUpfront?: number;
1042
- /** @description The full basket value of the sale, inclusive of any offers. */
1043
- totalValueOfSale?: number;
1044
- /** @description The taxes the user has to pay relating to the priceUpfront of the product(s) */
1045
- totalUpfrontTax?: number;
1046
- /** @description The taxes the user has to pay relating to the priceRecurring of the product(s), due per payment period */
1047
- totalRecurringTax?: number;
1048
- totalTaxOnSale?: number;
1049
- /** @description A list containing separate line items for each product sold. */
1050
- productsSold: {
1051
- /** @description The ID or SKU of a product that is provided by the customer */
1052
- siteProductId: string;
1053
- /** @description The name of the product */
1054
- siteProductName: string;
1055
- /** @description The category of products the product belongs to. */
1056
- siteProductType: string;
1057
- /** @description An ISO-8601 duration that represents the contract length */
1058
- productContractLength: string;
1059
- /** @description An integer representing how many of this particular product the user is purchasing */
1060
- quantity: number;
1061
- /** @description The upfront price the user has to pay for the product. */
1062
- productPriceUpfront: number;
1063
- /** @description The recurring payment per payment period for the product */
1064
- productPricePerPeriod: number;
1065
- /** @description An ISO-8601 duration that represents the period of time that the productPricePerPeriod payment recurs over */
1066
- productRecurringPaymentPeriod: string;
1067
- /** @description The ID or SKU of a bundle that the product (and other products being purchased at the same time) are part of */
1068
- bundleId?: string;
1069
- }[];
1070
1021
  } | {
1071
1022
  /**
1072
1023
  * @description The customer that the event occurred on
@@ -1128,7 +1079,7 @@ interface paths {
1128
1079
  /** @description A list containing separate line items for each product sold. */
1129
1080
  productsSold: {
1130
1081
  /** @description The ID or SKU of a product that is provided by the customer */
1131
- siteProductId: string;
1082
+ siteProductId?: string;
1132
1083
  /** @description The name of the product */
1133
1084
  siteProductName: string;
1134
1085
  /** @description The category of products the product belongs to. */
@@ -1207,7 +1158,7 @@ interface paths {
1207
1158
  /** @description A list containing separate line items for each product sold. */
1208
1159
  productsSold: {
1209
1160
  /** @description The ID or SKU of a product that is provided by the customer */
1210
- siteProductId: string;
1161
+ siteProductId?: string;
1211
1162
  /** @description The name of the product */
1212
1163
  siteProductName: string;
1213
1164
  /** @description The category of products the product belongs to. */
@@ -1284,7 +1235,7 @@ interface paths {
1284
1235
  };
1285
1236
  };
1286
1237
  };
1287
- /** @description Validation error response */
1238
+ /** @description Default Response */
1288
1239
  422: {
1289
1240
  headers: {
1290
1241
  [name: string]: unknown;
@@ -1309,7 +1260,10 @@ interface paths {
1309
1260
  /** @description The comparison that caused the error */
1310
1261
  comparison?: string;
1311
1262
  };
1312
- }[];
1263
+ }[] | {
1264
+ /** @description The error message */
1265
+ message?: string;
1266
+ };
1313
1267
  };
1314
1268
  };
1315
1269
  };
@@ -1439,6 +1393,8 @@ interface paths {
1439
1393
  conversation_id?: string;
1440
1394
  /** @description An integer representing the rank of the corresponding feedback score. It should always start at 0, even if the number of options changes. */
1441
1395
  feedback_score_num?: number;
1396
+ /** @description A hashed IP address for the user. Hashing Algorithm and Salt are in 1Password. */
1397
+ ip_address_hashed?: string;
1442
1398
  /** @description Describes the reason the tool ui was closed. When the value is 'customer_triggered' it's because it's been programmatically closed by the customer (by running window.axiom.integrations.hide() or window.axiom.integrations.minimise()). When it's 'user_close_click' it's because the actual end user has closed it manually by clicking. */
1443
1399
  tool_ui_closed_reason?: string;
1444
1400
  /** @description The turn number in the conversation. This links each user message to a corresponding assistant response. If there is an opening message from the assistant, this would have a message_turn of 1. Then the first message a user sends would have a message_turn of 2. The first actual response the assistant sends would have a message_turn of 2.
@@ -1462,7 +1418,11 @@ interface paths {
1462
1418
  message_text?: string;
1463
1419
  /** @description List of objects that represents the options for single & multiselect questions. */
1464
1420
  message_select_options?: unknown[];
1465
- /** @description true or false depending on whether the users message caused the assistant to provide a guardrail response */
1421
+ /** @description true or false depending on whether the users message caused the assistant to provide a fallback guardrail response.
1422
+ *
1423
+ * This happens for most guardrails, but in the case of pii-masking it will be false, because it strips the PII from the conversation history and continues the conversation as normal.
1424
+ *
1425
+ * To check whether the guardrail was triggered, use the is_guardrail_triggered property. */
1466
1426
  is_user_message_guardrailed?: boolean;
1467
1427
  /** @description A list of all guardrails checked for in the corresponding turn associated with the assistant_message-submitted event this property is part of. Includes whether they were triggered and some meaningful way of measuring how close to being triggered/not triggered they were, as well as categorising into input/output guardrails. */
1468
1428
  guardrails?: unknown[];
@@ -1532,6 +1492,8 @@ interface paths {
1532
1492
  slots?: unknown[];
1533
1493
  /** @description Describes the reason the entry point was closed. When the value is 'customer_triggered' it's because it's been programmatically closed by the customer (by running window.axiom.integrations.hide()). When it's 'user_close_click' it's because the actual end user has closed it manually by clicking. */
1534
1494
  entry_point_closed_reason?: string;
1495
+ /** @description A categorical property to denote which party was responsible for suppression. This is useful for accurately calculating control conversion rates, it allows us to count how many users were suppressed before humara loading, and how many were put in a control group. */
1496
+ suppressed_by?: unknown[];
1535
1497
  /** @description A list of objects for recommendations sent in a conversation api message. */
1536
1498
  recommendation_set?: unknown[];
1537
1499
  /** @description This is a score that evaluates how much progress has been made through the discovery phase of the conversation. A higher score means more information has been discovered. This value is generated by the recommender.
@@ -1853,6 +1815,7 @@ declare class Client {
1853
1815
  feedback_score_text?: string;
1854
1816
  conversation_id?: string;
1855
1817
  feedback_score_num?: number;
1818
+ ip_address_hashed?: string;
1856
1819
  tool_ui_closed_reason?: string;
1857
1820
  conversation_turn_num?: number;
1858
1821
  conversation_turn_id?: string;
@@ -1889,6 +1852,7 @@ declare class Client {
1889
1852
  experiment_variation_name?: string;
1890
1853
  slots?: unknown[];
1891
1854
  entry_point_closed_reason?: string;
1855
+ suppressed_by?: unknown[];
1892
1856
  recommendation_set?: unknown[];
1893
1857
  discovery_progress_score?: number;
1894
1858
  };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var A=Object.create;var d=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var n in t)d(e,n,{get:t[n],enumerable:!0})},O=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of R(t))!W.call(e,o)&&o!==n&&d(e,o,{get:()=>t[o],enumerable:!(i=D(t,o))||i.enumerable});return e};var j=(e,t,n)=>(n=e!=null?A(U(e)):{},O(t||!e||!e.__esModule?d(n,"default",{value:e,enumerable:!0}):n,e)),J=e=>O(d({},"__esModule",{value:!0}),e);var F={};V(F,{CONVERSATION_ID:()=>c,Client:()=>_,JWT_TOKEN:()=>f,SESSION_ID:()=>h,TTL:()=>N,USER_ID:()=>E,authMiddleware:()=>a,deleteConversationId:()=>u,errorMiddleware:()=>l,getConversationId:()=>m,getSessionId:()=>v,getToken:()=>M,getUserId:()=>S,headerMiddleware:()=>I,isTokenExpired:()=>P,setConversationId:()=>p,setSessionId:()=>y,setToken:()=>T,setUserId:()=>g});module.exports=J(F);var C=j(require("openapi-fetch"));var c="__15gifts_conversation_id",u=()=>sessionStorage.removeItem(c),m=()=>sessionStorage.getItem(c),p=e=>sessionStorage.setItem(c,e);var h="__15gifts_session_id",v=()=>sessionStorage.getItem(h),y=e=>sessionStorage.setItem(h,e);var G=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},w=G;var X=(e,t,n)=>{let i={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(i))},x=X;var z=1e3*60*60*24,E="__15gifts_user_id",N=z*30,S=()=>{let e=w(E);return e&&g(e),e},g=e=>x(E,e,N);var f="__15gifts_identity_token",P=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},M=()=>{let e=localStorage.getItem(f);return!e||P(e)?(localStorage.removeItem(f),null):e},T=e=>localStorage.setItem(f,e);var B=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),a=B;var H={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},l=H;var K=(e,t)=>({onRequest:async({request:n})=>(e.pageviewId&&n.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&n.headers.set("X-PAGE-URL",t),n)}),I=K;var b="0.13.0";var _=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:i,fetch:o,frontendUrl:r,headers:s}=t,k={...s,"X-SDK-VERSION":b};this.endpoint={conversation:(0,C.default)({baseUrl:n,fetch:o,headers:k,credentials:"include"}),frontend:(0,C.default)({baseUrl:r,fetch:o,headers:k})},this.identity={customerId:i,conversationId:m()??void 0,sessionId:v()??void 0,userId:S()??void 0},this.endpoint.conversation.use(l),this.endpoint.conversation.use(I(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:n,userId:i}=this.identity;try{let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:n,userId:i,url:window.location.href,userAgent:window.navigator.userAgent}});if(!o)throw new Error("No data received when creating identity");this.identity.pageviewId=o.pageviewId,n||(this.identity.sessionId=o.sessionId,y(o.sessionId)),i||(this.identity.userId=o.userId,g(o.userId)),T(o.token),Object.values(this.endpoint).forEach(r=>{r.use(a(o.token))})}catch(o){throw Object.values(this.endpoint).forEach(r=>{r.use(a())}),new Error("Failed to create identity. Please try again later.",{cause:o})}}endConversation(){u(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={...t},{data:i}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!i)return;let[o,r]=i,s=o.conversationId;if(!s)throw new Error("Conversation ID not received");return p(s),this.identity.conversationId=s,r}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let i=n.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(p(i),this.identity.conversationId=i),n.filter(r=>r.type!=="CONVERSATION_ID")}async trackEvent(t,n){let i={additionalProperties:n,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}getIdentity(){return this.identity}getIdentityToken(){return M()}};0&&(module.exports={CONVERSATION_ID,Client,JWT_TOKEN,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,errorMiddleware,getConversationId,getSessionId,getToken,getUserId,headerMiddleware,isTokenExpired,setConversationId,setSessionId,setToken,setUserId});
1
+ "use strict";var A=Object.create;var d=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var n in t)d(e,n,{get:t[n],enumerable:!0})},O=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of R(t))!W.call(e,o)&&o!==n&&d(e,o,{get:()=>t[o],enumerable:!(i=D(t,o))||i.enumerable});return e};var j=(e,t,n)=>(n=e!=null?A(U(e)):{},O(t||!e||!e.__esModule?d(n,"default",{value:e,enumerable:!0}):n,e)),J=e=>O(d({},"__esModule",{value:!0}),e);var F={};V(F,{CONVERSATION_ID:()=>c,Client:()=>_,JWT_TOKEN:()=>f,SESSION_ID:()=>h,TTL:()=>N,USER_ID:()=>E,authMiddleware:()=>a,deleteConversationId:()=>u,errorMiddleware:()=>l,getConversationId:()=>m,getSessionId:()=>v,getToken:()=>M,getUserId:()=>S,headerMiddleware:()=>I,isTokenExpired:()=>P,setConversationId:()=>p,setSessionId:()=>y,setToken:()=>T,setUserId:()=>g});module.exports=J(F);var C=j(require("openapi-fetch"));var c="__15gifts_conversation_id",u=()=>sessionStorage.removeItem(c),m=()=>sessionStorage.getItem(c),p=e=>sessionStorage.setItem(c,e);var h="__15gifts_session_id",v=()=>sessionStorage.getItem(h),y=e=>sessionStorage.setItem(h,e);var G=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},w=G;var X=(e,t,n)=>{let i={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(i))},x=X;var z=1e3*60*60*24,E="__15gifts_user_id",N=z*30,S=()=>{let e=w(E);return e&&g(e),e},g=e=>x(E,e,N);var f="__15gifts_identity_token",P=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},M=()=>{let e=localStorage.getItem(f);return!e||P(e)?(localStorage.removeItem(f),null):e},T=e=>localStorage.setItem(f,e);var B=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),a=B;var H={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},l=H;var K=(e,t)=>({onRequest:async({request:n})=>(e.pageviewId&&n.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&n.headers.set("X-PAGE-URL",t),n)}),I=K;var b="0.13.2";var _=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:i,fetch:o,frontendUrl:r,headers:s}=t,k={...s,"X-SDK-VERSION":b};this.endpoint={conversation:(0,C.default)({baseUrl:n,fetch:o,headers:k,credentials:"include"}),frontend:(0,C.default)({baseUrl:r,fetch:o,headers:k})},this.identity={customerId:i,conversationId:m()??void 0,sessionId:v()??void 0,userId:S()??void 0},this.endpoint.conversation.use(l),this.endpoint.conversation.use(I(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:n,userId:i}=this.identity;try{let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:n,userId:i,url:window.location.href,userAgent:window.navigator.userAgent}});if(!o)throw new Error("No data received when creating identity");this.identity.pageviewId=o.pageviewId,n||(this.identity.sessionId=o.sessionId,y(o.sessionId)),i||(this.identity.userId=o.userId,g(o.userId)),T(o.token),Object.values(this.endpoint).forEach(r=>{r.use(a(o.token))})}catch(o){throw Object.values(this.endpoint).forEach(r=>{r.use(a())}),new Error("Failed to create identity. Please try again later.",{cause:o})}}endConversation(){u(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={...t},{data:i}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!i)return;let[o,r]=i,s=o.conversationId;if(!s)throw new Error("Conversation ID not received");return p(s),this.identity.conversationId=s,r}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let i=n.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(p(i),this.identity.conversationId=i),n.filter(r=>r.type!=="CONVERSATION_ID")}async trackEvent(t,n){let i={additionalProperties:n,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}getIdentity(){return this.identity}getIdentityToken(){return M()}};0&&(module.exports={CONVERSATION_ID,Client,JWT_TOKEN,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,errorMiddleware,getConversationId,getSessionId,getToken,getUserId,headerMiddleware,isTokenExpired,setConversationId,setSessionId,setToken,setUserId});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationIdMessage, Endpoint, Identity, Message, TextMessage, TrackingEvent } from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new Error('No data received when creating identity')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new Error('Failed to create identity. Please try again later.', { cause: error })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.13.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"npm run generate && tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,oBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAArB,GCAA,IAAAsB,EAAiD,4BCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,Q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Aa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,KAAM,qBACN,oBAAAS,CACF,CACF,CAAC,EAED,GAAI,CAACT,EAAM,OAEX,GAAM,CAACU,EAAuBC,CAAc,EAAIX,EAE1CY,EAAiBF,EAAsB,eAC7C,GAAI,CAACE,EACH,MAAM,IAAI,MAAM,8BAA8B,EAGhD,OAAAC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,EAExBD,CACT,CAqBA,MAAM,YAAY,CAChB,YAAAG,CACF,EAEmE,CACjE,GAAM,CAAE,KAAAd,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,YAAAc,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACd,EAAM,OAGX,IAAMY,EAAiBZ,EAAK,KAAMe,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIH,IACFC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBZ,EAAK,OAAQe,GAAYA,EAAQ,OAAS,iBAAiB,CAE9E,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","headers_default","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","message","eventName","properties","body","getToken"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationIdMessage, Endpoint, Identity, Message, TextMessage, TrackingEvent } from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new Error('No data received when creating identity')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new Error('Failed to create identity. Please try again later.', { cause: error })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.13.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"npm run generate && tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,oBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAArB,GCAA,IAAAsB,EAAiD,4BCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,ECVf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,CAAI,CAAC,CAChD,EAEOC,EAAQL,ECdf,IAAMM,EAAM,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IH,IACFC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBZ,EAAK,OAAQe,GAAYA,EAAQ,OAAS,iBAAiB,CAE9E,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","headers_default","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","message","eventName","properties","body","getToken"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import _ from"openapi-fetch";var d="__15gifts_conversation_id",h=()=>sessionStorage.removeItem(d),v=()=>sessionStorage.getItem(d),c=e=>sessionStorage.setItem(d,e);var y="__15gifts_session_id",w=()=>sessionStorage.getItem(y),x=e=>sessionStorage.setItem(y,e);var O=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},p=O;var N=(e,t,n)=>{let i={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(i))},g=N;var P=1e3*60*60*24,E="__15gifts_user_id",b=P*30,S=()=>{let e=p(E);return e&&f(e),e},f=e=>g(E,e,b);var l="__15gifts_identity_token",A=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},M=()=>{let e=localStorage.getItem(l);return!e||A(e)?(localStorage.removeItem(l),null):e},T=e=>localStorage.setItem(l,e);var D=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),a=D;var R={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},I=R;var U=(e,t)=>({onRequest:async({request:n})=>(e.pageviewId&&n.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&n.headers.set("X-PAGE-URL",t),n)}),u=U;var C="0.13.0";var k=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:i,fetch:o,frontendUrl:r,headers:s}=t,m={...s,"X-SDK-VERSION":C};this.endpoint={conversation:_({baseUrl:n,fetch:o,headers:m,credentials:"include"}),frontend:_({baseUrl:r,fetch:o,headers:m})},this.identity={customerId:i,conversationId:v()??void 0,sessionId:w()??void 0,userId:S()??void 0},this.endpoint.conversation.use(I),this.endpoint.conversation.use(u(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:n,userId:i}=this.identity;try{let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:n,userId:i,url:window.location.href,userAgent:window.navigator.userAgent}});if(!o)throw new Error("No data received when creating identity");this.identity.pageviewId=o.pageviewId,n||(this.identity.sessionId=o.sessionId,x(o.sessionId)),i||(this.identity.userId=o.userId,f(o.userId)),T(o.token),Object.values(this.endpoint).forEach(r=>{r.use(a(o.token))})}catch(o){throw Object.values(this.endpoint).forEach(r=>{r.use(a())}),new Error("Failed to create identity. Please try again later.",{cause:o})}}endConversation(){h(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={...t},{data:i}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!i)return;let[o,r]=i,s=o.conversationId;if(!s)throw new Error("Conversation ID not received");return c(s),this.identity.conversationId=s,r}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let i=n.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(c(i),this.identity.conversationId=i),n.filter(r=>r.type!=="CONVERSATION_ID")}async trackEvent(t,n){let i={additionalProperties:n,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}getIdentity(){return this.identity}getIdentityToken(){return M()}};export{d as CONVERSATION_ID,k as Client,l as JWT_TOKEN,y as SESSION_ID,b as TTL,E as USER_ID,a as authMiddleware,h as deleteConversationId,I as errorMiddleware,v as getConversationId,w as getSessionId,M as getToken,S as getUserId,u as headerMiddleware,A as isTokenExpired,c as setConversationId,x as setSessionId,T as setToken,f as setUserId};
1
+ import _ from"openapi-fetch";var d="__15gifts_conversation_id",h=()=>sessionStorage.removeItem(d),v=()=>sessionStorage.getItem(d),c=e=>sessionStorage.setItem(d,e);var y="__15gifts_session_id",w=()=>sessionStorage.getItem(y),x=e=>sessionStorage.setItem(y,e);var O=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},p=O;var N=(e,t,n)=>{let i={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(i))},g=N;var P=1e3*60*60*24,E="__15gifts_user_id",b=P*30,S=()=>{let e=p(E);return e&&f(e),e},f=e=>g(E,e,b);var l="__15gifts_identity_token",A=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},M=()=>{let e=localStorage.getItem(l);return!e||A(e)?(localStorage.removeItem(l),null):e},T=e=>localStorage.setItem(l,e);var D=e=>({onRequest:async({request:t})=>{if(t.url.includes("/identity/"))return t;if(!e)throw new Error("Access token is required for authentication.");return t.headers.set("Authorization",`Bearer ${e}`),t}}),a=D;var R={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},I=R;var U=(e,t)=>({onRequest:async({request:n})=>(e.pageviewId&&n.headers.set("X-PAGEVIEW-ID",e.pageviewId),t&&n.headers.set("X-PAGE-URL",t),n)}),u=U;var C="0.13.2";var k=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:i,fetch:o,frontendUrl:r,headers:s}=t,m={...s,"X-SDK-VERSION":C};this.endpoint={conversation:_({baseUrl:n,fetch:o,headers:m,credentials:"include"}),frontend:_({baseUrl:r,fetch:o,headers:m})},this.identity={customerId:i,conversationId:v()??void 0,sessionId:w()??void 0,userId:S()??void 0},this.endpoint.conversation.use(I),this.endpoint.conversation.use(u(this.identity,window.location.href))}async createIdentity(){let{customerId:t,sessionId:n,userId:i}=this.identity;try{let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:n,userId:i,url:window.location.href,userAgent:window.navigator.userAgent}});if(!o)throw new Error("No data received when creating identity");this.identity.pageviewId=o.pageviewId,n||(this.identity.sessionId=o.sessionId,x(o.sessionId)),i||(this.identity.userId=o.userId,f(o.userId)),T(o.token),Object.values(this.endpoint).forEach(r=>{r.use(a(o.token))})}catch(o){throw Object.values(this.endpoint).forEach(r=>{r.use(a())}),new Error("Failed to create identity. Please try again later.",{cause:o})}}endConversation(){h(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={...t},{data:i}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!i)return;let[o,r]=i,s=o.conversationId;if(!s)throw new Error("Conversation ID not received");return c(s),this.identity.conversationId=s,r}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let i=n.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(c(i),this.identity.conversationId=i),n.filter(r=>r.type!=="CONVERSATION_ID")}async trackEvent(t,n){let i={additionalProperties:n,conversationId:this.identity.conversationId,eventName:t,pageviewId:this.identity.pageviewId??"unknown",screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}getIdentity(){return this.identity}getIdentityToken(){return M()}};export{d as CONVERSATION_ID,k as Client,l as JWT_TOKEN,y as SESSION_ID,b as TTL,E as USER_ID,a as authMiddleware,h as deleteConversationId,I as errorMiddleware,v as getConversationId,w as getSessionId,M as getToken,S as getUserId,u as headerMiddleware,A as isTokenExpired,c as setConversationId,x as setSessionId,T as setToken,f as setUserId};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationIdMessage, Endpoint, Identity, Message, TextMessage, TrackingEvent } from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new Error('No data received when creating identity')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new Error('Failed to create identity. Please try again later.', { cause: error })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.13.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"npm run generate && tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAA0C,gBCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF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AAAd,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,YAAAc,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACd,EAAM,OAGX,IAAMY,EAAiBZ,EAAK,KAAMe,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIH,IACFC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBZ,EAAK,OAAQe,GAAYA,EAAQ,OAAS,iBAAiB,CAE9E,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","message","eventName","properties","body","getToken"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../src/middlewares/headers.ts","../package.json"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware, headerMiddleware } from './middlewares'\nimport type { components, paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationIdMessage, Endpoint, Identity, Message, TextMessage, TrackingEvent } from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v3')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({\n baseUrl: conversationUrl,\n fetch,\n headers,\n credentials: 'include',\n }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n\n this.endpoint.conversation.use(errorMiddleware)\n this.endpoint.conversation.use(headerMiddleware(this.identity, window.location.href))\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n * This should not be called more than once per page load.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { customerId, sessionId, userId } = this.identity\n\n try {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n },\n })\n\n if (!data) {\n throw new Error('No data received when creating identity')\n }\n\n this.identity.pageviewId = data.pageviewId\n\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n // Add the access token to the Authorization header for all endpoints\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware(data.token))\n })\n } catch (error) {\n // Enable the auth middleware without a token so that it will throw an error before sending\n // the request, preventing unnecessary API calls / 401 responses.\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.use(authMiddleware())\n })\n throw new Error('Failed to create identity. Please try again later.', { cause: error })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n *\n * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: components['schemas']['ConversationContext']): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage>[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n eventName,\n pageviewId: this.identity.pageviewId ?? 'unknown',\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","/**\n * Set an item in localStorage with an expiration time\n * @param key The key under which the value is stored in localStorage\n * @param value The value to be stored\n * @param ttl The time-to-live (TTL) in milliseconds\n */\nconst setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\nconst day = 1000 * 60 * 60 * 24\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = day * 30\n\n/**\n * Retrieves the user ID from `localStorage` and updates its expiry time.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => {\n const userId = getItemWithExpiry(USER_ID)\n\n // Update the userId with a new expiry time\n // So that it will be valid for another 30 days, rather than 30 days from when it was first set\n if (userId) {\n setUserId(userId)\n }\n\n return userId\n}\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken?: string): Middleware => ({\n onRequest: async ({ request }) => {\n const isIdentityEndpoint = request.url.includes('/identity/')\n if (isIdentityEndpoint) {\n return request\n }\n\n // Throw an error because we know the API will return a 401 if the access token is not set.\n if (!accessToken) {\n throw new Error('Access token is required for authentication.')\n }\n\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\nimport { Identity } from '../types'\n\n/**\n * Middleware for adding request headers that other services use for tracking.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { pageViewId } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(headerMiddleware('123', 'https://example.com'))\n * ```\n */\nconst headerMiddleware = (identity: Identity, url: string): Middleware => ({\n onRequest: async ({ request }) => {\n if (identity.pageviewId) {\n request.headers.set('X-PAGEVIEW-ID', identity.pageviewId)\n }\n if (url) {\n request.headers.set('X-PAGE-URL', url)\n }\n\n return request\n },\n})\n\nexport default headerMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.13.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"npm run generate && tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAA0C,gBCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO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AAK,SAAS,eAAiBA,EAExBD,CACT,CAqBA,MAAM,YAAY,CAChB,YAAAG,CACF,EAEmE,CACjE,GAAM,CAAE,KAAAd,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,YAAAc,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACd,EAAM,OAGX,IAAMY,EAAiBZ,EAAK,KAAMe,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIH,IACFC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBZ,EAAK,OAAQe,GAAYA,EAAQ,OAAS,iBAAiB,CAE9E,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,UAAAD,EACA,WAAY,KAAK,SAAS,YAAc,UACxC,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","day","USER_ID","TTL","getUserId","userId","getItemWithExpiry_default","setUserId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","headerMiddleware","identity","url","request","headers_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","headers_default","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","error","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","message","eventName","properties","body","getToken"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "files": [
5
5
  "dist"
6
6
  ],