@15gifts/sdk 0.9.0 → 0.10.0

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
@@ -1258,8 +1258,9 @@ declare class Client {
1258
1258
  *
1259
1259
  * @param context - Optional context to customize the conversation. It can include:
1260
1260
  * @param context.eligibleProducts An array of eligible product IDs.
1261
+ * @param context.eligibleBundles An array of eligible bundle IDs.
1261
1262
  * @param context.productOverrides Overrides for product details.
1262
- *
1263
+ * @param context.bundleOverrides Overrides for bundle details.
1263
1264
  *
1264
1265
  * @returns A promise that resolves to the opening message.
1265
1266
  *
@@ -1278,11 +1279,9 @@ declare class Client {
1278
1279
  */
1279
1280
  startConversation(context?: {
1280
1281
  eligibleProducts?: string[];
1281
- productOverrides?: Record<string, {
1282
- price: number;
1283
- minSpeed?: number;
1284
- maxSpeed?: number;
1285
- }>;
1282
+ eligibleBundles?: string[];
1283
+ productOverrides?: Record<string, unknown>;
1284
+ bundleOverrides?: Record<string, unknown>;
1286
1285
  }): Promise<TextMessage | undefined>;
1287
1286
  /**
1288
1287
  * Sends a message in the conversation.
package/dist/index.d.ts CHANGED
@@ -1258,8 +1258,9 @@ declare class Client {
1258
1258
  *
1259
1259
  * @param context - Optional context to customize the conversation. It can include:
1260
1260
  * @param context.eligibleProducts An array of eligible product IDs.
1261
+ * @param context.eligibleBundles An array of eligible bundle IDs.
1261
1262
  * @param context.productOverrides Overrides for product details.
1262
- *
1263
+ * @param context.bundleOverrides Overrides for bundle details.
1263
1264
  *
1264
1265
  * @returns A promise that resolves to the opening message.
1265
1266
  *
@@ -1278,11 +1279,9 @@ declare class Client {
1278
1279
  */
1279
1280
  startConversation(context?: {
1280
1281
  eligibleProducts?: string[];
1281
- productOverrides?: Record<string, {
1282
- price: number;
1283
- minSpeed?: number;
1284
- maxSpeed?: number;
1285
- }>;
1282
+ eligibleBundles?: string[];
1283
+ productOverrides?: Record<string, unknown>;
1284
+ bundleOverrides?: Record<string, unknown>;
1286
1285
  }): Promise<TextMessage | undefined>;
1287
1286
  /**
1288
1287
  * Sends a message in the conversation.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.create;var a=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var W=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},C=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of U(t))!A.call(e,o)&&o!==n&&a(e,o,{get:()=>t[o],enumerable:!(s=P(t,o))||s.enumerable});return e};var V=(e,t,n)=>(n=e!=null?N(R(e)):{},C(t||!e||!e.__esModule?a(n,"default",{value:e,enumerable:!0}):n,e)),j=e=>C(a({},"__esModule",{value:!0}),e);var K={};W(K,{CONVERSATION_ID:()=>d,Client:()=>_,JWT_TOKEN:()=>p,SESSION_ID:()=>l,TTL:()=>O,USER_ID:()=>x,authMiddleware:()=>g,deleteConversationId:()=>u,errorMiddleware:()=>I,getConversationId:()=>f,getSessionId:()=>m,getToken:()=>E,getUserId:()=>w,isTokenExpired:()=>k,setConversationId:()=>c,setSessionId:()=>v,setToken:()=>T,setUserId:()=>S});module.exports=j(K);var M=V(require("openapi-fetch"));var d="__15gifts_conversation_id",u=()=>sessionStorage.removeItem(d),f=()=>sessionStorage.getItem(d),c=e=>sessionStorage.setItem(d,e);var l="__15gifts_session_id",m=()=>sessionStorage.getItem(l),v=e=>sessionStorage.setItem(l,e);var B=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},h=B;var J=(e,t,n)=>{let s={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(s))},y=J;var x="__15gifts_user_id",O=1e3*60*60*24*30,w=()=>h(x),S=e=>y(x,e,O);var p="__15gifts_identity_token",k=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},E=()=>{let e=localStorage.getItem(p);return!e||k(e)?(localStorage.removeItem(p),null):e},T=e=>localStorage.setItem(p,e);var G=e=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${e}`),t)}),g=G;var z={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},I=z;var D="0.9.0";var _=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:s,fetch:o,frontendUrl:r,headers:i}=t,b={...i,"X-SDK-VERSION":D};this.endpoint={conversation:(0,M.default)({baseUrl:n,fetch:o,headers:b}),frontend:(0,M.default)({baseUrl:r,fetch:o,headers:b})},this.identity={customerId:s,conversationId:f()??void 0,sessionId:m()??void 0,userId:w()??void 0},this.endpoint.conversation.use(I)}async createIdentity(){let{customerId:t,pageviewId:n,sessionId:s,userId:o}=this.identity,{data:r}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o}});r&&(n||(this.identity.pageviewId=r.pageviewId),s||(this.identity.sessionId=r.sessionId,v(r.sessionId)),o||(this.identity.userId=r.userId,S(r.userId)),T(r.token),Object.values(this.endpoint).forEach(i=>{i.use(g(r.token))}))}endConversation(){u(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={availableProductIds:[],...t},{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!s)return;let[o,r]=s,i=o.conversationId;if(!i)throw new Error("Conversation ID not received");return c(i),this.identity.conversationId=i,r}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let s=n.filter(i=>i.type==="DEBUG");s.length&&console.info("Debug messages:",s);let o=n.find(i=>i.type==="CONVERSATION_ID")?.conversationId;return o&&(c(o),this.identity.conversationId=o),n.filter(i=>i.type!=="CONVERSATION_ID"&&i.type!=="DEBUG")}async trackEvent(t,n){let s={additionalProperties:n,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,pageviewId:this.identity.pageviewId,screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:s})}getIdentity(){return this.identity}getIdentityToken(){return E()}};0&&(module.exports={CONVERSATION_ID,Client,JWT_TOKEN,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,errorMiddleware,getConversationId,getSessionId,getToken,getUserId,isTokenExpired,setConversationId,setSessionId,setToken,setUserId});
1
+ "use strict";var N=Object.create;var a=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var W=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0})},_=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of R(t))!A.call(e,o)&&o!==n&&a(e,o,{get:()=>t[o],enumerable:!(s=P(t,o))||s.enumerable});return e};var B=(e,t,n)=>(n=e!=null?N(U(e)):{},_(t||!e||!e.__esModule?a(n,"default",{value:e,enumerable:!0}):n,e)),V=e=>_(a({},"__esModule",{value:!0}),e);var K={};W(K,{CONVERSATION_ID:()=>d,Client:()=>k,JWT_TOKEN:()=>p,SESSION_ID:()=>f,TTL:()=>C,USER_ID:()=>x,authMiddleware:()=>g,deleteConversationId:()=>u,errorMiddleware:()=>l,getConversationId:()=>I,getSessionId:()=>v,getToken:()=>E,getUserId:()=>w,isTokenExpired:()=>b,setConversationId:()=>c,setSessionId:()=>m,setToken:()=>T,setUserId:()=>S});module.exports=V(K);var M=B(require("openapi-fetch"));var d="__15gifts_conversation_id",u=()=>sessionStorage.removeItem(d),I=()=>sessionStorage.getItem(d),c=e=>sessionStorage.setItem(d,e);var f="__15gifts_session_id",v=()=>sessionStorage.getItem(f),m=e=>sessionStorage.setItem(f,e);var j=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},h=j;var J=(e,t,n)=>{let s={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(s))},y=J;var x="__15gifts_user_id",C=1e3*60*60*24*30,w=()=>h(x),S=e=>y(x,e,C);var p="__15gifts_identity_token",b=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},E=()=>{let e=localStorage.getItem(p);return!e||b(e)?(localStorage.removeItem(p),null):e},T=e=>localStorage.setItem(p,e);var G=e=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${e}`),t)}),g=G;var z={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},l=z;var D="0.10.0";var k=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:s,fetch:o,frontendUrl:r,headers:i}=t,O={...i,"X-SDK-VERSION":D};this.endpoint={conversation:(0,M.default)({baseUrl:n,fetch:o,headers:O}),frontend:(0,M.default)({baseUrl:r,fetch:o,headers:O})},this.identity={customerId:s,conversationId:I()??void 0,sessionId:v()??void 0,userId:w()??void 0},this.endpoint.conversation.use(l)}async createIdentity(){let{customerId:t,pageviewId:n,sessionId:s,userId:o}=this.identity,{data:r}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:o}});r&&(n||(this.identity.pageviewId=r.pageviewId),s||(this.identity.sessionId=r.sessionId,m(r.sessionId)),o||(this.identity.userId=r.userId,S(r.userId)),T(r.token),Object.values(this.endpoint).forEach(i=>{i.use(g(r.token))}))}endConversation(){u(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={...t},{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!s)return;let[o,r]=s,i=o.conversationId;if(!i)throw new Error("Conversation ID not received");return c(i),this.identity.conversationId=i,r}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let s=n.filter(i=>i.type==="DEBUG");s.length&&console.info("Debug messages:",s);let o=n.find(i=>i.type==="CONVERSATION_ID")?.conversationId;return o&&(c(o),this.identity.conversationId=o),n.filter(i=>i.type!=="CONVERSATION_ID"&&i.type!=="DEBUG")}async trackEvent(t,n){let s={additionalProperties:n,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,pageviewId:this.identity.pageviewId,screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:s})}getIdentity(){return this.identity}getIdentityToken(){return E()}};0&&(module.exports={CONVERSATION_ID,Client,JWT_TOKEN,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,errorMiddleware,getConversationId,getSessionId,getToken,getUserId,isTokenExpired,setConversationId,setSessionId,setToken,setUserId});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TextMessage,\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(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ 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 this.endpoint.conversation.use(errorMiddleware)\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 { customerId, pageviewId, sessionId, userId } = this.identity\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 (!pageviewId) {\n this.identity.pageviewId = data.pageviewId\n }\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.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 * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.productOverrides Overrides for product details.\n *\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: {\n eligibleProducts?: string[]\n productOverrides?: Record<string, { price: number; minSpeed?: number; maxSpeed?: number }>\n }): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n availableProductIds: [],\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | 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('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","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","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.9.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 \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,oBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,mBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,aAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAApB,GCAA,IAAAqB,EAAiD,4BCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa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S,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,WAAY,KAAK,SAAS,WAC1B,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","pageviewId","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body","getToken"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TextMessage,\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(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ 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 this.endpoint.conversation.use(errorMiddleware)\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 { customerId, pageviewId, sessionId, userId } = this.identity\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 (!pageviewId) {\n this.identity.pageviewId = data.pageviewId\n }\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.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 * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: {\n eligibleProducts?: string[]\n eligibleBundles?: string[]\n productOverrides?: Record<string, unknown>\n bundleOverrides?: Record<string, unknown>\n }): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | 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('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","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","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.10.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 \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,cAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAA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,eAAgB,KAAK,SAAS,eAC9B,YAAAa,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACb,EAAM,OAIX,IAAMc,EAAgBd,EAAK,OAAQe,GAAYA,EAAQ,OAAS,OAAO,EACnED,EAAc,QAChB,QAAQ,KAAK,kBAAmBA,CAAa,EAI/C,IAAMH,EAAiBX,EAAK,KAAMe,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIJ,IACFC,EAAkBD,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBX,EAAK,OAAQe,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,WAAY,KAAK,SAAS,WAC1B,YAAa,OAAO,OAAO,MAC3B,aAAc,OAAO,OAAO,OAC5B,WAAY,OAAO,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["index_exports","__export","CONVERSATION_ID","Client","JWT_TOKEN","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","error_default","getConversationId","getSessionId","getToken","getUserId","isTokenExpired","setConversationId","setSessionId","setToken","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","pageviewId","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body","getToken"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import _ from"openapi-fetch";var a="__15gifts_conversation_id",l=()=>sessionStorage.removeItem(a),m=()=>sessionStorage.getItem(a),d=e=>sessionStorage.setItem(a,e);var v="__15gifts_session_id",h=()=>sessionStorage.getItem(v),y=e=>sessionStorage.setItem(v,e);var C=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},c=C;var O=(e,t,n)=>{let s={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(s))},p=O;var x="__15gifts_user_id",k=1e3*60*60*24*30,w=()=>c(x),S=e=>p(x,e,k);var g="__15gifts_identity_token",D=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},E=()=>{let e=localStorage.getItem(g);return!e||D(e)?(localStorage.removeItem(g),null):e},T=e=>localStorage.setItem(g,e);var N=e=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${e}`),t)}),I=N;var P={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},u=P;var M="0.9.0";var b=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:s,fetch:r,frontendUrl:i,headers:o}=t,f={...o,"X-SDK-VERSION":M};this.endpoint={conversation:_({baseUrl:n,fetch:r,headers:f}),frontend:_({baseUrl:i,fetch:r,headers:f})},this.identity={customerId:s,conversationId:m()??void 0,sessionId:h()??void 0,userId:w()??void 0},this.endpoint.conversation.use(u)}async createIdentity(){let{customerId:t,pageviewId:n,sessionId:s,userId:r}=this.identity,{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:r}});i&&(n||(this.identity.pageviewId=i.pageviewId),s||(this.identity.sessionId=i.sessionId,y(i.sessionId)),r||(this.identity.userId=i.userId,S(i.userId)),T(i.token),Object.values(this.endpoint).forEach(o=>{o.use(I(i.token))}))}endConversation(){l(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={availableProductIds:[],...t},{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!s)return;let[r,i]=s,o=r.conversationId;if(!o)throw new Error("Conversation ID not received");return d(o),this.identity.conversationId=o,i}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let s=n.filter(o=>o.type==="DEBUG");s.length&&console.info("Debug messages:",s);let r=n.find(o=>o.type==="CONVERSATION_ID")?.conversationId;return r&&(d(r),this.identity.conversationId=r),n.filter(o=>o.type!=="CONVERSATION_ID"&&o.type!=="DEBUG")}async trackEvent(t,n){let s={additionalProperties:n,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,pageviewId:this.identity.pageviewId,screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:s})}getIdentity(){return this.identity}getIdentityToken(){return E()}};export{a as CONVERSATION_ID,b as Client,g as JWT_TOKEN,v as SESSION_ID,k as TTL,x as USER_ID,I as authMiddleware,l as deleteConversationId,u as errorMiddleware,m as getConversationId,h as getSessionId,E as getToken,w as getUserId,D as isTokenExpired,d as setConversationId,y as setSessionId,T as setToken,S as setUserId};
1
+ import k from"openapi-fetch";var a="__15gifts_conversation_id",f=()=>sessionStorage.removeItem(a),v=()=>sessionStorage.getItem(a),d=e=>sessionStorage.setItem(a,e);var m="__15gifts_session_id",h=()=>sessionStorage.getItem(m),y=e=>sessionStorage.setItem(m,e);var _=e=>{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Date.now()>n.expires?(localStorage.removeItem(e),null):n.value},c=_;var C=(e,t,n)=>{let s={expires:Date.now()+n,value:t};localStorage.setItem(e,JSON.stringify(s))},p=C;var x="__15gifts_user_id",b=1e3*60*60*24*30,w=()=>c(x),S=e=>p(x,e,b);var g="__15gifts_identity_token",D=e=>{try{let[,t]=e.split(".");if(!t)throw new Error("Invalid token payload");let n=JSON.parse(atob(t));return n.exp&&Date.now()/1e3>n.exp}catch(t){return console.error("Invalid token format",t),!0}},E=()=>{let e=localStorage.getItem(g);return!e||D(e)?(localStorage.removeItem(g),null):e},T=e=>localStorage.setItem(g,e);var N=e=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${e}`),t)}),l=N;var P={onResponse:async({response:e})=>{if(!e.ok){let t=await e.json();throw new Error(t.message)}return e}},u=P;var M="0.10.0";var O=class{endpoint;identity;constructor(t){let{conversationUrl:n,customerId:s,fetch:r,frontendUrl:i,headers:o}=t,I={...o,"X-SDK-VERSION":M};this.endpoint={conversation:k({baseUrl:n,fetch:r,headers:I}),frontend:k({baseUrl:i,fetch:r,headers:I})},this.identity={customerId:s,conversationId:v()??void 0,sessionId:h()??void 0,userId:w()??void 0},this.endpoint.conversation.use(u)}async createIdentity(){let{customerId:t,pageviewId:n,sessionId:s,userId:r}=this.identity,{data:i}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:t,sessionId:s,userId:r}});i&&(n||(this.identity.pageviewId=i.pageviewId),s||(this.identity.sessionId=i.sessionId,y(i.sessionId)),r||(this.identity.userId=i.userId,S(i.userId)),T(i.token),Object.values(this.endpoint).forEach(o=>{o.use(l(i.token))}))}endConversation(){f(),this.identity.conversationId=void 0}async startConversation(t){this.endConversation();let n={...t},{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:n}});if(!s)return;let[r,i]=s,o=r.conversationId;if(!o)throw new Error("Conversation ID not received");return d(o),this.identity.conversationId=o,i}async sendMessage({userMessage:t}){let{data:n}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!n)return;let s=n.filter(o=>o.type==="DEBUG");s.length&&console.info("Debug messages:",s);let r=n.find(o=>o.type==="CONVERSATION_ID")?.conversationId;return r&&(d(r),this.identity.conversationId=r),n.filter(o=>o.type!=="CONVERSATION_ID"&&o.type!=="DEBUG")}async trackEvent(t,n){let s={additionalProperties:n,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,pageviewId:this.identity.pageviewId,screenWidth:window.screen.width,screenHeight:window.screen.height,screenSize:window.screen.width<=480?"mobile":"large",url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:s})}getIdentity(){return this.identity}getIdentityToken(){return E()}};export{a as CONVERSATION_ID,O as Client,g as JWT_TOKEN,m as SESSION_ID,b as TTL,x as USER_ID,l as authMiddleware,f as deleteConversationId,u as errorMiddleware,v as getConversationId,h as getSessionId,E as getToken,w as getUserId,D as isTokenExpired,d as setConversationId,y as setSessionId,T as setToken,S as setUserId};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../package.json"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TextMessage,\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(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ 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 this.endpoint.conversation.use(errorMiddleware)\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 { customerId, pageviewId, sessionId, userId } = this.identity\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 (!pageviewId) {\n this.identity.pageviewId = data.pageviewId\n }\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.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 * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.productOverrides Overrides for product details.\n *\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: {\n eligibleProducts?: string[]\n productOverrides?: Record<string, { price: number; minSpeed?: number; maxSpeed?: number }>\n }): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n availableProductIds: [],\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | 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('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","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","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.9.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 \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAA0C,gBCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAA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O,OAAO,OAAS,IAAM,SAAW,QACpD,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CAaA,aAAwB,CACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","pageviewId","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body","getToken"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/identity/token.ts","../src/middlewares/auth.ts","../src/middlewares/error.ts","../package.json"],"sourcesContent":["import createClient, { type ClientOptions } from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n getToken,\n setConversationId,\n setSessionId,\n setUserId,\n setToken,\n} from './identity'\nimport { authMiddleware, errorMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n Config,\n ConversationIdMessage,\n DebugMessage,\n Endpoint,\n Identity,\n Message,\n TextMessage,\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(config: Config) {\n const { conversationUrl, customerId, fetch, frontendUrl, headers: defaultHeaders } = config\n\n const headers: ClientOptions['headers'] = {\n ...defaultHeaders,\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ 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 this.endpoint.conversation.use(errorMiddleware)\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 { customerId, pageviewId, sessionId, userId } = this.identity\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 (!pageviewId) {\n this.identity.pageviewId = data.pageviewId\n }\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n setToken(data.token)\n\n Object.values(this.endpoint).forEach((endpoint) => {\n endpoint.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 * @param context - Optional context to customize the conversation. It can include:\n * @param context.eligibleProducts An array of eligible product IDs.\n * @param context.eligibleBundles An array of eligible bundle IDs.\n * @param context.productOverrides Overrides for product details.\n * @param context.bundleOverrides Overrides for bundle details.\n *\n * @returns A promise that resolves to the opening message.\n *\n * @example\n * ##### Basic usage\n * ```ts\n * const openingMessage = await client.startConversation()\n * console.log('Opening message:', openingMessage)\n * ```\n *\n * ##### With context\n * ```ts\n * const openingMessage = await client.startConversation({ eligibleProducts: ['product-1', 'product-2'], productOverrides: { 'product-1': { price: 40 } })\n * console.log('Opening message:', openingMessage)\n * ```\n */\n async startConversation(context?: {\n eligibleProducts?: string[]\n eligibleBundles?: string[]\n productOverrides?: Record<string, unknown>\n bundleOverrides?: Record<string, unknown>\n }): Promise<TextMessage | undefined> {\n this.endConversation()\n\n const conversationContext = {\n ...context,\n }\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext,\n },\n })\n\n if (!data) return undefined\n\n const [conversationIdMessage, openingMessage] = data as [ConversationIdMessage, TextMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation.\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: string\n }): Promise<Exclude<Message, ConversationIdMessage | 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('entry_point-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n pageviewId: this.identity.pageviewId,\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n screenSize: window.screen.width <= 480 ? 'mobile' : 'large',\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n\n /**\n * Gets an existing identity of the user.\n *\n * @returns An Identity object containing `customerId`, `conversationId`, `sessionId`, `userId`.\n *\n * @example\n * ```ts\n * identity = client.getIdentity()\n * console.log('Identity retrieved:', identity)\n * ```\n */\n getIdentity(): Identity {\n return this.identity\n }\n\n /**\n * Gets the JWT from the localStorage.\n *\n * @returns {string | null} the JWT.\n *\n * @example\n * ```ts\n * token = client.getIdentityToken()\n * console.log('Identity token retrieved:', token)\n * ```\n */\n getIdentityToken(): string | null {\n return getToken()\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","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","/**\n * The key used to store the JWT in `localStorage`.\n *\n * @ignore\n */\nexport const JWT_TOKEN = '__15gifts_identity_token'\n\n/**\n * Checks if the JWT is expired.\n *\n * @param {string} token - the JWT.\n * @returns {boolean} `true` if expired, `false` otherwise.\n */\nexport const isTokenExpired = (token: string): boolean => {\n try {\n const [, payloadBase64] = token.split('.')\n if (!payloadBase64) {\n throw new Error('Invalid token payload')\n }\n const payload = JSON.parse(atob(payloadBase64))\n\n return payload.exp && Date.now() / 1000 > payload.exp\n } catch (error) {\n console.error('Invalid token format', error)\n return true\n }\n}\n\n/**\n * Retrieves the JWT from `localStorage` and checks if it is expired.\n *\n * @returns {string | null} The JWT if valid, otherwise `null`.\n */\nexport const getToken = (): string | null => {\n const token = localStorage.getItem(JWT_TOKEN)\n\n if (!token || isTokenExpired(token)) {\n localStorage.removeItem(JWT_TOKEN)\n return null\n }\n\n return token\n}\n\n/**\n * Stores the given JWT in `localStorage`.\n *\n * @example\n * ```ts\n * import { setToken } from '@15gifts/sdk'\n *\n * setToken('ey...')\n * ```\n */\nexport const setToken = (token: string) => localStorage.setItem(JWT_TOKEN, token)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for handling errors.\n *\n * @returns A middleware object that throws an error if the response is not ok.\n *\n * @example\n * ```ts\n * import { errorMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(errorMiddleware())\n * ```\n */\nconst errorMiddleware: Middleware = {\n // onError does not handle error responses with 4xx or 5xx HTTP status codes, since these are considered \"successful\" responses but with a bad status code.\n // In these cases we need to check the response's status property or ok() method via the onResponse callback.\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const data = await response.json()\n\n throw new Error(data.message)\n }\n\n return response\n },\n}\n\nexport default errorMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.10.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 \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.13.4\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.6.0\",\n \"tsup\": \"^8.3.6\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAA0C,gBCK1C,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,EChBf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IA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ACtB,OAAO,KAAK,QACd,CAaA,kBAAkC,CAChC,OAAOC,EAAS,CAClB,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","JWT_TOKEN","isTokenExpired","token","payloadBase64","payload","error","getToken","setToken","authMiddleware","accessToken","request","auth_default","errorMiddleware","response","data","error_default","version","Client","config","conversationUrl","customerId","fetch","frontendUrl","defaultHeaders","headers","version","createClient","getConversationId","getSessionId","getUserId","error_default","pageviewId","sessionId","userId","data","setSessionId","setUserId","setToken","endpoint","auth_default","deleteConversationId","context","conversationContext","conversationIdMessage","openingMessage","conversationId","setConversationId","userMessage","debugMessages","message","eventName","properties","body","getToken"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@15gifts/sdk",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "files": [
5
5
  "dist"
6
6
  ],