@15gifts/sdk 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -469,7 +469,7 @@ interface operations {
469
469
  [name: string]: unknown;
470
470
  };
471
471
  content: {
472
- 'application/json': components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'];
472
+ 'application/json': (components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'])[];
473
473
  };
474
474
  };
475
475
  /** @description Validation Error */
@@ -930,8 +930,11 @@ interface paths {
930
930
  * "url": "https://www.example.com/telco/"
931
931
  * } */
932
932
  'application/json': {
933
- /** @description Event Name */
934
- eventName: string;
933
+ /**
934
+ * @description Event Name
935
+ * @enum {string}
936
+ */
937
+ eventName: 'welcome_screen-shown' | 'tab-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool-closed' | 'user_message-submitted' | 'assistant_message-submitted' | 'feedback-shown' | 'feedback_skip-clicked' | 'sale-completed' | 'tab-clicked' | 'tool_close-clicked' | 'woo_assistant_message-submitted' | 'woo_user_message-submitted' | 'woo_reaction-submitted';
935
938
  /** @description Customer ID */
936
939
  customerId: string;
937
940
  /** @description User ID */
@@ -949,7 +952,9 @@ interface paths {
949
952
  deviceType?: 'desktop' | 'mobile' | 'tablet';
950
953
  /** @description User Agent */
951
954
  userAgent?: string;
952
- additionalProperties?: Record<string, never>;
955
+ additionalProperties?: {
956
+ [key: string]: string | number | boolean;
957
+ };
953
958
  };
954
959
  };
955
960
  };
@@ -978,9 +983,19 @@ interface paths {
978
983
  };
979
984
  }
980
985
 
981
- type ConversationApiRequest = components['schemas']['ConversationRequest'];
986
+ /**
987
+ * These are the types as defined in the OpenAPI schema.
988
+ * We don't use them directly, or export them here because of how they appear in the documentation site.
989
+ */
990
+ type ApiConversationRequest = components['schemas']['ConversationRequest'];
982
991
  type ApiMessage = components['schemas']['ConversationResponseMessageChunk'];
983
992
  type ApiDebug = components['schemas']['ConversationResponseDebugChunk'];
993
+ type ApiTrackingEvent = paths['/api/tracking/user/v1']['post']['requestBody']['content']['application/json'];
994
+ /**
995
+ * The request to the conversation API.
996
+ */
997
+ interface ConversationApiRequest extends ApiConversationRequest {
998
+ }
984
999
  /**
985
1000
  * Configuration options for initializing the client.
986
1001
  */
