@15gifts/sdk 0.4.3 → 0.5.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
@@ -1567,17 +1567,16 @@ interface paths {
1567
1567
  * These are the types as defined in the OpenAPI schema.
1568
1568
  * We don't use them directly, or export them here because of how they appear in the documentation site.
1569
1569
  */
1570
- type ApiConversationRequest = components['schemas']['app__conversation__models__input__MessageRequest'];
1571
- type ApiConversationResponse = operations['generate_conversation_json_response_api_conversation_v2_post']['responses']['200']['content']['application/json'];
1572
- type ApiDebug = components['schemas']['DebugChunk'];
1573
1570
  type ApiBasicMessage = components['schemas']['MessageChunk'];
1574
- type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
1575
- type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
1571
+ type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
1572
+ type ApiDebugMessage = components['schemas']['DebugChunk'];
1576
1573
  type ApiExitToChatMessage = components['schemas']['ExitToChatChunk'];
1577
1574
  type ApiExitToPurchaseMessage = components['schemas']['ExitToPurchaseChunk'];
1578
- type ApiRecomendationMessage = components['schemas']['RecommendationChunk'];
1579
- type ApiTrackingUserRequest = paths['/api/tracking/user/v2']['post']['requestBody']['content']['application/json'];
1575
+ type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
1576
+ type ApiRecommendationMessage = components['schemas']['RecommendationChunk'];
1577
+ type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
1580
1578
  type ApiIdentityRequest = paths['/api/tracking/identity/v2']['post']['requestBody']['content']['application/json'];
1579
+ type ApiTrackingUserRequest = paths['/api/tracking/user/v2']['post']['requestBody']['content']['application/json'];
1581
1580
  /**
1582
1581
  * Configuration options for initializing the client.
1583
1582
  */
@@ -1634,22 +1633,26 @@ interface Identity {
1634
1633
  */
1635
1634
  userId?: string;
1636
1635
  }
1637
- interface DebugResponse extends ApiDebug {
1638
- }
1639
1636
  /**
1640
1637
  * The message types that the SDK returns.
1641
1638
  * Note that the API response may contain additional types that the SDK does not return.
1642
1639
  */
1643
- type Message = ApiBasicMessage | ApiMultiSelectMessage | ApiSingleSelectMessage | ApiExitToChatMessage | ApiExitToPurchaseMessage | ApiRecomendationMessage;
1644
- /**
1645
- * The request to the conversation API.
1646
- */
1647
- interface ConversationApiRequest extends ApiConversationRequest {
1640
+ type Message = BasicMessage | ConversationIdMessage | DebugMessage | ExitToChatMessage | ExitToPurchaseMessage | MultiSelectMessage | RecommendationMessage | SingleSelectMessage;
1641
+ interface BasicMessage extends ApiBasicMessage {
1648
1642
  }
1649
- /**
1650
- * The response from the conversation API.
1651
- */
1652
- interface ConversationApiResponse extends ApiConversationResponse {
1643
+ interface ConversationIdMessage extends ApiConversationIdMessage {
1644
+ }
1645
+ interface DebugMessage extends ApiDebugMessage {
1646
+ }
1647
+ interface ExitToChatMessage extends ApiExitToChatMessage {
1648
+ }
1649
+ interface ExitToPurchaseMessage extends ApiExitToPurchaseMessage {
1650
+ }
1651
+ interface MultiSelectMessage extends ApiMultiSelectMessage {
1652
+ }
1653
+ interface RecommendationMessage extends ApiRecommendationMessage {
1654
+ }
1655
+ interface SingleSelectMessage extends ApiSingleSelectMessage {
1653
1656
  }
1654
1657
  interface TrackingEvent extends ApiTrackingUserRequest {
1655
1658
  }
@@ -1659,7 +1662,7 @@ interface TrackingEvent extends ApiTrackingUserRequest {
1659
1662
  */
1660
1663
  declare class Client {
1661
1664
  /**
1662
- * 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.
1665
+ * 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.
1663
1666
  *
1664
1667
  * @example
1665
1668
  * ```ts
@@ -1707,7 +1710,19 @@ declare class Client {
1707
1710
  */
1708
1711
  endConversation(): void;
1709
1712
  /**
1710
- * Sends a message in the conversation
1713
+ * Clears the existing conversation ID, then generates a new one and returns the opening message.
1714
+ *
1715
+ * @returns A promise that resolves to the opening message.
1716
+ *
1717
+ * @example
1718
+ * ```ts
1719
+ * const openingMessage = await client.startConversation()
1720
+ * console.log('Opening message:', openingMessage)
1721
+ * ```
1722
+ */
1723
+ startConversation(): Promise<BasicMessage | undefined>;
1724
+ /**
1725
+ * Sends a message in the conversation.
1711
1726
  *
1712
1727
  * @param options - An object containing the user message.
1713
1728
  * @returns A promise that resolves to an array of messages or debug records.
@@ -1727,8 +1742,8 @@ declare class Client {
1727
1742
  * ```
1728
1743
  */
1729
1744
  sendMessage({ userMessage, }: {
1730
- userMessage: ConversationApiRequest['userMessage'];
1731
- }): Promise<Message[] | undefined>;
1745
+ userMessage: string;
1746
+ }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined>;
1732
1747
  /**
1733
1748
  * Sends an event to the tracking API, with the required properties already set.
1734
1749
  *
@@ -1923,4 +1938,4 @@ declare const setUserId: (userId: string) => void;
1923
1938
  */
1924
1939
  declare const authMiddleware: (accessToken: string) => Middleware;
1925
1940
 
1926
- export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type ConversationApiResponse, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
1941
+ export { type BasicMessage, CONVERSATION_ID, Client, type Config, type ConversationIdMessage, type DebugMessage, type Endpoint, type ExitToChatMessage, type ExitToPurchaseMessage, type Identity, type Message, type MultiSelectMessage, type RecommendationMessage, SESSION_ID, type SingleSelectMessage, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
package/dist/index.d.ts CHANGED
@@ -1567,17 +1567,16 @@ interface paths {
1567
1567
  * These are the types as defined in the OpenAPI schema.
1568
1568
  * We don't use them directly, or export them here because of how they appear in the documentation site.
1569
1569
  */
1570
- type ApiConversationRequest = components['schemas']['app__conversation__models__input__MessageRequest'];
1571
- type ApiConversationResponse = operations['generate_conversation_json_response_api_conversation_v2_post']['responses']['200']['content']['application/json'];
1572
- type ApiDebug = components['schemas']['DebugChunk'];
1573
1570
  type ApiBasicMessage = components['schemas']['MessageChunk'];
1574
- type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
1575
- type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
1571
+ type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
1572
+ type ApiDebugMessage = components['schemas']['DebugChunk'];
1576
1573
  type ApiExitToChatMessage = components['schemas']['ExitToChatChunk'];
1577
1574
  type ApiExitToPurchaseMessage = components['schemas']['ExitToPurchaseChunk'];
1578
- type ApiRecomendationMessage = components['schemas']['RecommendationChunk'];
1579
- type ApiTrackingUserRequest = paths['/api/tracking/user/v2']['post']['requestBody']['content']['application/json'];
1575
+ type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
1576
+ type ApiRecommendationMessage = components['schemas']['RecommendationChunk'];
1577
+ type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
1580
1578
  type ApiIdentityRequest = paths['/api/tracking/identity/v2']['post']['requestBody']['content']['application/json'];
1579
+ type ApiTrackingUserRequest = paths['/api/tracking/user/v2']['post']['requestBody']['content']['application/json'];
1581
1580
  /**
1582
1581
  * Configuration options for initializing the client.
1583
1582
  */
@@ -1634,22 +1633,26 @@ interface Identity {
1634
1633
  */
1635
1634
  userId?: string;
1636
1635
  }
1637
- interface DebugResponse extends ApiDebug {
1638
- }
1639
1636
  /**
1640
1637
  * The message types that the SDK returns.
1641
1638
  * Note that the API response may contain additional types that the SDK does not return.
1642
1639
  */
1643
- type Message = ApiBasicMessage | ApiMultiSelectMessage | ApiSingleSelectMessage | ApiExitToChatMessage | ApiExitToPurchaseMessage | ApiRecomendationMessage;
1644
- /**
1645
- * The request to the conversation API.
1646
- */
1647
- interface ConversationApiRequest extends ApiConversationRequest {
1640
+ type Message = BasicMessage | ConversationIdMessage | DebugMessage | ExitToChatMessage | ExitToPurchaseMessage | MultiSelectMessage | RecommendationMessage | SingleSelectMessage;
1641
+ interface BasicMessage extends ApiBasicMessage {
1648
1642
  }
1649
- /**
1650
- * The response from the conversation API.
1651
- */
1652
- interface ConversationApiResponse extends ApiConversationResponse {
1643
+ interface ConversationIdMessage extends ApiConversationIdMessage {
1644
+ }
1645
+ interface DebugMessage extends ApiDebugMessage {
1646
+ }
1647
+ interface ExitToChatMessage extends ApiExitToChatMessage {
1648
+ }
1649
+ interface ExitToPurchaseMessage extends ApiExitToPurchaseMessage {
1650
+ }
1651
+ interface MultiSelectMessage extends ApiMultiSelectMessage {
1652
+ }
1653
+ interface RecommendationMessage extends ApiRecommendationMessage {
1654
+ }
1655
+ interface SingleSelectMessage extends ApiSingleSelectMessage {
1653
1656
  }
1654
1657
  interface TrackingEvent extends ApiTrackingUserRequest {
1655
1658
  }
@@ -1659,7 +1662,7 @@ interface TrackingEvent extends ApiTrackingUserRequest {
1659
1662
  */
1660
1663
  declare class Client {
1661
1664
  /**
1662
- * 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.
1665
+ * 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.
1663
1666
  *
1664
1667
  * @example
1665
1668
  * ```ts
@@ -1707,7 +1710,19 @@ declare class Client {
1707
1710
  */
1708
1711
  endConversation(): void;
1709
1712
  /**
1710
- * Sends a message in the conversation
1713
+ * Clears the existing conversation ID, then generates a new one and returns the opening message.
1714
+ *
1715
+ * @returns A promise that resolves to the opening message.
1716
+ *
1717
+ * @example
1718
+ * ```ts
1719
+ * const openingMessage = await client.startConversation()
1720
+ * console.log('Opening message:', openingMessage)
1721
+ * ```
1722
+ */
1723
+ startConversation(): Promise<BasicMessage | undefined>;
1724
+ /**
1725
+ * Sends a message in the conversation.
1711
1726
  *
1712
1727
  * @param options - An object containing the user message.
1713
1728
  * @returns A promise that resolves to an array of messages or debug records.
@@ -1727,8 +1742,8 @@ declare class Client {
1727
1742
  * ```
1728
1743
  */
1729
1744
  sendMessage({ userMessage, }: {
1730
- userMessage: ConversationApiRequest['userMessage'];
1731
- }): Promise<Message[] | undefined>;
1745
+ userMessage: string;
1746
+ }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined>;
1732
1747
  /**
1733
1748
  * Sends an event to the tracking API, with the required properties already set.
1734
1749
  *
@@ -1923,4 +1938,4 @@ declare const setUserId: (userId: string) => void;
1923
1938
  */
1924
1939
  declare const authMiddleware: (accessToken: string) => Middleware;
1925
1940
 
1926
- export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type ConversationApiResponse, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
1941
+ export { type BasicMessage, CONVERSATION_ID, Client, type Config, type ConversationIdMessage, type DebugMessage, type Endpoint, type ExitToChatMessage, type ExitToPurchaseMessage, type Identity, type Message, type MultiSelectMessage, type RecommendationMessage, SESSION_ID, type SingleSelectMessage, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var O=Object.create;var d=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var b=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var N=(e,t)=>{for(var s in t)d(e,s,{get:t[s],enumerable:!0})},w=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of T(t))!D.call(e,n)&&n!==s&&d(e,n,{get:()=>t[n],enumerable:!(i=M(t,n))||i.enumerable});return e};var P=(e,t,s)=>(s=e!=null?O(b(e)):{},w(t||!e||!e.__esModule?d(s,"default",{value:e,enumerable:!0}):s,e)),k=e=>w(d({},"__esModule",{value:!0}),e);var V={};N(V,{CONVERSATION_ID:()=>a,Client:()=>E,SESSION_ID:()=>g,TTL:()=>_,USER_ID:()=>h,authMiddleware:()=>p,deleteConversationId:()=>c,getConversationId:()=>f,getSessionId:()=>m,getUserId:()=>l,setConversationId:()=>I,setSessionId:()=>u,setUserId:()=>x});module.exports=k(V);var S=P(require("openapi-fetch"));var a="__15gifts_conversation_id",c=()=>sessionStorage.removeItem(a),f=()=>sessionStorage.getItem(a),I=e=>sessionStorage.setItem(a,e);var g="__15gifts_session_id",m=()=>sessionStorage.getItem(g),u=e=>sessionStorage.setItem(g,e);var A=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},v=A;var U=(e,t,s)=>{let i={expires:Date.now()+s,value:t};localStorage.setItem(e,JSON.stringify(i))},y=U;var h="__15gifts_user_id",_=1e3*60*60*24*30,l=()=>v(h),x=e=>y(h,e,_);var R=e=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${e}`),t)}),p=R;var C="0.4.3";var E=class{endpoint;identity;constructor({customerId:t,fetch:s,conversationUrl:i,frontendUrl:n}){let o={"X-SDK-VERSION":C};this.endpoint={conversation:(0,S.default)({baseUrl:i,fetch:s,headers:o}),frontend:(0,S.default)({baseUrl:n,fetch:s,headers:o})},this.identity={customerId:t,conversationId:f()??void 0,sessionId:m()??void 0,userId:l()??void 0}}async createIdentity(){let{conversationId:t,customerId:s,sessionId:i,userId:n}=this.identity;t&&this.endConversation();let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:s,sessionId:i,userId:n}});o&&(i||(this.identity.sessionId=o.sessionId,u(o.sessionId)),n||(this.identity.userId=o.userId,x(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(p(o.token))}))}endConversation(){c(),this.identity.conversationId=void 0}async sendMessage({userMessage:t}){let{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!s)return;if(s.find(r=>r.type==="DEBUG"))throw new Error("Debug record received");let n=s.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return n&&(I(n),this.identity.conversationId=n),s.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(t,s){let i={additionalProperties:s,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,setUserId});
1
+ "use strict";var _=Object.create;var a=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var b=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var s in e)a(t,s,{get:e[s],enumerable:!0})},M=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of T(e))!D.call(t,n)&&n!==s&&a(t,n,{get:()=>e[n],enumerable:!(i=O(e,n))||i.enumerable});return t};var N=(t,e,s)=>(s=t!=null?_(b(t)):{},M(e||!t||!t.__esModule?a(s,"default",{value:t,enumerable:!0}):s,t)),k=t=>M(a({},"__esModule",{value:!0}),t);var W={};P(W,{CONVERSATION_ID:()=>d,Client:()=>E,SESSION_ID:()=>v,TTL:()=>C,USER_ID:()=>h,authMiddleware:()=>p,deleteConversationId:()=>g,getConversationId:()=>I,getSessionId:()=>f,getUserId:()=>l,setConversationId:()=>c,setSessionId:()=>u,setUserId:()=>x});module.exports=k(W);var S=N(require("openapi-fetch"));var d="__15gifts_conversation_id",g=()=>sessionStorage.removeItem(d),I=()=>sessionStorage.getItem(d),c=t=>sessionStorage.setItem(d,t);var v="__15gifts_session_id",f=()=>sessionStorage.getItem(v),u=t=>sessionStorage.setItem(v,t);var A=t=>{let e=localStorage.getItem(t);if(!e)return null;let s=JSON.parse(e);return Date.now()>s.expires?(localStorage.removeItem(t),null):s.value},m=A;var U=(t,e,s)=>{let i={expires:Date.now()+s,value:e};localStorage.setItem(t,JSON.stringify(i))},y=U;var h="__15gifts_user_id",C=1e3*60*60*24*30,l=()=>m(h),x=t=>y(h,t,C);var R=t=>({onRequest:async({request:e})=>(e.headers.set("Authorization",`Bearer ${t}`),e)}),p=R;var w="0.5.1";var E=class{endpoint;identity;constructor({customerId:e,fetch:s,conversationUrl:i,frontendUrl:n}){let o={"X-SDK-VERSION":w};this.endpoint={conversation:(0,S.default)({baseUrl:i,fetch:s,headers:o}),frontend:(0,S.default)({baseUrl:n,fetch:s,headers:o})},this.identity={customerId:e,conversationId:I()??void 0,sessionId:f()??void 0,userId:l()??void 0}}async createIdentity(){let{conversationId:e,customerId:s,sessionId:i,userId:n}=this.identity;e&&this.endConversation();let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:s,sessionId:i,userId:n}});o&&(i||(this.identity.sessionId=o.sessionId,u(o.sessionId)),n||(this.identity.userId=o.userId,x(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(p(o.token))}))}endConversation(){g(),this.identity.conversationId=void 0}async startConversation(){this.endConversation();let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:{availableProductIds:[]}}}),[s,i]=e,n=s.conversationId;if(!n)throw new Error("Conversation ID not received");return c(n),this.identity.conversationId=n,i}async sendMessage({userMessage:e}){let{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:e,type:"MESSAGE"}});if(!s)return;if(s.find(r=>r.type==="DEBUG"))throw new Error("Debug record received");let n=s.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return n&&(c(n),this.identity.conversationId=n),s.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(e,s){let i={additionalProperties:s,conversationId:this.identity.conversationId,deviceType:void 0,eventName:e,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,authMiddleware,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","../src/middlewares/auth.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\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 { authMiddleware } from './middlewares'\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() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\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, 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 *\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 { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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 this.identity.conversationId = undefined\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 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 * 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: ConversationApiRequest['userMessage']\n }): Promise<Message[] | 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 const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\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' && message.type !== 'DEBUG')\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('tab-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 deviceType: undefined,\n eventName,\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 * 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","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 *\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 = 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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.4.3\",\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.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"t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,CAAE,KAAAN,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,YAAAM,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACN,EAAM,OAGX,GADqBA,EAAK,KAAMO,GAAYA,EAAQ,OAAS,OAAO,EAElE,MAAM,IAAI,MAAM,uBAAuB,EAIzC,IAAMV,EAAiBG,EAAK,KAAMO,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIV,IACFW,EAAkBX,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBG,EAAK,OAAQO,GAAYA,EAAQ,OAAS,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWE,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,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","auth_default","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","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","userMessage","message","setConversationId","eventName","properties","body"]}
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/middlewares/auth.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\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 { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n BasicMessage,\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} 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/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() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\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, 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 *\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 { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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 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 * @returns A promise that resolves to the opening message.\n *\n * @example\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(): Promise<BasicMessage | undefined> {\n this.endConversation()\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext: {\n availableProductIds: [],\n },\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, BasicMessage]\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 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 * 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 | DebugMessage>[] | 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 const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\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' && message.type !== 'DEBUG')\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('tab-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 deviceType: undefined,\n eventName,\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 * 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","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 *\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 = 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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.5.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.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\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,mBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAf,GCAA,IAAAgB,EAAyB,4BCKlB,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,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,E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A,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","auth_default","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","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","conversationIdMessage","openingMessage","setConversationId","userMessage","message","eventName","properties","body"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import S from"openapi-fetch";var d="__15gifts_conversation_id",f=()=>sessionStorage.removeItem(d),I=()=>sessionStorage.getItem(d),g=s=>sessionStorage.setItem(d,s);var m="__15gifts_session_id",u=()=>sessionStorage.getItem(m),v=s=>sessionStorage.setItem(m,s);var w=s=>{let t=localStorage.getItem(s);if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expires?(localStorage.removeItem(s),null):e.value},a=w;var _=(s,t,e)=>{let i={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(i))},p=_;var y="__15gifts_user_id",C=1e3*60*60*24*30,h=()=>a(y),l=s=>p(y,s,C);var O=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),c=O;var x="0.4.3";var E=class{endpoint;identity;constructor({customerId:t,fetch:e,conversationUrl:i,frontendUrl:o}){let n={"X-SDK-VERSION":x};this.endpoint={conversation:S({baseUrl:i,fetch:e,headers:n}),frontend:S({baseUrl:o,fetch:e,headers:n})},this.identity={customerId:t,conversationId:I()??void 0,sessionId:u()??void 0,userId:h()??void 0}}async createIdentity(){let{conversationId:t,customerId:e,sessionId:i,userId:o}=this.identity;t&&this.endConversation();let{data:n}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:e,sessionId:i,userId:o}});n&&(i||(this.identity.sessionId=n.sessionId,v(n.sessionId)),o||(this.identity.userId=n.userId,l(n.userId)),Object.values(this.endpoint).forEach(r=>{r.use(c(n.token))}))}endConversation(){f(),this.identity.conversationId=void 0}async sendMessage({userMessage:t}){let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!e)return;if(e.find(r=>r.type==="DEBUG"))throw new Error("Debug record received");let o=e.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return o&&(g(o),this.identity.conversationId=o),e.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(t,e){let i={additionalProperties:e,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}};export{d as CONVERSATION_ID,E as Client,m as SESSION_ID,C as TTL,y as USER_ID,c as authMiddleware,f as deleteConversationId,I as getConversationId,u as getSessionId,h as getUserId,g as setConversationId,v as setSessionId,l as setUserId};
1
+ import S from"openapi-fetch";var a="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(a),v=()=>sessionStorage.getItem(a),d=s=>sessionStorage.setItem(a,s);var f="__15gifts_session_id",u=()=>sessionStorage.getItem(f),m=s=>sessionStorage.setItem(f,s);var M=s=>{let t=localStorage.getItem(s);if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expires?(localStorage.removeItem(s),null):e.value},c=M;var C=(s,t,e)=>{let i={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(i))},p=C;var y="__15gifts_user_id",w=1e3*60*60*24*30,h=()=>c(y),l=s=>p(y,s,w);var _=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),g=_;var x="0.5.1";var E=class{endpoint;identity;constructor({customerId:t,fetch:e,conversationUrl:i,frontendUrl:n}){let o={"X-SDK-VERSION":x};this.endpoint={conversation:S({baseUrl:i,fetch:e,headers:o}),frontend:S({baseUrl:n,fetch:e,headers:o})},this.identity={customerId:t,conversationId:v()??void 0,sessionId:u()??void 0,userId:h()??void 0}}async createIdentity(){let{conversationId:t,customerId:e,sessionId:i,userId:n}=this.identity;t&&this.endConversation();let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:e,sessionId:i,userId:n}});o&&(i||(this.identity.sessionId=o.sessionId,m(o.sessionId)),n||(this.identity.userId=o.userId,l(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(g(o.token))}))}endConversation(){I(),this.identity.conversationId=void 0}async startConversation(){this.endConversation();let{data:t}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:{availableProductIds:[]}}}),[e,i]=t,n=e.conversationId;if(!n)throw new Error("Conversation ID not received");return d(n),this.identity.conversationId=n,i}async sendMessage({userMessage:t}){let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!e)return;if(e.find(r=>r.type==="DEBUG"))throw new Error("Debug record received");let n=e.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return n&&(d(n),this.identity.conversationId=n),e.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(t,e){let i={additionalProperties:e,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}};export{a as CONVERSATION_ID,E as Client,f as SESSION_ID,w as TTL,y as USER_ID,g as authMiddleware,I as deleteConversationId,v as getConversationId,u as getSessionId,h as getUserId,d as setConversationId,m as setSessionId,l 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/middlewares/auth.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 { authMiddleware } from './middlewares'\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() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\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, 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 *\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 { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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 this.identity.conversationId = undefined\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 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 * 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: ConversationApiRequest['userMessage']\n }): Promise<Message[] | 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 const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\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' && message.type !== 'DEBUG')\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('tab-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 deviceType: undefined,\n eventName,\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 * 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","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 *\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 = 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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.4.3\",\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.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCKlB,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,u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AsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,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","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","userMessage","message","setConversationId","eventName","properties","body"]}
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/middlewares/auth.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 { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n BasicMessage,\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} 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/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() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\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, 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 *\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 { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\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 Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\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 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 * @returns A promise that resolves to the opening message.\n *\n * @example\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(): Promise<BasicMessage | undefined> {\n this.endConversation()\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext: {\n availableProductIds: [],\n },\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, BasicMessage]\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 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 * 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 | DebugMessage>[] | 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 const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\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' && message.type !== 'DEBUG')\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('tab-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 deviceType: undefined,\n eventName,\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 * 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","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 *\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 = 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","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 request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.5.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.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCKlB,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,MAA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S,eAAiBA,GAGhBG,EAAK,OAAQU,GAAYA,EAAQ,OAAS,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,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","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","conversationIdMessage","openingMessage","setConversationId","userMessage","message","eventName","properties","body"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "files": [
5
5
  "dist"
6
6
  ],