@15gifts/sdk 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1567,18 +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
- type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
1574
1570
  type ApiBasicMessage = components['schemas']['MessageChunk'];
1575
- type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
1576
- type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
1571
+ type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
1572
+ type ApiDebugMessage = components['schemas']['DebugChunk'];
1577
1573
  type ApiExitToChatMessage = components['schemas']['ExitToChatChunk'];
1578
1574
  type ApiExitToPurchaseMessage = components['schemas']['ExitToPurchaseChunk'];
1579
- type ApiRecomendationMessage = components['schemas']['RecommendationChunk'];
1580
- 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'];
1581
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'];
1582
1580
  /**
1583
1581
  * Configuration options for initializing the client.
1584
1582
  */
@@ -1635,22 +1633,26 @@ interface Identity {
1635
1633
  */
1636
1634
  userId?: string;
1637
1635
  }
1638
- interface DebugResponse extends ApiDebug {
1639
- }
1640
1636
  /**
1641
1637
  * The message types that the SDK returns.
1642
1638
  * Note that the API response may contain additional types that the SDK does not return.
1643
1639
  */
1644
- type Message = ApiBasicMessage | ApiMultiSelectMessage | ApiSingleSelectMessage | ApiExitToChatMessage | ApiExitToPurchaseMessage | ApiRecomendationMessage;
1645
- /**
1646
- * The request to the conversation API.
1647
- */
1648
- interface ConversationApiRequest extends ApiConversationRequest {
1640
+ type Message = BasicMessage | ConversationIdMessage | DebugMessage | ExitToChatMessage | ExitToPurchaseMessage | MultiSelectMessage | RecommendationMessage | SingleSelectMessage;
1641
+ interface BasicMessage extends ApiBasicMessage {
1649
1642
  }
1650
- /**
1651
- * The response from the conversation API.
1652
- */
1653
- 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 {
1654
1656
  }
1655
1657
  interface TrackingEvent extends ApiTrackingUserRequest {
1656
1658
  }
@@ -1660,7 +1662,7 @@ interface TrackingEvent extends ApiTrackingUserRequest {
1660
1662
  */
1661
1663
  declare class Client {
1662
1664
  /**
1663
- * 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.
1664
1666
  *
1665
1667
  * @example
1666
1668
  * ```ts
@@ -1709,14 +1711,21 @@ declare class Client {
1709
1711
  endConversation(): void;
1710
1712
  /**
1711
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
+ * ```
1712
1722
  */
1713
- startConversation(): Promise<ApiBasicMessage | undefined>;
1723
+ startConversation(): Promise<BasicMessage | undefined>;
1714
1724
  /**
1715
- * Sends a message in the conversation
1725
+ * Sends a message in the conversation.
1716
1726
  *
1717
1727
  * @param options - An object containing the user message.
1718
- * @returns A promise that resolves to an array of messages or debug records.
1719
- * If the message is a debug record, it will throw an error.
1728
+ * @returns A promise that resolves to an array of messages
1720
1729
  *
1721
1730
  * @example
1722
1731
  * ```ts
@@ -1732,8 +1741,8 @@ declare class Client {
1732
1741
  * ```
1733
1742
  */
1734
1743
  sendMessage({ userMessage, }: {
1735
- userMessage: ConversationApiRequest['userMessage'];
1736
- }): Promise<Message[] | undefined>;
1744
+ userMessage: string;
1745
+ }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined>;
1737
1746
  /**
1738
1747
  * Sends an event to the tracking API, with the required properties already set.
1739
1748
  *
@@ -1928,4 +1937,4 @@ declare const setUserId: (userId: string) => void;
1928
1937
  */
1929
1938
  declare const authMiddleware: (accessToken: string) => Middleware;
1930
1939
 
1931
- export { type ApiBasicMessage, type ApiConversationIdMessage, 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 };
1940
+ 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,18 +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
- type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
1574
1570
  type ApiBasicMessage = components['schemas']['MessageChunk'];
1575
- type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
1576
- type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
1571
+ type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
1572
+ type ApiDebugMessage = components['schemas']['DebugChunk'];
1577
1573
  type ApiExitToChatMessage = components['schemas']['ExitToChatChunk'];
1578
1574
  type ApiExitToPurchaseMessage = components['schemas']['ExitToPurchaseChunk'];
1579
- type ApiRecomendationMessage = components['schemas']['RecommendationChunk'];
1580
- 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'];
1581
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'];
1582
1580
  /**
1583
1581
  * Configuration options for initializing the client.
1584
1582
  */
@@ -1635,22 +1633,26 @@ interface Identity {
1635
1633
  */
1636
1634
  userId?: string;
1637
1635
  }
1638
- interface DebugResponse extends ApiDebug {
1639
- }
1640
1636
  /**
1641
1637
  * The message types that the SDK returns.
1642
1638
  * Note that the API response may contain additional types that the SDK does not return.
1643
1639
  */
1644
- type Message = ApiBasicMessage | ApiMultiSelectMessage | ApiSingleSelectMessage | ApiExitToChatMessage | ApiExitToPurchaseMessage | ApiRecomendationMessage;
1645
- /**
1646
- * The request to the conversation API.
1647
- */
1648
- interface ConversationApiRequest extends ApiConversationRequest {
1640
+ type Message = BasicMessage | ConversationIdMessage | DebugMessage | ExitToChatMessage | ExitToPurchaseMessage | MultiSelectMessage | RecommendationMessage | SingleSelectMessage;
1641
+ interface BasicMessage extends ApiBasicMessage {
1649
1642
  }
1650
- /**
1651
- * The response from the conversation API.
1652
- */
1653
- 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 {
1654
1656
  }
1655
1657
  interface TrackingEvent extends ApiTrackingUserRequest {
1656
1658
  }
@@ -1660,7 +1662,7 @@ interface TrackingEvent extends ApiTrackingUserRequest {
1660
1662
  */
1661
1663
  declare class Client {
1662
1664
  /**
1663
- * 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.
1664
1666
  *
1665
1667
  * @example
1666
1668
  * ```ts
@@ -1709,14 +1711,21 @@ declare class Client {
1709
1711
  endConversation(): void;
1710
1712
  /**
1711
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
+ * ```
1712
1722
  */
1713
- startConversation(): Promise<ApiBasicMessage | undefined>;
1723
+ startConversation(): Promise<BasicMessage | undefined>;
1714
1724
  /**
1715
- * Sends a message in the conversation
1725
+ * Sends a message in the conversation.
1716
1726
  *
1717
1727
  * @param options - An object containing the user message.
1718
- * @returns A promise that resolves to an array of messages or debug records.
1719
- * If the message is a debug record, it will throw an error.
1728
+ * @returns A promise that resolves to an array of messages
1720
1729
  *
1721
1730
  * @example
1722
1731
  * ```ts
@@ -1732,8 +1741,8 @@ declare class Client {
1732
1741
  * ```
1733
1742
  */
1734
1743
  sendMessage({ userMessage, }: {
1735
- userMessage: ConversationApiRequest['userMessage'];
1736
- }): Promise<Message[] | undefined>;
1744
+ userMessage: string;
1745
+ }): Promise<Exclude<Message, ConversationIdMessage | DebugMessage>[] | undefined>;
1737
1746
  /**
1738
1747
  * Sends an event to the tracking API, with the required properties already set.
1739
1748
  *
@@ -1928,4 +1937,4 @@ declare const setUserId: (userId: string) => void;
1928
1937
  */
1929
1938
  declare const authMiddleware: (accessToken: string) => Middleware;
1930
1939
 
1931
- export { type ApiBasicMessage, type ApiConversationIdMessage, 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 };
1940
+ 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 _=Object.create;var a=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var s in e)a(t,s,{get:e[s],enumerable:!0})},C=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of T(e))!b.call(t,n)&&n!==s&&a(t,n,{get:()=>e[n],enumerable:!(i=O(e,n))||i.enumerable});return t};var D=(t,e,s)=>(s=t!=null?_(A(t)):{},C(e||!t||!t.__esModule?a(s,"default",{value:t,enumerable:!0}):s,t)),N=t=>C(a({},"__esModule",{value:!0}),t);var W={};P(W,{CONVERSATION_ID:()=>d,Client:()=>E,SESSION_ID:()=>g,TTL:()=>w,USER_ID:()=>h,authMiddleware:()=>c,deleteConversationId:()=>I,getConversationId:()=>v,getSessionId:()=>f,getUserId:()=>l,setConversationId:()=>p,setSessionId:()=>u,setUserId:()=>x});module.exports=N(W);var S=D(require("openapi-fetch"));var d="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(d),v=()=>sessionStorage.getItem(d),p=t=>sessionStorage.setItem(d,t);var g="__15gifts_session_id",f=()=>sessionStorage.getItem(g),u=t=>sessionStorage.setItem(g,t);var R=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=R;var k=(t,e,s)=>{let i={expires:Date.now()+s,value:e};localStorage.setItem(t,JSON.stringify(i))},y=k;var h="__15gifts_user_id",w=1e3*60*60*24*30,l=()=>m(h),x=t=>y(h,t,w);var U=t=>({onRequest:async({request:e})=>(e.headers.set("Authorization",`Bearer ${t}`),e)}),c=U;var M="0.5.0";var E=class{endpoint;identity;constructor({customerId:e,fetch:s,conversationUrl:i,frontendUrl:n}){let o={"X-SDK-VERSION":M};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:v()??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(c(o.token))}))}endConversation(){I(),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 p(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&&(p(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});
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})},C=(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)):{},C(e||!t||!t.__esModule?a(s,"default",{value:t,enumerable:!0}):s,t)),k=t=>C(a({},"__esModule",{value:!0}),t);var W={};P(W,{CONVERSATION_ID:()=>d,Client:()=>E,SESSION_ID:()=>v,TTL:()=>M,USER_ID:()=>y,authMiddleware:()=>p,deleteConversationId:()=>g,getConversationId:()=>I,getSessionId:()=>f,getUserId:()=>h,setConversationId:()=>c,setSessionId:()=>m,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),m=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},u=A;var U=(t,e,s)=>{let i={expires:Date.now()+s,value:e};localStorage.setItem(t,JSON.stringify(i))},l=U;var y="__15gifts_user_id",M=1e3*60*60*24*30,h=()=>u(y),x=t=>l(y,t,M);var R=t=>({onRequest:async({request:e})=>(e.headers.set("Authorization",`Bearer ${t}`),e)}),p=R;var w="0.5.2";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:h()??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,m(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;let i=s.filter(r=>r.type==="DEBUG");i.length&&console.info("Debug messages:",i);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 {\n ApiBasicMessage,\n ApiConversationIdMessage,\n Config,\n ConversationApiRequest,\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-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 async startConversation(): Promise<ApiBasicMessage | 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 [ApiConversationIdMessage, ApiBasicMessage]\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: 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.5.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.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,cAA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A8B,EAGhD,OAAAW,EAAkBX,CAAc,EAChC,KAAK,SAAS,eAAiBA,EAExBU,CACT,CAsBA,MAAM,YAAY,CAChB,YAAAE,CACF,EAEmC,CACjC,GAAM,CAAE,KAAAT,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,YAAAS,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACT,EAAM,OAGX,GADqBA,EAAK,KAAMU,GAAYA,EAAQ,OAAS,OAAO,EAElE,MAAM,IAAI,MAAM,uBAAuB,EAIzC,IAAMb,EAAiBG,EAAK,KAAMU,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIb,IACFW,EAAkBX,CAAc,EAChC,KAAK,SAAS,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":["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"]}
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\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 // Log debug messages\n // These will only be in the response when used in internal testing\n const debugMessages = data.filter((message) => message.type === 'DEBUG')\n if (debugMessages.length) {\n console.info('Debug messages:', debugMessages)\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.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"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,E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A,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":["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","debugMessages","message","eventName","properties","body"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import S from"openapi-fetch";var a="__15gifts_conversation_id",v=()=>sessionStorage.removeItem(a),g=()=>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 C=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},p=C;var w=(s,t,e)=>{let i={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(i))},c=w;var y="__15gifts_user_id",M=1e3*60*60*24*30,h=()=>p(y),l=s=>c(y,s,M);var _=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),I=_;var x="0.5.0";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:g()??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(I(o.token))}))}endConversation(){v(),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,M as TTL,y as USER_ID,I as authMiddleware,v as deleteConversationId,g as getConversationId,u as getSessionId,h as getUserId,d as setConversationId,m 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",m=()=>sessionStorage.getItem(f),u=s=>sessionStorage.setItem(f,s);var C=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=C;var M=(s,t,e)=>{let n={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(n))},p=M;var l="__15gifts_user_id",w=1e3*60*60*24*30,y=()=>c(l),h=s=>p(l,s,w);var _=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),g=_;var x="0.5.2";var E=class{endpoint;identity;constructor({customerId:t,fetch:e,conversationUrl:n,frontendUrl:i}){let o={"X-SDK-VERSION":x};this.endpoint={conversation:S({baseUrl:n,fetch:e,headers:o}),frontend:S({baseUrl:i,fetch:e,headers:o})},this.identity={customerId:t,conversationId:v()??void 0,sessionId:m()??void 0,userId:y()??void 0}}async createIdentity(){let{conversationId:t,customerId:e,sessionId:n,userId:i}=this.identity;t&&this.endConversation();let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:e,sessionId:n,userId:i}});o&&(n||(this.identity.sessionId=o.sessionId,u(o.sessionId)),i||(this.identity.userId=o.userId,h(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,n]=t,i=e.conversationId;if(!i)throw new Error("Conversation ID not received");return d(i),this.identity.conversationId=i,n}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;let n=e.filter(r=>r.type==="DEBUG");n.length&&console.info("Debug messages:",n);let i=e.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return i&&(d(i),this.identity.conversationId=i),e.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(t,e){let n={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:n})}};export{a as CONVERSATION_ID,E as Client,f as SESSION_ID,w as TTL,l as USER_ID,g as authMiddleware,I as deleteConversationId,v as getConversationId,m as getSessionId,y as getUserId,d as setConversationId,u as setSessionId,h 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 {\n ApiBasicMessage,\n ApiConversationIdMessage,\n Config,\n ConversationApiRequest,\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-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 async startConversation(): Promise<ApiBasicMessage | 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 [ApiConversationIdMessage, ApiBasicMessage]\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: 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.5.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.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,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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AAS,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"]}
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\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 // Log debug messages\n // These will only be in the response when used in internal testing\n const debugMessages = data.filter((message) => message.type === 'DEBUG')\n if (debugMessages.length) {\n console.info('Debug messages:', debugMessages)\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.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"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,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK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,OAAQW,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","debugMessages","message","eventName","properties","body"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "files": [
5
5
  "dist"
6
6
  ],