@@ -1040,7 +1055,7 @@ interface Identity {
1040
1055
  /**
1041
1056
  * Message within a conversation.
1042
1057
  */
1043
- interface Message {
1058
+ interface Message extends ApiMessage {
1044
1059
  /**
1045
1060
  * The conversation ID to which the message belongs.
1046
1061
  */
@@ -1068,6 +1083,8 @@ interface DebugResponse {
1068
1083
  */
1069
1084
  type: ApiDebug['type'];
1070
1085
  }
1086
+ interface TrackingEvent extends ApiTrackingEvent {
1087
+ }
1071
1088
 
1072
1089
  /**
1073
1090
  * The `Client` class provides methods to manage 15gifts API.
@@ -1124,12 +1141,12 @@ declare class Client {
1124
1141
  * Sends a message in the conversation, optionally with an opening message.
1125
1142
  *
1126
1143
  * @param options - An object containing the opening message and the user message.
1127
- * @returns A promise that resolves to a message or a debug record.
1144
+ * @returns A promise that resolves to an array of messages or debug records.
1128
1145
  * If the message is a debug record, it will throw an error.
1129
1146
  *
1130
1147
  * @example
1131
1148
  * ```ts
1132
- * const newMessage = await client.sendMessage({
1149
+ * const newMessages = await client.sendMessage({
1133
1150
  * openingMessage: 'Hello! How can I help you?',
1134
1151
  * userMessage: 'How can I get support?',
1135
1152
  * })
@@ -1144,7 +1161,24 @@ declare class Client {
1144
1161
  sendMessage({ openingMessage, userMessage, }: {
1145
1162
  openingMessage?: ConversationApiRequest['openingMessage'];
1146
1163
  userMessage: ConversationApiRequest['userMessage'];
1147
- }): Promise<Message | undefined>;
1164
+ }): Promise<Message[] | undefined>;
1165
+ /**
1166
+ * Sends an event to the tracking API, with the required properties already set.
1167
+ *
1168
+ * @param eventName - The name of the event to track.
1169
+ * @param properties - Additional properties to include in the event.
1170
+ * @returns A promise that resolves once the event is tracked.
1171
+ *
1172
+ * @example
1173
+ * ```ts
1174
+ * await client.trackEvent('tab-shown')
1175
+ * ```
1176
+ */
1177
+ trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']): Promise<{
1178
+ data?: undefined;
1179
+ error?: undefined;
1180
+ response: Response;
1181
+ }>;
1148
1182
  }
1149
1183
 
1150
1184
  /**
@@ -1266,4 +1300,4 @@ declare const getUserId: () => string | null;
1266
1300
  */
1267
1301
  declare const setUserId: (userId: string) => void;
1268
1302
 
1269
- export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
1303
+ export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
package/dist/index.d.ts CHANGED
@@ -469,7 +469,7 @@ interface operations {
469
469
  [name: string]: unknown;
470
470
  };
471
471
  content: {
472
- 'application/json': components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'];
472
+ 'application/json': (components['schemas']['ConversationResponseMessageChunk'] | components['schemas']['ConversationResponseDebugChunk'])[];
473
473
  };
474
474
  };
475
475
  /** @description Validation Error */
@@ -930,8 +930,11 @@ interface paths {
930
930
  * "url": "https://www.example.com/telco/"
931
931
  * } */
932
932
  'application/json': {
933
- /** @description Event Name */
934
- eventName: string;
933
+ /**
934
+ * @description Event Name
935
+ * @enum {string}
936
+ */
937
+ eventName: 'welcome_screen-shown' | 'tab-shown' | 'feedback_submit-clicked' | 'page-shown' | 'tool-closed' | 'user_message-submitted' | 'assistant_message-submitted' | 'feedback-shown' | 'feedback_skip-clicked' | 'sale-completed' | 'tab-clicked' | 'tool_close-clicked' | 'woo_assistant_message-submitted' | 'woo_user_message-submitted' | 'woo_reaction-submitted';
935
938
  /** @description Customer ID */
936
939
  customerId: string;
937
940
  /** @description User ID */
@@ -949,7 +952,9 @@ interface paths {
949
952
  deviceType?: 'desktop' | 'mobile' | 'tablet';
950
953
  /** @description User Agent */
951
954
  userAgent?: string;
952
- additionalProperties?: Record<string, never>;
955
+ additionalProperties?: {
956
+ [key: string]: string | number | boolean;
957
+ };
953
958
  };
954
959
  };
955
960
  };
@@ -978,9 +983,19 @@ interface paths {
978
983
  };
979
984
  }
980
985
 
981
- type ConversationApiRequest = components['schemas']['ConversationRequest'];
986
+ /**
987
+ * These are the types as defined in the OpenAPI schema.
988
+ * We don't use them directly, or export them here because of how they appear in the documentation site.
989
+ */
990
+ type ApiConversationRequest = components['schemas']['ConversationRequest'];
982
991
  type ApiMessage = components['schemas']['ConversationResponseMessageChunk'];
983
992
  type ApiDebug = components['schemas']['ConversationResponseDebugChunk'];
993
+ type ApiTrackingEvent = paths['/api/tracking/user/v1']['post']['requestBody']['content']['application/json'];
994
+ /**
995
+ * The request to the conversation API.
996
+ */
997
+ interface ConversationApiRequest extends ApiConversationRequest {
998
+ }
984
999
  /**
985
1000
  * Configuration options for initializing the client.
986
1001
  */
@@ -1040,7 +1055,7 @@ interface Identity {
1040
1055
  /**
1041
1056
  * Message within a conversation.
1042
1057
  */
1043
- interface Message {
1058
+ interface Message extends ApiMessage {
1044
1059
  /**
1045
1060
  * The conversation ID to which the message belongs.
1046
1061
  */
@@ -1068,6 +1083,8 @@ interface DebugResponse {
1068
1083
  */
1069
1084
  type: ApiDebug['type'];
1070
1085
  }
1086
+ interface TrackingEvent extends ApiTrackingEvent {
1087
+ }
1071
1088
 
1072
1089
  /**
1073
1090
  * The `Client` class provides methods to manage 15gifts API.
@@ -1124,12 +1141,12 @@ declare class Client {
1124
1141
  * Sends a message in the conversation, optionally with an opening message.
1125
1142
  *
1126
1143
  * @param options - An object containing the opening message and the user message.
1127
- * @returns A promise that resolves to a message or a debug record.
1144
+ * @returns A promise that resolves to an array of messages or debug records.
1128
1145
  * If the message is a debug record, it will throw an error.
1129
1146
  *
1130
1147
  * @example
1131
1148
  * ```ts
1132
- * const newMessage = await client.sendMessage({
1149
+ * const newMessages = await client.sendMessage({
1133
1150
  * openingMessage: 'Hello! How can I help you?',
1134
1151
  * userMessage: 'How can I get support?',
1135
1152
  * })
@@ -1144,7 +1161,24 @@ declare class Client {
1144
1161
  sendMessage({ openingMessage, userMessage, }: {
1145
1162
  openingMessage?: ConversationApiRequest['openingMessage'];
1146
1163
  userMessage: ConversationApiRequest['userMessage'];
1147
- }): Promise<Message | undefined>;
1164
+ }): Promise<Message[] | undefined>;
1165
+ /**
1166
+ * Sends an event to the tracking API, with the required properties already set.
1167
+ *
1168
+ * @param eventName - The name of the event to track.
1169
+ * @param properties - Additional properties to include in the event.
1170
+ * @returns A promise that resolves once the event is tracked.
1171
+ *
1172
+ * @example
1173
+ * ```ts
1174
+ * await client.trackEvent('tab-shown')
1175
+ * ```
1176
+ */
1177
+ trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']): Promise<{
1178
+ data?: undefined;
1179
+ error?: undefined;
1180
+ response: Response;
1181
+ }>;
1148
1182
  }
1149
1183
 
1150
1184
  /**
@@ -1266,4 +1300,4 @@ declare const getUserId: () => string | null;
1266
1300
  */
1267
1301
  declare const setUserId: (userId: string) => void;
1268
1302
 
1269
- export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
1303
+ export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var E=Object.create;var o=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var P=(e,t)=>{for(var s in t)o(e,s,{get:t[s],enumerable:!0})},S=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of b(t))!O.call(e,n)&&n!==s&&o(e,n,{get:()=>t[n],enumerable:!(i=D(t,n))||i.enumerable});return e};var R=(e,t,s)=>(s=e!=null?E(U(e)):{},S(t||!e||!e.__esModule?o(s,"default",{value:e,enumerable:!0}):s,e)),w=e=>S(o({},"__esModule",{value:!0}),e);var T={};P(T,{CONVERSATION_ID:()=>r,Client:()=>x,SESSION_ID:()=>c,TTL:()=>C,USER_ID:()=>u,deleteConversationId:()=>d,getConversationId:()=>a,getSessionId:()=>I,getUserId:()=>v,setConversationId:()=>p,setSessionId:()=>m,setUserId:()=>y});module.exports=w(T);var h=R(require("openapi-fetch"));var r="__15gifts_conversation_id",d=()=>sessionStorage.removeItem(r),a=()=>sessionStorage.getItem(r),p=e=>sessionStorage.setItem(r,e);var c="__15gifts_session_id",I=()=>sessionStorage.getItem(c),m=e=>sessionStorage.setItem(c,e);var M=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},g=M;var N=(e,t,s)=>{let i={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(i))},f=N;var u="__15gifts_user_id",C=1e3*60*60*24*30,v=()=>g(u),y=e=>f(u,e,C);var _="0.2.0";var x=class{endpoint;identity;constructor({customerId:t,fetch:s,conversationUrl:i,frontendUrl:n}){let l={"X-SDK-VERSION":_};this.endpoint={conversation:(0,h.default)({baseUrl:i,fetch:s,headers:l}),frontend:(0,h.default)({baseUrl:n,fetch:s,headers:l})},this.identity={customerId:t,conversationId:a(),sessionId:I()??"",userId:v()}}async createIdentity(){let{conversationId:t,sessionId:s,userId:i}=this.identity;if(t&&this.endConversation(),!s||!i){let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!s,createUserId:!i,customerId:this.identity.customerId}});n&&(!s&&n.sessionId&&(this.identity.sessionId=n.sessionId,m(n.sessionId)),!i&&n.userId&&(this.identity.userId=n.userId,y(n.userId)))}}endConversation(){d()}async sendMessage({openingMessage:t,userMessage:s}){t&&this.identity.conversationId&&this.endConversation();let{data:i}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:t,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:s}});if(i){if(p(i.conversationId),i.type==="DEBUG")throw i;return i}}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,setUserId});
1
+ "use strict";var _=Object.create;var o=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var U=(e,t)=>{for(var s in t)o(e,s,{get:t[s],enumerable:!0})},S=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of w(t))!O.call(e,i)&&i!==s&&o(e,i,{get:()=>t[i],enumerable:!(n=P(t,i))||n.enumerable});return e};var b=(e,t,s)=>(s=e!=null?_(T(e)):{},S(t||!e||!e.__esModule?o(s,"default",{value:e,enumerable:!0}):s,e)),k=e=>S(o({},"__esModule",{value:!0}),e);var R={};U(R,{CONVERSATION_ID:()=>r,Client:()=>x,SESSION_ID:()=>c,TTL:()=>E,USER_ID:()=>f,deleteConversationId:()=>d,getConversationId:()=>a,getSessionId:()=>I,getUserId:()=>v,setConversationId:()=>p,setSessionId:()=>m,setUserId:()=>y});module.exports=k(R);var h=b(require("openapi-fetch"));var r="__15gifts_conversation_id",d=()=>sessionStorage.removeItem(r),a=()=>sessionStorage.getItem(r),p=e=>sessionStorage.setItem(r,e);var c="__15gifts_session_id",I=()=>sessionStorage.getItem(c),m=e=>sessionStorage.setItem(c,e);var D=e=>{let t=localStorage.getItem(e);if(!t)return null;let s=JSON.parse(t);return Date.now()>s.expires?(localStorage.removeItem(e),null):s.value},u=D;var M=(e,t,s)=>{let n={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(n))},g=M;var f="__15gifts_user_id",E=1e3*60*60*24*30,v=()=>u(f),y=e=>g(f,e,E);var C="0.3.1";var x=class{endpoint;identity;constructor({customerId:t,fetch:s,conversationUrl:n,frontendUrl:i}){let l={"X-SDK-VERSION":C};this.endpoint={conversation:(0,h.default)({baseUrl:n,fetch:s,headers:l}),frontend:(0,h.default)({baseUrl:i,fetch:s,headers:l})},this.identity={customerId:t,conversationId:a(),sessionId:I()??"",userId:v()}}async createIdentity(){let{conversationId:t,sessionId:s,userId:n}=this.identity;if(t&&this.endConversation(),!s||!n){let{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!s,createUserId:!n,customerId:this.identity.customerId}});i&&(!s&&i.sessionId&&(this.identity.sessionId=i.sessionId,m(i.sessionId)),!n&&i.userId&&(this.identity.userId=i.userId,y(i.userId)))}}endConversation(){d()}async sendMessage({openingMessage:t,userMessage:s}){t&&this.identity.conversationId&&this.endConversation();let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:t,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:s}});if(!n)return;let[i]=n;if(i?.conversationId&&p(i.conversationId),i?.type==="DEBUG")throw i;return n}async trackEvent(t,s){let n={additionalProperties:s,conversationId:this.identity.conversationId||void 0,customerId:this.identity.customerId,deviceType:void 0,eventName:t,sessionId:this.identity.sessionId,url:window.location.href,userAgent:window.navigator.userAgent,userId:this.identity.userId||void 0};return this.endpoint.frontend.POST("/api/tracking/user/v1",{body:n})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,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","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './types'\n","import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, DebugResponse, Endpoint, Identity, Message } 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-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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to a message or a debug record.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessage = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n setConversationId(data.conversationId)\n if (data.type === 'DEBUG') {\n throw data as DebugResponse\n }\n\n return data\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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","const 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'\n\n/**\n * The key used to store the user ID in `localStorage`.\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 */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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 \"name\": \"@15gifts/sdk\",\n \"version\": \"0.2.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\": \"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 \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.0\",\n \"tsup\": \"^8.2.4\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAd,GCAA,IAAAe,EAAyB,4BCGlB,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,EClC/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,EChBf,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,ECJR,IAAMM,EAAU,oBAMVC,EAAM,IAAO,GAAK,GAAK,GAAK,GAkB5BC,EAAY,IAAMC,EAAkBH,CAAO,EAa3CI,EAAaC,G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BAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAI,EACA,UAAW,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAKL,EAGL,IADAM,EAAkBN,EAAK,cAAc,EACjCA,EAAK,OAAS,QAChB,MAAMA,EAGR,OAAOA,EACT,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","deleteConversationId","getConversationId","getSessionId","getUserId","setConversationId","setSessionId","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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","setConversationId"]}
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","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './types'\n","import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, Endpoint, Identity, Message, 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-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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n const [firstMessage] = data\n\n if (firstMessage?.conversationId) {\n setConversationId(firstMessage.conversationId)\n }\n\n if (firstMessage?.type === 'DEBUG') {\n throw firstMessage\n }\n\n // Based on the above check, we assume that the data is an array of messages and not debug records\n return data as Message[]\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('tab-shown')\n * ```\n */\n async trackEvent(\n eventName: TrackingEvent['eventName'],\n properties?: TrackingEvent['additionalProperties'],\n ): Promise<{ data?: undefined; error?: undefined; response: Response }> {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId || undefined,\n customerId: this.identity.customerId,\n deviceType: undefined,\n eventName,\n sessionId: this.identity.sessionId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n userId: this.identity.userId || undefined,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v1', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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","const 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'\n\n/**\n * The key used to store the user ID in `localStorage`.\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 */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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 \"name\": \"@15gifts/sdk\",\n \"version\": \"0.3.1\",\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\": \"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 \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch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K,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAI,EACA,UAAW,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAI,CAACL,EAAM,OAEX,GAAM,CAACM,CAAY,EAAIN,EAMvB,GAJIM,GAAc,gBAChBC,EAAkBD,EAAa,cAAc,EAG3CA,GAAc,OAAS,QACzB,MAAMA,EAIR,OAAON,CACT,CAcA,MAAM,WACJQ,EACAC,EACsE,CACtE,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,gBAAkB,OAChD,WAAY,KAAK,SAAS,WAC1B,WAAY,OACZ,UAAAD,EACA,UAAW,KAAK,SAAS,UACzB,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,UAC5B,OAAQ,KAAK,SAAS,QAAU,MAClC,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","deleteConversationId","getConversationId","getSessionId","getUserId","setConversationId","setSessionId","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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","firstMessage","setConversationId","eventName","properties","body"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import x from"openapi-fetch";var o="__15gifts_conversation_id",p=()=>sessionStorage.removeItem(o),c=()=>sessionStorage.getItem(o),I=s=>sessionStorage.setItem(o,s);var m="__15gifts_session_id",g=()=>sessionStorage.getItem(m),f=s=>sessionStorage.setItem(m,s);var S=s=>{let i=localStorage.getItem(s);if(!i)return null;let e=JSON.parse(i);return Date.now()>e.expires?(localStorage.removeItem(s),null):e.value},r=S;var C=(s,i,e)=>{let t={expires:Date.now()+e,value:i};localStorage.setItem(s,JSON.stringify(t))},d=C;var u="__15gifts_user_id",_=1e3*60*60*24*30,v=()=>r(u),y=s=>d(u,s,_);var h="0.2.0";var l=class{endpoint;identity;constructor({customerId:i,fetch:e,conversationUrl:t,frontendUrl:n}){let a={"X-SDK-VERSION":h};this.endpoint={conversation:x({baseUrl:t,fetch:e,headers:a}),frontend:x({baseUrl:n,fetch:e,headers:a})},this.identity={customerId:i,conversationId:c(),sessionId:g()??"",userId:v()}}async createIdentity(){let{conversationId:i,sessionId:e,userId:t}=this.identity;if(i&&this.endConversation(),!e||!t){let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!e,createUserId:!t,customerId:this.identity.customerId}});n&&(!e&&n.sessionId&&(this.identity.sessionId=n.sessionId,f(n.sessionId)),!t&&n.userId&&(this.identity.userId=n.userId,y(n.userId)))}}endConversation(){p()}async sendMessage({openingMessage:i,userMessage:e}){i&&this.identity.conversationId&&this.endConversation();let{data:t}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:i,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:e}});if(t){if(I(t.conversationId),t.type==="DEBUG")throw t;return t}}};export{o as CONVERSATION_ID,l as Client,m as SESSION_ID,_ as TTL,u as USER_ID,p as deleteConversationId,c as getConversationId,g as getSessionId,v as getUserId,I as setConversationId,f as setSessionId,y as setUserId};
1
+ import x from"openapi-fetch";var o="__15gifts_conversation_id",p=()=>sessionStorage.removeItem(o),c=()=>sessionStorage.getItem(o),I=n=>sessionStorage.setItem(o,n);var m="__15gifts_session_id",u=()=>sessionStorage.getItem(m),g=n=>sessionStorage.setItem(m,n);var S=n=>{let s=localStorage.getItem(n);if(!s)return null;let e=JSON.parse(s);return Date.now()>e.expires?(localStorage.removeItem(n),null):e.value},r=S;var E=(n,s,e)=>{let i={expires:Date.now()+e,value:s};localStorage.setItem(n,JSON.stringify(i))},d=E;var f="__15gifts_user_id",C=1e3*60*60*24*30,v=()=>r(f),y=n=>d(f,n,C);var h="0.3.1";var l=class{endpoint;identity;constructor({customerId:s,fetch:e,conversationUrl:i,frontendUrl:t}){let a={"X-SDK-VERSION":h};this.endpoint={conversation:x({baseUrl:i,fetch:e,headers:a}),frontend:x({baseUrl:t,fetch:e,headers:a})},this.identity={customerId:s,conversationId:c(),sessionId:u()??"",userId:v()}}async createIdentity(){let{conversationId:s,sessionId:e,userId:i}=this.identity;if(s&&this.endConversation(),!e||!i){let{data:t}=await this.endpoint.frontend.POST("/api/tracking/identity/v1",{body:{createSessionId:!e,createUserId:!i,customerId:this.identity.customerId}});t&&(!e&&t.sessionId&&(this.identity.sessionId=t.sessionId,g(t.sessionId)),!i&&t.userId&&(this.identity.userId=t.userId,y(t.userId)))}}endConversation(){p()}async sendMessage({openingMessage:s,userMessage:e}){s&&this.identity.conversationId&&this.endConversation();let{data:i}=await this.endpoint.conversation.POST("/api/conversation/v2",{body:{conversationId:this.identity.conversationId,customerId:this.identity.customerId,openingMessage:s,sessionId:this.identity.sessionId,userId:this.identity.userId,userMessage:e}});if(!i)return;let[t]=i;if(t?.conversationId&&I(t.conversationId),t?.type==="DEBUG")throw t;return i}async trackEvent(s,e){let i={additionalProperties:e,conversationId:this.identity.conversationId||void 0,customerId:this.identity.customerId,deviceType:void 0,eventName:s,sessionId:this.identity.sessionId,url:window.location.href,userAgent:window.navigator.userAgent,userId:this.identity.userId||void 0};return this.endpoint.frontend.POST("/api/tracking/user/v1",{body:i})}};export{o as CONVERSATION_ID,l as Client,m as SESSION_ID,C as TTL,f as USER_ID,p as deleteConversationId,c as getConversationId,u as getSessionId,v as getUserId,I as setConversationId,g as setSessionId,y 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","../package.json"],"sourcesContent":["import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, DebugResponse, Endpoint, Identity, Message } 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-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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to a message or a debug record.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessage = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n setConversationId(data.conversationId)\n if (data.type === 'DEBUG') {\n throw data as DebugResponse\n }\n\n return data\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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","const 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'\n\n/**\n * The key used to store the user ID in `localStorage`.\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 */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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 \"name\": \"@15gifts/sdk\",\n \"version\": \"0.2.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\": \"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 \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \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AAQ,CAAC,EAC1F,SAAUE,EAA4B,CAAE,QAASH,EAAa,MAAAF,EAAO,QAAAG,CAAQ,CAAC,CAChF,EACA,KAAK,SAAW,CACd,WAAAJ,EACA,eAAgBO,EAAkB,EAClC,UAAWC,EAAa,GAAK,GAC7B,OAAQC,EAAU,CACpB,CACF,CAaA,MAAM,gBAAgC,CACpC,GAAM,CAAE,eAAAC,EAAgB,UAAAC,EAAW,OAAAC,CAAO,EAAI,KAAK,SAInD,GAFIF,GAAgB,KAAK,gBAAgB,EAErC,CAACC,GAAa,CAACC,EAAQ,CACzB,GAAM,CAAE,KAAAC,CAAK,EAAI,MAAM,KAAK,SAAS,SAAS,KAAK,4BAA6B,CAC9E,KAAM,CACJ,gBAAiB,CAACF,EAClB,aAAc,CAACC,EACf,WAAY,KAAK,SAAS,UAC5B,CACF,CAAC,EAEGC,IACE,CAACF,GAAaE,EAAK,YACrB,KAAK,SAAS,UAAYA,EAAK,UAC/BC,EAAaD,EAAK,SAAS,GAEzB,CAACD,GAAUC,EAAK,SAClB,KAAK,SAAS,OAASA,EAAK,OAC5BE,EAAUF,EAAK,MAAM,GAG3B,CACF,CAWA,iBAAwB,CACtBG,EAAqB,CACvB,CAuBA,MAAM,YAAY,CAChB,eAAAC,EACA,YAAAC,CACF,EAGiC,CAC3BD,GAAkB,KAAK,SAAS,gBAClC,KAAK,gBAAgB,EAGvB,GAAM,CAAE,KAAAJ,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAI,EACA,UAAW,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAKL,EAGL,IADAM,EAAkBN,EAAK,cAAc,EACjCA,EAAK,OAAS,QAChB,MAAMA,EAGR,OAAOA,EACT,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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","setConversationId"]}
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","../package.json"],"sourcesContent":["import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, Endpoint, Identity, Message, 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-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/v2')\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({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId(),\n sessionId: getSessionId() ?? '',\n userId: getUserId(),\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist.\n *\n * @returns A promise that resolves once the identity is created.\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 { conversationId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n if (!sessionId || !userId) {\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v1', {\n body: {\n createSessionId: !sessionId,\n createUserId: !userId,\n customerId: this.identity.customerId,\n },\n })\n\n if (data) {\n if (!sessionId && data.sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId && data.userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n }\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 }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\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 openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId,\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n const [firstMessage] = data\n\n if (firstMessage?.conversationId) {\n setConversationId(firstMessage.conversationId)\n }\n\n if (firstMessage?.type === 'DEBUG') {\n throw firstMessage\n }\n\n // Based on the above check, we assume that the data is an array of messages and not debug records\n return data as Message[]\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('tab-shown')\n * ```\n */\n async trackEvent(\n eventName: TrackingEvent['eventName'],\n properties?: TrackingEvent['additionalProperties'],\n ): Promise<{ data?: undefined; error?: undefined; response: Response }> {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId || undefined,\n customerId: this.identity.customerId,\n deviceType: undefined,\n eventName,\n sessionId: this.identity.sessionId,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n userId: this.identity.userId || undefined,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v1', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\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 */\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","const 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'\n\n/**\n * The key used to store the user ID in `localStorage`.\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 */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\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 = () => getItemWithExpiry(USER_ID)\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 \"name\": \"@15gifts/sdk\",\n \"version\": \"0.3.1\",\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\": \"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 \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.0\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.0\",\n \"tsup\": \"^8.2.4\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCGlB,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,EClC/F,IAAMC,EAAqBC,GAAgB,CACzC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CAC9E,KAAM,CACJ,gBAAiB,CAACF,EAClB,aAAc,CAACC,EACf,WAAY,KAAK,SAAS,UAC5B,CACF,CAAC,EAEGC,IACE,CAACF,GAAaE,EAAK,YACrB,KAAK,SAAS,UAAYA,EAAK,UAC/BC,EAAaD,EAAK,SAAS,GAEzB,CAACD,GAAUC,EAAK,SAClB,KAAK,SAAS,OAASA,EAAK,OAC5BE,EAAUF,EAAK,MAAM,GAG3B,CACF,CAWA,iBAAwB,CACtBG,EAAqB,CACvB,CAuBA,MAAM,YAAY,CAChB,eAAAC,EACA,YAAAC,CACF,EAGmC,CAC7BD,GAAkB,KAAK,SAAS,gBAClC,KAAK,gBAAgB,EAGvB,GAAM,CAAE,KAAAJ,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAI,EACA,UAAW,KAAK,SAAS,UACzB,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAI,CAACL,EAAM,OAEX,GAAM,CAACM,CAAY,EAAIN,EAMvB,GAJIM,GAAc,gBAChBC,EAAkBD,EAAa,cAAc,EAG3CA,GAAc,OAAS,QACzB,MAAMA,EAIR,OAAON,CACT,CAcA,MAAM,WACJQ,EACAC,EACsE,CACtE,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,gBAAkB,OAChD,WAAY,KAAK,SAAS,WAC1B,WAAY,OACZ,UAAAD,EACA,UAAW,KAAK,SAAS,UACzB,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,UAC5B,OAAQ,KAAK,SAAS,QAAU,MAClC,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,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","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","deleteConversationId","openingMessage","userMessage","firstMessage","setConversationId","eventName","properties","body"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "files": [
5
5
  "dist"
6
6
  ],