@15gifts/sdk 0.4.2 → 0.5.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 +35 -30
- package/dist/index.d.ts +35 -30
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -168,6 +168,23 @@ interface components {
|
|
|
168
168
|
/** Value */
|
|
169
169
|
value: string;
|
|
170
170
|
};
|
|
171
|
+
/** ConversationStageTransitionRecord */
|
|
172
|
+
ConversationStageTransitionRecord: {
|
|
173
|
+
/**
|
|
174
|
+
* Id
|
|
175
|
+
* @default conversation_stage_transition
|
|
176
|
+
* @constant
|
|
177
|
+
* @enum {string}
|
|
178
|
+
*/
|
|
179
|
+
id: 'conversation_stage_transition';
|
|
180
|
+
/**
|
|
181
|
+
* Timestamp
|
|
182
|
+
* Format: date-time
|
|
183
|
+
*/
|
|
184
|
+
timestamp?: string;
|
|
185
|
+
/** Data */
|
|
186
|
+
data: string;
|
|
187
|
+
};
|
|
171
188
|
/** ConversationTurnIDRecord */
|
|
172
189
|
ConversationTurnIDRecord: {
|
|
173
190
|
/**
|
|
@@ -224,7 +241,7 @@ interface components {
|
|
|
224
241
|
* Records
|
|
225
242
|
* @description List of debug records.
|
|
226
243
|
*/
|
|
227
|
-
records: (components['schemas']['EmbeddingTokenCountRecord'] | components['schemas']['SystemPromptRecord'] | components['schemas']['TriggeredBranchesRecord'] | components['schemas']['ActionsMatchedByTriggeredBranchesRecord'] | components['schemas']['RunActionDetailsRecord'] | components['schemas']['MaxCosineSimilarityScoresRecord'] | components['schemas']['LLMTokenCountRecord'] | components['schemas']['ContextChunksRecord'] | components['schemas']['ApplicationVersionRecord'] | components['schemas']['DBVersionRecord'] | components['schemas']['PhraseTokenProbabilitiesRecord'] | components['schemas']['ConversationTurnIDRecord'])[];
|
|
244
|
+
records: (components['schemas']['EmbeddingTokenCountRecord'] | components['schemas']['SystemPromptRecord'] | components['schemas']['TriggeredBranchesRecord'] | components['schemas']['ActionsMatchedByTriggeredBranchesRecord'] | components['schemas']['RunActionDetailsRecord'] | components['schemas']['MaxCosineSimilarityScoresRecord'] | components['schemas']['LLMTokenCountRecord'] | components['schemas']['ContextChunksRecord'] | components['schemas']['ApplicationVersionRecord'] | components['schemas']['DBVersionRecord'] | components['schemas']['PhraseTokenProbabilitiesRecord'] | components['schemas']['ConversationTurnIDRecord'] | components['schemas']['ConversationStageTransitionRecord'])[];
|
|
228
245
|
};
|
|
229
246
|
/** EmbeddingTokenCountRecord */
|
|
230
247
|
EmbeddingTokenCountRecord: {
|
|
@@ -297,12 +314,6 @@ interface components {
|
|
|
297
314
|
/** Detail */
|
|
298
315
|
detail?: components['schemas']['ValidationError'][];
|
|
299
316
|
};
|
|
300
|
-
/**
|
|
301
|
-
* IndustryEnum
|
|
302
|
-
* @constant
|
|
303
|
-
* @enum {string}
|
|
304
|
-
*/
|
|
305
|
-
IndustryEnum: 'telco';
|
|
306
317
|
/** LLMTokenCountRecord */
|
|
307
318
|
LLMTokenCountRecord: {
|
|
308
319
|
/**
|
|
@@ -418,21 +429,12 @@ interface components {
|
|
|
418
429
|
*/
|
|
419
430
|
url: string;
|
|
420
431
|
};
|
|
421
|
-
/** ProductInformationChunkMetadata */
|
|
422
|
-
ProductInformationChunkMetadata: {
|
|
423
|
-
/** Model */
|
|
424
|
-
model: string;
|
|
425
|
-
/** Brand */
|
|
426
|
-
brand: string;
|
|
427
|
-
};
|
|
428
432
|
/** ProductInformationChunkQueryResult */
|
|
429
433
|
ProductInformationChunkQueryResult: {
|
|
430
434
|
/** Text */
|
|
431
435
|
text: string;
|
|
432
436
|
/** Customer Id */
|
|
433
437
|
customer_id: string;
|
|
434
|
-
metadata: components['schemas']['ProductInformationChunkMetadata'];
|
|
435
|
-
industry: components['schemas']['IndustryEnum'];
|
|
436
438
|
/** Similarity Score */
|
|
437
439
|
similarity_score: number;
|
|
438
440
|
};
|
|
@@ -535,10 +537,9 @@ interface components {
|
|
|
535
537
|
/**
|
|
536
538
|
* Id
|
|
537
539
|
* @default system_prompt
|
|
538
|
-
* @constant
|
|
539
540
|
* @enum {string}
|
|
540
541
|
*/
|
|
541
|
-
id: 'system_prompt';
|
|
542
|
+
id: 'system_prompt' | 'sales_framework_system_prompt' | 'conversation_stage_transition_prompt';
|
|
542
543
|
/**
|
|
543
544
|
* Timestamp
|
|
544
545
|
* Format: date-time
|
|
@@ -852,7 +853,7 @@ interface operations {
|
|
|
852
853
|
'user-agent'?: string;
|
|
853
854
|
/**
|
|
854
855
|
* @description Comma-separated list of feature flags (flags might require elevated permissions)
|
|
855
|
-
* @example debug,no-decision-forest
|
|
856
|
+
* @example debug,no-decision-forest,use-sales-framework
|
|
856
857
|
*/
|
|
857
858
|
'x-feature-flags'?: string | null;
|
|
858
859
|
/**
|
|
@@ -924,7 +925,7 @@ interface operations {
|
|
|
924
925
|
'user-agent'?: string;
|
|
925
926
|
/**
|
|
926
927
|
* @description Comma-separated list of feature flags (flags might require elevated permissions)
|
|
927
|
-
* @example debug,no-decision-forest
|
|
928
|
+
* @example debug,no-decision-forest,use-sales-framework
|
|
928
929
|
*/
|
|
929
930
|
'x-feature-flags'?: string | null;
|
|
930
931
|
/**
|
|
@@ -948,7 +949,7 @@ interface operations {
|
|
|
948
949
|
[name: string]: unknown;
|
|
949
950
|
};
|
|
950
951
|
content: {
|
|
951
|
-
'application/json': components['schemas']['MessageChunk'] | components['schemas']['DebugChunk'] | components['schemas']['SingleSelectChunk'] | components['schemas']['MultiSelectChunk'] | components['schemas']['ExitToChatChunk'] | components['schemas']['RecommendationChunk'] | components['schemas']['ConversationIdChunk'] | components['schemas']['ExitToPurchaseChunk'];
|
|
952
|
+
'application/json': (components['schemas']['MessageChunk'] | components['schemas']['DebugChunk'] | components['schemas']['SingleSelectChunk'] | components['schemas']['MultiSelectChunk'] | components['schemas']['ExitToChatChunk'] | components['schemas']['RecommendationChunk'] | components['schemas']['ConversationIdChunk'] | components['schemas']['ExitToPurchaseChunk'])[];
|
|
952
953
|
};
|
|
953
954
|
};
|
|
954
955
|
/** @description The user is not authorized to access the requested data */
|
|
@@ -996,7 +997,7 @@ interface operations {
|
|
|
996
997
|
'user-agent'?: string;
|
|
997
998
|
/**
|
|
998
999
|
* @description Comma-separated list of feature flags (flags might require elevated permissions)
|
|
999
|
-
* @example debug,no-decision-forest
|
|
1000
|
+
* @example debug,no-decision-forest,use-sales-framework
|
|
1000
1001
|
*/
|
|
1001
1002
|
'x-feature-flags'?: string | null;
|
|
1002
1003
|
/**
|
|
@@ -1566,9 +1567,10 @@ interface paths {
|
|
|
1566
1567
|
* These are the types as defined in the OpenAPI schema.
|
|
1567
1568
|
* We don't use them directly, or export them here because of how they appear in the documentation site.
|
|
1568
1569
|
*/
|
|
1569
|
-
type ApiConversationRequest = components['schemas']['
|
|
1570
|
+
type ApiConversationRequest = components['schemas']['app__conversation__models__input__MessageRequest'];
|
|
1570
1571
|
type ApiConversationResponse = operations['generate_conversation_json_response_api_conversation_v2_post']['responses']['200']['content']['application/json'];
|
|
1571
1572
|
type ApiDebug = components['schemas']['DebugChunk'];
|
|
1573
|
+
type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
|
|
1572
1574
|
type ApiBasicMessage = components['schemas']['MessageChunk'];
|
|
1573
1575
|
type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
|
|
1574
1576
|
type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
|
|
@@ -1576,6 +1578,7 @@ type ApiExitToChatMessage = components['schemas']['ExitToChatChunk'];
|
|
|
1576
1578
|
type ApiExitToPurchaseMessage = components['schemas']['ExitToPurchaseChunk'];
|
|
1577
1579
|
type ApiRecomendationMessage = components['schemas']['RecommendationChunk'];
|
|
1578
1580
|
type ApiTrackingUserRequest = paths['/api/tracking/user/v2']['post']['requestBody']['content']['application/json'];
|
|
1581
|
+
type ApiIdentityRequest = paths['/api/tracking/identity/v2']['post']['requestBody']['content']['application/json'];
|
|
1579
1582
|
/**
|
|
1580
1583
|
* Configuration options for initializing the client.
|
|
1581
1584
|
*/
|
|
@@ -1583,7 +1586,7 @@ interface Config {
|
|
|
1583
1586
|
/**
|
|
1584
1587
|
* The customer ID associated with the conversation.
|
|
1585
1588
|
*/
|
|
1586
|
-
customerId:
|
|
1589
|
+
customerId: ApiIdentityRequest['customerId'];
|
|
1587
1590
|
/**
|
|
1588
1591
|
* Optional fetch function to use for making HTTP requests.
|
|
1589
1592
|
* If not provided, the default `fetch` implementation will be used.
|
|
@@ -1705,16 +1708,19 @@ declare class Client {
|
|
|
1705
1708
|
*/
|
|
1706
1709
|
endConversation(): void;
|
|
1707
1710
|
/**
|
|
1708
|
-
*
|
|
1711
|
+
* Clears the existing conversation ID, then generates a new one and returns the opening message.
|
|
1712
|
+
*/
|
|
1713
|
+
startConversation(): Promise<ApiBasicMessage | undefined>;
|
|
1714
|
+
/**
|
|
1715
|
+
* Sends a message in the conversation
|
|
1709
1716
|
*
|
|
1710
|
-
* @param options - An object containing the
|
|
1717
|
+
* @param options - An object containing the user message.
|
|
1711
1718
|
* @returns A promise that resolves to an array of messages or debug records.
|
|
1712
1719
|
* If the message is a debug record, it will throw an error.
|
|
1713
1720
|
*
|
|
1714
1721
|
* @example
|
|
1715
1722
|
* ```ts
|
|
1716
1723
|
* const newMessages = await client.sendMessage({
|
|
1717
|
-
* openingMessage: 'Hello! How can I help you?',
|
|
1718
1724
|
* userMessage: 'How can I get support?',
|
|
1719
1725
|
* })
|
|
1720
1726
|
*
|
|
@@ -1725,8 +1731,7 @@ declare class Client {
|
|
|
1725
1731
|
* }
|
|
1726
1732
|
* ```
|
|
1727
1733
|
*/
|
|
1728
|
-
sendMessage({
|
|
1729
|
-
openingMessage?: ConversationApiRequest['openingMessage'];
|
|
1734
|
+
sendMessage({ userMessage, }: {
|
|
1730
1735
|
userMessage: ConversationApiRequest['userMessage'];
|
|
1731
1736
|
}): Promise<Message[] | undefined>;
|
|
1732
1737
|
/**
|
|
@@ -1923,4 +1928,4 @@ declare const setUserId: (userId: string) => void;
|
|
|
1923
1928
|
*/
|
|
1924
1929
|
declare const authMiddleware: (accessToken: string) => Middleware;
|
|
1925
1930
|
|
|
1926
|
-
export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type ConversationApiResponse, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
|
1931
|
+
export { type ApiBasicMessage, type ApiConversationIdMessage, CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type ConversationApiResponse, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
package/dist/index.d.ts
CHANGED
|
@@ -168,6 +168,23 @@ interface components {
|
|
|
168
168
|
/** Value */
|
|
169
169
|
value: string;
|
|
170
170
|
};
|
|
171
|
+
/** ConversationStageTransitionRecord */
|
|
172
|
+
ConversationStageTransitionRecord: {
|
|
173
|
+
/**
|
|
174
|
+
* Id
|
|
175
|
+
* @default conversation_stage_transition
|
|
176
|
+
* @constant
|
|
177
|
+
* @enum {string}
|
|
178
|
+
*/
|
|
179
|
+
id: 'conversation_stage_transition';
|
|
180
|
+
/**
|
|
181
|
+
* Timestamp
|
|
182
|
+
* Format: date-time
|
|
183
|
+
*/
|
|
184
|
+
timestamp?: string;
|
|
185
|
+
/** Data */
|
|
186
|
+
data: string;
|
|
187
|
+
};
|
|
171
188
|
/** ConversationTurnIDRecord */
|
|
172
189
|
ConversationTurnIDRecord: {
|
|
173
190
|
/**
|
|
@@ -224,7 +241,7 @@ interface components {
|
|
|
224
241
|
* Records
|
|
225
242
|
* @description List of debug records.
|
|
226
243
|
*/
|
|
227
|
-
records: (components['schemas']['EmbeddingTokenCountRecord'] | components['schemas']['SystemPromptRecord'] | components['schemas']['TriggeredBranchesRecord'] | components['schemas']['ActionsMatchedByTriggeredBranchesRecord'] | components['schemas']['RunActionDetailsRecord'] | components['schemas']['MaxCosineSimilarityScoresRecord'] | components['schemas']['LLMTokenCountRecord'] | components['schemas']['ContextChunksRecord'] | components['schemas']['ApplicationVersionRecord'] | components['schemas']['DBVersionRecord'] | components['schemas']['PhraseTokenProbabilitiesRecord'] | components['schemas']['ConversationTurnIDRecord'])[];
|
|
244
|
+
records: (components['schemas']['EmbeddingTokenCountRecord'] | components['schemas']['SystemPromptRecord'] | components['schemas']['TriggeredBranchesRecord'] | components['schemas']['ActionsMatchedByTriggeredBranchesRecord'] | components['schemas']['RunActionDetailsRecord'] | components['schemas']['MaxCosineSimilarityScoresRecord'] | components['schemas']['LLMTokenCountRecord'] | components['schemas']['ContextChunksRecord'] | components['schemas']['ApplicationVersionRecord'] | components['schemas']['DBVersionRecord'] | components['schemas']['PhraseTokenProbabilitiesRecord'] | components['schemas']['ConversationTurnIDRecord'] | components['schemas']['ConversationStageTransitionRecord'])[];
|
|
228
245
|
};
|
|
229
246
|
/** EmbeddingTokenCountRecord */
|
|
230
247
|
EmbeddingTokenCountRecord: {
|
|
@@ -297,12 +314,6 @@ interface components {
|
|
|
297
314
|
/** Detail */
|
|
298
315
|
detail?: components['schemas']['ValidationError'][];
|
|
299
316
|
};
|
|
300
|
-
/**
|
|
301
|
-
* IndustryEnum
|
|
302
|
-
* @constant
|
|
303
|
-
* @enum {string}
|
|
304
|
-
*/
|
|
305
|
-
IndustryEnum: 'telco';
|
|
306
317
|
/** LLMTokenCountRecord */
|
|
307
318
|
LLMTokenCountRecord: {
|
|
308
319
|
/**
|
|
@@ -418,21 +429,12 @@ interface components {
|
|
|
418
429
|
*/
|
|
419
430
|
url: string;
|
|
420
431
|
};
|
|
421
|
-
/** ProductInformationChunkMetadata */
|
|
422
|
-
ProductInformationChunkMetadata: {
|
|
423
|
-
/** Model */
|
|
424
|
-
model: string;
|
|
425
|
-
/** Brand */
|
|
426
|
-
brand: string;
|
|
427
|
-
};
|
|
428
432
|
/** ProductInformationChunkQueryResult */
|
|
429
433
|
ProductInformationChunkQueryResult: {
|
|
430
434
|
/** Text */
|
|
431
435
|
text: string;
|
|
432
436
|
/** Customer Id */
|
|
433
437
|
customer_id: string;
|
|
434
|
-
metadata: components['schemas']['ProductInformationChunkMetadata'];
|
|
435
|
-
industry: components['schemas']['IndustryEnum'];
|
|
436
438
|
/** Similarity Score */
|
|
437
439
|
similarity_score: number;
|
|
438
440
|
};
|
|
@@ -535,10 +537,9 @@ interface components {
|
|
|
535
537
|
/**
|
|
536
538
|
* Id
|
|
537
539
|
* @default system_prompt
|
|
538
|
-
* @constant
|
|
539
540
|
* @enum {string}
|
|
540
541
|
*/
|
|
541
|
-
id: 'system_prompt';
|
|
542
|
+
id: 'system_prompt' | 'sales_framework_system_prompt' | 'conversation_stage_transition_prompt';
|
|
542
543
|
/**
|
|
543
544
|
* Timestamp
|
|
544
545
|
* Format: date-time
|
|
@@ -852,7 +853,7 @@ interface operations {
|
|
|
852
853
|
'user-agent'?: string;
|
|
853
854
|
/**
|
|
854
855
|
* @description Comma-separated list of feature flags (flags might require elevated permissions)
|
|
855
|
-
* @example debug,no-decision-forest
|
|
856
|
+
* @example debug,no-decision-forest,use-sales-framework
|
|
856
857
|
*/
|
|
857
858
|
'x-feature-flags'?: string | null;
|
|
858
859
|
/**
|
|
@@ -924,7 +925,7 @@ interface operations {
|
|
|
924
925
|
'user-agent'?: string;
|
|
925
926
|
/**
|
|
926
927
|
* @description Comma-separated list of feature flags (flags might require elevated permissions)
|
|
927
|
-
* @example debug,no-decision-forest
|
|
928
|
+
* @example debug,no-decision-forest,use-sales-framework
|
|
928
929
|
*/
|
|
929
930
|
'x-feature-flags'?: string | null;
|
|
930
931
|
/**
|
|
@@ -948,7 +949,7 @@ interface operations {
|
|
|
948
949
|
[name: string]: unknown;
|
|
949
950
|
};
|
|
950
951
|
content: {
|
|
951
|
-
'application/json': components['schemas']['MessageChunk'] | components['schemas']['DebugChunk'] | components['schemas']['SingleSelectChunk'] | components['schemas']['MultiSelectChunk'] | components['schemas']['ExitToChatChunk'] | components['schemas']['RecommendationChunk'] | components['schemas']['ConversationIdChunk'] | components['schemas']['ExitToPurchaseChunk'];
|
|
952
|
+
'application/json': (components['schemas']['MessageChunk'] | components['schemas']['DebugChunk'] | components['schemas']['SingleSelectChunk'] | components['schemas']['MultiSelectChunk'] | components['schemas']['ExitToChatChunk'] | components['schemas']['RecommendationChunk'] | components['schemas']['ConversationIdChunk'] | components['schemas']['ExitToPurchaseChunk'])[];
|
|
952
953
|
};
|
|
953
954
|
};
|
|
954
955
|
/** @description The user is not authorized to access the requested data */
|
|
@@ -996,7 +997,7 @@ interface operations {
|
|
|
996
997
|
'user-agent'?: string;
|
|
997
998
|
/**
|
|
998
999
|
* @description Comma-separated list of feature flags (flags might require elevated permissions)
|
|
999
|
-
* @example debug,no-decision-forest
|
|
1000
|
+
* @example debug,no-decision-forest,use-sales-framework
|
|
1000
1001
|
*/
|
|
1001
1002
|
'x-feature-flags'?: string | null;
|
|
1002
1003
|
/**
|
|
@@ -1566,9 +1567,10 @@ interface paths {
|
|
|
1566
1567
|
* These are the types as defined in the OpenAPI schema.
|
|
1567
1568
|
* We don't use them directly, or export them here because of how they appear in the documentation site.
|
|
1568
1569
|
*/
|
|
1569
|
-
type ApiConversationRequest = components['schemas']['
|
|
1570
|
+
type ApiConversationRequest = components['schemas']['app__conversation__models__input__MessageRequest'];
|
|
1570
1571
|
type ApiConversationResponse = operations['generate_conversation_json_response_api_conversation_v2_post']['responses']['200']['content']['application/json'];
|
|
1571
1572
|
type ApiDebug = components['schemas']['DebugChunk'];
|
|
1573
|
+
type ApiConversationIdMessage = components['schemas']['ConversationIdChunk'];
|
|
1572
1574
|
type ApiBasicMessage = components['schemas']['MessageChunk'];
|
|
1573
1575
|
type ApiMultiSelectMessage = components['schemas']['MultiSelectChunk'];
|
|
1574
1576
|
type ApiSingleSelectMessage = components['schemas']['SingleSelectChunk'];
|
|
@@ -1576,6 +1578,7 @@ type ApiExitToChatMessage = components['schemas']['ExitToChatChunk'];
|
|
|
1576
1578
|
type ApiExitToPurchaseMessage = components['schemas']['ExitToPurchaseChunk'];
|
|
1577
1579
|
type ApiRecomendationMessage = components['schemas']['RecommendationChunk'];
|
|
1578
1580
|
type ApiTrackingUserRequest = paths['/api/tracking/user/v2']['post']['requestBody']['content']['application/json'];
|
|
1581
|
+
type ApiIdentityRequest = paths['/api/tracking/identity/v2']['post']['requestBody']['content']['application/json'];
|
|
1579
1582
|
/**
|
|
1580
1583
|
* Configuration options for initializing the client.
|
|
1581
1584
|
*/
|
|
@@ -1583,7 +1586,7 @@ interface Config {
|
|
|
1583
1586
|
/**
|
|
1584
1587
|
* The customer ID associated with the conversation.
|
|
1585
1588
|
*/
|
|
1586
|
-
customerId:
|
|
1589
|
+
customerId: ApiIdentityRequest['customerId'];
|
|
1587
1590
|
/**
|
|
1588
1591
|
* Optional fetch function to use for making HTTP requests.
|
|
1589
1592
|
* If not provided, the default `fetch` implementation will be used.
|
|
@@ -1705,16 +1708,19 @@ declare class Client {
|
|
|
1705
1708
|
*/
|
|
1706
1709
|
endConversation(): void;
|
|
1707
1710
|
/**
|
|
1708
|
-
*
|
|
1711
|
+
* Clears the existing conversation ID, then generates a new one and returns the opening message.
|
|
1712
|
+
*/
|
|
1713
|
+
startConversation(): Promise<ApiBasicMessage | undefined>;
|
|
1714
|
+
/**
|
|
1715
|
+
* Sends a message in the conversation
|
|
1709
1716
|
*
|
|
1710
|
-
* @param options - An object containing the
|
|
1717
|
+
* @param options - An object containing the user message.
|
|
1711
1718
|
* @returns A promise that resolves to an array of messages or debug records.
|
|
1712
1719
|
* If the message is a debug record, it will throw an error.
|
|
1713
1720
|
*
|
|
1714
1721
|
* @example
|
|
1715
1722
|
* ```ts
|
|
1716
1723
|
* const newMessages = await client.sendMessage({
|
|
1717
|
-
* openingMessage: 'Hello! How can I help you?',
|
|
1718
1724
|
* userMessage: 'How can I get support?',
|
|
1719
1725
|
* })
|
|
1720
1726
|
*
|
|
@@ -1725,8 +1731,7 @@ declare class Client {
|
|
|
1725
1731
|
* }
|
|
1726
1732
|
* ```
|
|
1727
1733
|
*/
|
|
1728
|
-
sendMessage({
|
|
1729
|
-
openingMessage?: ConversationApiRequest['openingMessage'];
|
|
1734
|
+
sendMessage({ userMessage, }: {
|
|
1730
1735
|
userMessage: ConversationApiRequest['userMessage'];
|
|
1731
1736
|
}): Promise<Message[] | undefined>;
|
|
1732
1737
|
/**
|
|
@@ -1923,4 +1928,4 @@ declare const setUserId: (userId: string) => void;
|
|
|
1923
1928
|
*/
|
|
1924
1929
|
declare const authMiddleware: (accessToken: string) => Middleware;
|
|
1925
1930
|
|
|
1926
|
-
export { CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type ConversationApiResponse, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
|
1931
|
+
export { type ApiBasicMessage, type ApiConversationIdMessage, CONVERSATION_ID, Client, type Config, type ConversationApiRequest, type ConversationApiResponse, type DebugResponse, type Endpoint, type Identity, type Message, SESSION_ID, TTL, type TrackingEvent, USER_ID, authMiddleware, deleteConversationId, getConversationId, getSessionId, getUserId, setConversationId, setSessionId, setUserId };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var _=Object.create;var a=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var s in e)a(t,s,{get:e[s],enumerable:!0})},C=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of T(e))!b.call(t,n)&&n!==s&&a(t,n,{get:()=>e[n],enumerable:!(i=O(e,n))||i.enumerable});return t};var D=(t,e,s)=>(s=t!=null?_(A(t)):{},C(e||!t||!t.__esModule?a(s,"default",{value:t,enumerable:!0}):s,t)),N=t=>C(a({},"__esModule",{value:!0}),t);var W={};P(W,{CONVERSATION_ID:()=>d,Client:()=>E,SESSION_ID:()=>g,TTL:()=>w,USER_ID:()=>h,authMiddleware:()=>c,deleteConversationId:()=>I,getConversationId:()=>v,getSessionId:()=>f,getUserId:()=>l,setConversationId:()=>p,setSessionId:()=>u,setUserId:()=>x});module.exports=N(W);var S=D(require("openapi-fetch"));var d="__15gifts_conversation_id",I=()=>sessionStorage.removeItem(d),v=()=>sessionStorage.getItem(d),p=t=>sessionStorage.setItem(d,t);var g="__15gifts_session_id",f=()=>sessionStorage.getItem(g),u=t=>sessionStorage.setItem(g,t);var R=t=>{let e=localStorage.getItem(t);if(!e)return null;let s=JSON.parse(e);return Date.now()>s.expires?(localStorage.removeItem(t),null):s.value},m=R;var k=(t,e,s)=>{let i={expires:Date.now()+s,value:e};localStorage.setItem(t,JSON.stringify(i))},y=k;var h="__15gifts_user_id",w=1e3*60*60*24*30,l=()=>m(h),x=t=>y(h,t,w);var U=t=>({onRequest:async({request:e})=>(e.headers.set("Authorization",`Bearer ${t}`),e)}),c=U;var M="0.5.0";var E=class{endpoint;identity;constructor({customerId:e,fetch:s,conversationUrl:i,frontendUrl:n}){let o={"X-SDK-VERSION":M};this.endpoint={conversation:(0,S.default)({baseUrl:i,fetch:s,headers:o}),frontend:(0,S.default)({baseUrl:n,fetch:s,headers:o})},this.identity={customerId:e,conversationId:v()??void 0,sessionId:f()??void 0,userId:l()??void 0}}async createIdentity(){let{conversationId:e,customerId:s,sessionId:i,userId:n}=this.identity;e&&this.endConversation();let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:s,sessionId:i,userId:n}});o&&(i||(this.identity.sessionId=o.sessionId,u(o.sessionId)),n||(this.identity.userId=o.userId,x(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(c(o.token))}))}endConversation(){I(),this.identity.conversationId=void 0}async startConversation(){this.endConversation();let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:{availableProductIds:[]}}}),[s,i]=e,n=s.conversationId;if(!n)throw new Error("Conversation ID not received");return p(n),this.identity.conversationId=n,i}async sendMessage({userMessage:e}){let{data:s}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:e,type:"MESSAGE"}});if(!s)return;if(s.find(r=>r.type==="DEBUG"))throw new Error("Debug record received");let n=s.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return n&&(p(n),this.identity.conversationId=n),s.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(e,s){let i={additionalProperties:s,conversationId:this.identity.conversationId,deviceType:void 0,eventName:e,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}};0&&(module.exports={CONVERSATION_ID,Client,SESSION_ID,TTL,USER_ID,authMiddleware,deleteConversationId,getConversationId,getSessionId,getUserId,setConversationId,setSessionId,setUserId});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/middlewares/auth.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, Endpoint, Identity, Message, TrackingEvent } from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v2')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId ?? '',\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('tab-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","const setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => getItemWithExpiry(USER_ID)\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.4.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,iBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAf,GCAA,IAAAgB,EAAyB,4BCKlB,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,u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,SAAS,eAAiBA,GAGhBG,EAAK,OAAQQ,GAAYA,EAAQ,OAAS,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWE,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","getConversationId","getSessionId","getUserId","setConversationId","setSessionId","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","openingMessage","userMessage","message","setConversationId","eventName","properties","body"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/middlewares/auth.ts","../package.json"],"sourcesContent":["export * from './client'\nexport * from './identity'\nexport * from './middlewares'\nexport * from './types'\n","import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n ApiBasicMessage,\n ApiConversationIdMessage,\n Config,\n ConversationApiRequest,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v2')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n */\n async startConversation(): Promise<ApiBasicMessage | undefined> {\n this.endConversation()\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext: {\n availableProductIds: [],\n },\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ApiConversationIdMessage, ApiBasicMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('tab-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","const setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => getItemWithExpiry(USER_ID)\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.5.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,WAAAC,EAAA,eAAAC,EAAA,QAAAC,EAAA,YAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,iBA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AAI,MAAM,8BAA8B,EAGhD,OAAAW,EAAkBX,CAAc,EAChC,KAAK,SAAS,eAAiBA,EAExBU,CACT,CAsBA,MAAM,YAAY,CAChB,YAAAE,CACF,EAEmC,CACjC,GAAM,CAAE,KAAAT,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,YAAAS,EACA,KAAM,SACR,CACF,CAAC,EAED,GAAI,CAACT,EAAM,OAGX,GADqBA,EAAK,KAAMU,GAAYA,EAAQ,OAAS,OAAO,EAElE,MAAM,IAAI,MAAM,uBAAuB,EAIzC,IAAMb,EAAiBG,EAAK,KAAMU,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIb,IACFW,EAAkBX,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBG,EAAK,OAAQU,GAAYA,EAAQ,OAAS,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWC,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["src_exports","__export","CONVERSATION_ID","Client","SESSION_ID","TTL","USER_ID","auth_default","deleteConversationId","getConversationId","getSessionId","getUserId","setConversationId","setSessionId","setUserId","__toCommonJS","import_openapi_fetch","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","conversationIdMessage","openingMessage","setConversationId","userMessage","message","eventName","properties","body"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import S from"openapi-fetch";var a="__15gifts_conversation_id",v=()=>sessionStorage.removeItem(a),g=()=>sessionStorage.getItem(a),d=s=>sessionStorage.setItem(a,s);var f="__15gifts_session_id",u=()=>sessionStorage.getItem(f),m=s=>sessionStorage.setItem(f,s);var C=s=>{let t=localStorage.getItem(s);if(!t)return null;let e=JSON.parse(t);return Date.now()>e.expires?(localStorage.removeItem(s),null):e.value},p=C;var w=(s,t,e)=>{let i={expires:Date.now()+e,value:t};localStorage.setItem(s,JSON.stringify(i))},c=w;var y="__15gifts_user_id",M=1e3*60*60*24*30,h=()=>p(y),l=s=>c(y,s,M);var _=s=>({onRequest:async({request:t})=>(t.headers.set("Authorization",`Bearer ${s}`),t)}),I=_;var x="0.5.0";var E=class{endpoint;identity;constructor({customerId:t,fetch:e,conversationUrl:i,frontendUrl:n}){let o={"X-SDK-VERSION":x};this.endpoint={conversation:S({baseUrl:i,fetch:e,headers:o}),frontend:S({baseUrl:n,fetch:e,headers:o})},this.identity={customerId:t,conversationId:g()??void 0,sessionId:u()??void 0,userId:h()??void 0}}async createIdentity(){let{conversationId:t,customerId:e,sessionId:i,userId:n}=this.identity;t&&this.endConversation();let{data:o}=await this.endpoint.frontend.POST("/api/tracking/identity/v2",{body:{customerId:e,sessionId:i,userId:n}});o&&(i||(this.identity.sessionId=o.sessionId,m(o.sessionId)),n||(this.identity.userId=o.userId,l(o.userId)),Object.values(this.endpoint).forEach(r=>{r.use(I(o.token))}))}endConversation(){v(),this.identity.conversationId=void 0}async startConversation(){this.endConversation();let{data:t}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{type:"START_CONVERSATION",conversationContext:{availableProductIds:[]}}}),[e,i]=t,n=e.conversationId;if(!n)throw new Error("Conversation ID not received");return d(n),this.identity.conversationId=n,i}async sendMessage({userMessage:t}){let{data:e}=await this.endpoint.conversation.POST("/api/conversation/v3",{body:{conversationId:this.identity.conversationId,userMessage:t,type:"MESSAGE"}});if(!e)return;if(e.find(r=>r.type==="DEBUG"))throw new Error("Debug record received");let n=e.find(r=>r.type==="CONVERSATION_ID")?.conversationId;return n&&(d(n),this.identity.conversationId=n),e.filter(r=>r.type!=="CONVERSATION_ID"&&r.type!=="DEBUG")}async trackEvent(t,e){let i={additionalProperties:e,conversationId:this.identity.conversationId,deviceType:void 0,eventName:t,url:window.location.href,userAgent:window.navigator.userAgent};return this.endpoint.frontend.POST("/api/tracking/user/v2",{body:i})}};export{a as CONVERSATION_ID,E as Client,f as SESSION_ID,M as TTL,y as USER_ID,I as authMiddleware,v as deleteConversationId,g as getConversationId,u as getSessionId,h as getUserId,d as setConversationId,m as setSessionId,l as setUserId};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/middlewares/auth.ts","../package.json"],"sourcesContent":["import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type { Config, ConversationApiRequest, Endpoint, Identity, Message, TrackingEvent } from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v2')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Sends a message in the conversation, optionally with an opening message.\n *\n * @param options - An object containing the opening message and the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * openingMessage: 'Hello! How can I help you?',\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n openingMessage,\n userMessage,\n }: {\n openingMessage?: ConversationApiRequest['openingMessage']\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n if (openingMessage && this.identity.conversationId) {\n this.endConversation()\n }\n\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v2', {\n body: {\n conversationId: this.identity.conversationId,\n customerId: this.identity.customerId,\n openingMessage,\n sessionId: this.identity.sessionId ?? '',\n userId: this.identity.userId,\n userMessage,\n },\n })\n\n if (!data) return undefined\n\n const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('tab-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","const setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => getItemWithExpiry(USER_ID)\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.4.2\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCKlB,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,EChBf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAA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AAK,SAAS,OAASC,EAAK,OAC5BE,EAAUF,EAAK,MAAM,GAGvB,OAAO,OAAO,KAAK,QAAQ,EAAE,QAASG,GAAY,CAChDA,EAAQ,IAAIC,EAAeJ,EAAK,KAAK,CAAC,CACxC,CAAC,EAEL,CAWA,iBAAwB,CACtBK,EAAqB,EACrB,KAAK,SAAS,eAAiB,MACjC,CAuBA,MAAM,YAAY,CAChB,eAAAC,EACA,YAAAC,CACF,EAGmC,CAC7BD,GAAkB,KAAK,SAAS,gBAClC,KAAK,gBAAgB,EAGvB,GAAM,CAAE,KAAAN,CAAK,EAAI,MAAM,KAAK,SAAS,aAAa,KAAK,uBAAwB,CAC7E,KAAM,CACJ,eAAgB,KAAK,SAAS,eAC9B,WAAY,KAAK,SAAS,WAC1B,eAAAM,EACA,UAAW,KAAK,SAAS,WAAa,GACtC,OAAQ,KAAK,SAAS,OACtB,YAAAC,CACF,CACF,CAAC,EAED,GAAI,CAACP,EAAM,OAGX,GADqBA,EAAK,KAAMQ,GAAYA,EAAQ,OAAS,OAAO,EAElE,MAAM,IAAI,MAAM,uBAAuB,EAIzC,IAAMX,EAAiBG,EAAK,KAAMQ,GAAYA,EAAQ,OAAS,iBAAiB,GAAG,eACnF,OAAIX,IACFY,EAAkBZ,CAAc,EAChC,KAAK,SAAS,eAAiBA,GAGhBG,EAAK,OAAQQ,GAAYA,EAAQ,OAAS,mBAAqBA,EAAQ,OAAS,OAAO,CAE1G,CAcA,MAAM,WAAWE,EAAuCC,EAAoD,CAC1G,IAAMC,EAAsB,CAC1B,qBAAsBD,EACtB,eAAgB,KAAK,SAAS,eAC9B,WAAY,OACZ,UAAAD,EACA,IAAK,OAAO,SAAS,KACrB,UAAW,OAAO,UAAU,SAC9B,EAEA,OAAO,KAAK,SAAS,SAAS,KAAK,wBAAyB,CAC1D,KAAAE,CACF,CAAC,CACH,CACF","names":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","openingMessage","userMessage","message","setConversationId","eventName","properties","body"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/identity/conversationId.ts","../src/identity/sessionId.ts","../src/utils/getItemWithExpiry.ts","../src/utils/setItemWithExpiry.ts","../src/identity/userId.ts","../src/middlewares/auth.ts","../package.json"],"sourcesContent":["import createClient from 'openapi-fetch'\n\nimport {\n deleteConversationId,\n getConversationId,\n getSessionId,\n getUserId,\n setConversationId,\n setSessionId,\n setUserId,\n} from './identity'\nimport { authMiddleware } from './middlewares'\nimport type { paths as conversationPaths } from './schemas/conversation'\nimport type { paths as frontendPaths } from './schemas/frontend'\nimport type {\n ApiBasicMessage,\n ApiConversationIdMessage,\n Config,\n ConversationApiRequest,\n Endpoint,\n Identity,\n Message,\n TrackingEvent,\n} from './types'\nimport { version } from '../package.json'\n\n/**\n * The `Client` class provides methods to manage 15gifts API.\n */\nexport class Client {\n /**\n * This can be used to interact with the APIs directly. It is recommended to use the [helper methods](/sdk-reference/classes/client/#methods) provided by the `Client` class instead.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * const { data } = await client.endpoint.conversation.POST('/api/conversation/v2')\n * ```\n */\n endpoint: Endpoint\n\n /**\n * The identity information.\n */\n identity: Identity\n\n /**\n * Creates a new instance of the `Client` class.\n *\n * @param config - Configuration options for initializing the client.\n *\n * @example\n * ```ts\n * const client = new Client({ customerId: 'YOUR_CUSTOMER_ID' })\n * ```\n */\n constructor({ customerId, fetch, conversationUrl, frontendUrl }: Config) {\n const headers = {\n 'X-SDK-VERSION': version,\n }\n\n this.endpoint = {\n conversation: createClient<conversationPaths>({ baseUrl: conversationUrl, fetch, headers }),\n frontend: createClient<frontendPaths>({ baseUrl: frontendUrl, fetch, headers }),\n }\n this.identity = {\n customerId,\n conversationId: getConversationId() ?? undefined,\n sessionId: getSessionId() ?? undefined,\n userId: getUserId() ?? undefined,\n }\n }\n\n /**\n * Creates a new identity for the user by generating a session ID and user ID if they don't exist, and sets the access token for future API calls.\n * Ends the current conversation if a conversation ID is present before sending a request to update identity.\n *\n * @returns A promise that resolves once the identity is created and the access token is set.\n *\n * @example\n * ```ts\n * await client.createIdentity()\n * console.log('Identity created:', client.identity)\n * ```\n */\n async createIdentity(): Promise<void> {\n const { conversationId, customerId, sessionId, userId } = this.identity\n\n if (conversationId) this.endConversation()\n\n const { data } = await this.endpoint.frontend.POST('/api/tracking/identity/v2', {\n body: {\n customerId,\n sessionId,\n userId,\n },\n })\n\n if (data) {\n if (!sessionId) {\n this.identity.sessionId = data.sessionId\n setSessionId(data.sessionId)\n }\n if (!userId) {\n this.identity.userId = data.userId\n setUserId(data.userId)\n }\n\n Object.values(this.endpoint).forEach((endpont) => {\n endpont.use(authMiddleware(data.token))\n })\n }\n }\n\n /**\n * Ends the current conversation by deleting the conversation ID.\n *\n * @example\n * ```ts\n * client.endConversation()\n * console.log('Conversation ended')\n * ```\n */\n endConversation(): void {\n deleteConversationId()\n this.identity.conversationId = undefined\n }\n\n /**\n * Clears the existing conversation ID, then generates a new one and returns the opening message.\n */\n async startConversation(): Promise<ApiBasicMessage | undefined> {\n this.endConversation()\n\n const { data } = await this.endpoint.conversation.POST(`/api/conversation/v3`, {\n body: {\n type: 'START_CONVERSATION',\n conversationContext: {\n availableProductIds: [],\n },\n },\n })\n\n const [conversationIdMessage, openingMessage] = data as [ApiConversationIdMessage, ApiBasicMessage]\n\n const conversationId = conversationIdMessage.conversationId\n if (!conversationId) {\n throw new Error('Conversation ID not received')\n }\n\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n\n return openingMessage\n }\n\n /**\n * Sends a message in the conversation\n *\n * @param options - An object containing the user message.\n * @returns A promise that resolves to an array of messages or debug records.\n * If the message is a debug record, it will throw an error.\n *\n * @example\n * ```ts\n * const newMessages = await client.sendMessage({\n * userMessage: 'How can I get support?',\n * })\n *\n * if (newMessages) {\n * console.log('Received messages:', newMessages)\n * } else {\n * console.log('No message received')\n * }\n * ```\n */\n async sendMessage({\n userMessage,\n }: {\n userMessage: ConversationApiRequest['userMessage']\n }): Promise<Message[] | undefined> {\n const { data } = await this.endpoint.conversation.POST('/api/conversation/v3', {\n body: {\n conversationId: this.identity.conversationId,\n userMessage,\n type: 'MESSAGE',\n },\n })\n\n if (!data) return undefined\n\n const debugMessage = data.find((message) => message.type === 'DEBUG')\n if (debugMessage) {\n throw new Error('Debug record received')\n }\n\n // When a request does not contain a conversation ID, the API will return a new conversation ID as the first message\n const conversationId = data.find((message) => message.type === 'CONVERSATION_ID')?.conversationId\n if (conversationId) {\n setConversationId(conversationId)\n this.identity.conversationId = conversationId\n }\n\n const messages = data.filter((message) => message.type !== 'CONVERSATION_ID' && message.type !== 'DEBUG')\n return messages\n }\n\n /**\n * Sends an event to the tracking API, with the required properties already set.\n *\n * @param eventName - The name of the event to track.\n * @param properties - Additional properties to include in the event.\n * @returns A promise that resolves once the event is tracked.\n *\n * @example\n * ```ts\n * await client.trackEvent('tab-shown')\n * ```\n */\n async trackEvent(eventName: TrackingEvent['eventName'], properties?: TrackingEvent['additionalProperties']) {\n const body: TrackingEvent = {\n additionalProperties: properties,\n conversationId: this.identity.conversationId,\n deviceType: undefined,\n eventName,\n url: window.location.href,\n userAgent: window.navigator.userAgent,\n }\n\n return this.endpoint.frontend.POST('/api/tracking/user/v2', {\n body,\n })\n }\n}\n","/**\n * The key used to store the conversation ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const CONVERSATION_ID = '__15gifts_conversation_id'\n\n/**\n * Deletes the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { deleteConversationId } from '@15gifts/sdk'\n *\n * deleteConversationId()\n * // The conversation ID will be removed.\n * ```\n */\nexport const deleteConversationId = () => sessionStorage.removeItem(CONVERSATION_ID)\n\n/**\n * Retrieves the conversation ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getConversationId } from '@15gifts/sdk'\n *\n * const conversationId = getConversationId()\n *\n * if (conversationId) {\n * console.log(`Conversation ID: ${conversationId}`)\n * } else {\n * console.log('No conversation ID found.')\n * }\n * ```\n */\nexport const getConversationId = () => sessionStorage.getItem(CONVERSATION_ID)\n\n/**\n * Stores the given conversation ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setConversationId } from '@15gifts/sdk'\n *\n * setConversationId('ca0ab4ce-f697-41cc-8d0c-081762aace9b')\n * // The conversation ID 'ca0ab4ce-f697-41cc-8d0c-081762aace9b' will be stored.\n * ```\n */\nexport const setConversationId = (conversationId: string) => sessionStorage.setItem(CONVERSATION_ID, conversationId)\n","/**\n * The key used to store the session ID in `sessionStorage`.\n *\n * @ignore\n */\nexport const SESSION_ID = '__15gifts_session_id'\n\n/**\n * Retrieves the session ID from `sessionStorage`.\n *\n * @example\n * ```ts\n * import { getSessionId } from '@15gifts/sdk'\n *\n * const sessionId = getSessionId()\n *\n * if (sessionId) {\n * console.log(`Session ID: ${sessionId}`)\n * } else {\n * console.log('No session ID found.')\n * }\n * ```\n */\nexport const getSessionId = () => sessionStorage.getItem(SESSION_ID)\n\n/**\n * Stores the given session ID in `sessionStorage`.\n *\n * @example\n * ```ts\n * import { setSessionId } from '@15gifts/sdk'\n *\n * setSessionId('20b2bff6-64a0-4101-bed9-ff545326584a')\n * // The session ID '20b2bff6-64a0-4101-bed9-ff545326584a' will be stored.\n * ```\n */\nexport const setSessionId = (sessionId: string) => sessionStorage.setItem(SESSION_ID, sessionId)\n","const getItemWithExpiry = (key: string) => {\n const itemString = localStorage.getItem(key)\n\n if (!itemString) return null\n\n const item = JSON.parse(itemString) as { expires: number; value: string }\n\n if (Date.now() > item.expires) {\n localStorage.removeItem(key)\n\n return null\n }\n\n return item.value\n}\n\nexport default getItemWithExpiry\n","const setItemWithExpiry = (key: string, value: string, ttl: number) => {\n const item = {\n expires: Date.now() + ttl,\n value,\n }\n\n localStorage.setItem(key, JSON.stringify(item))\n}\n\nexport default setItemWithExpiry\n","import { getItemWithExpiry, setItemWithExpiry } from '../utils'\n\n/**\n * The key used to store the user ID in `localStorage`.\n *\n * @ignore\n */\nexport const USER_ID = '__15gifts_user_id'\n\n/**\n * Time-to-live (TTL) for the user ID in milliseconds.\n * Set to 30 days.\n *\n * @ignore\n */\nexport const TTL = 1000 * 60 * 60 * 24 * 30 // 30 days\n\n/**\n * Retrieves the user ID from `localStorage`.\n *\n * @example\n * ```ts\n * import { getUserId } from '@15gifts/sdk'\n *\n * const userId = getUserId()\n *\n * if (userId) {\n * console.log(`User ID: ${userId}`)\n * } else {\n * console.log('No user ID found.')\n * }\n * ```\n */\nexport const getUserId = () => getItemWithExpiry(USER_ID)\n\n/**\n * Stores the given user ID in `localStorage`.\n *\n * @example\n * ```ts\n * import { setUserId } from '@15gifts/sdk'\n *\n * setUserId('5b77656c-ea4c-492f-82bf-7129297c5873')\n * // The user ID '5b77656c-ea4c-492f-82bf-7129297c5873' will be stored with a 30-day expiry.\n * ```\n */\nexport const setUserId = (userId: string) => setItemWithExpiry(USER_ID, userId, TTL)\n","import type { Middleware } from 'openapi-fetch'\n\n/**\n * Middleware for adding an `Authorization` header to requests.\n *\n * @param accessToken - The token to be included in the `Authorization` header.\n * @returns A middleware object that attaches the access token to the request headers.\n *\n * @example\n * ```ts\n * import { authMiddleware } from '@15gifts/sdk';\n *\n * this.endpoint.conversation.use(authMiddleware(accessToken))\n * ```\n */\nconst authMiddleware = (accessToken: string): Middleware => ({\n onRequest: async ({ request }) => {\n request.headers.set('Authorization', `Bearer ${accessToken}`)\n\n return request\n },\n})\n\nexport default authMiddleware\n","{\n \"name\": \"@15gifts/sdk\",\n \"version\": \"0.5.0\",\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"coverage\": \"vitest run --coverage\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier . --write\",\n \"generate\": \"npx openapi-typescript\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc\"\n },\n \"dependencies\": {\n \"openapi-fetch\": \"^0.12.2\"\n },\n \"devDependencies\": {\n \"openapi-typescript\": \"^7.4.1\",\n \"tsup\": \"^8.3.0\"\n },\n \"sideEffects\": false,\n \"prettier\": \"prettier-config-custom\"\n}\n"],"mappings":"AAAA,OAAOA,MAAkB,gBCKlB,IAAMC,EAAkB,4BAalBC,EAAuB,IAAM,eAAe,WAAWD,CAAe,EAkBtEE,EAAoB,IAAM,eAAe,QAAQF,CAAe,EAahEG,EAAqBC,GAA2B,eAAe,QAAQJ,EAAiBI,CAAc,EC5C5G,IAAMC,EAAa,uBAkBbC,EAAe,IAAM,eAAe,QAAQD,CAAU,EAatDE,EAAgBC,GAAsB,eAAe,QAAQH,EAAYG,CAAS,ECpC/F,IAAMC,EAAqBC,GAAgB,CACzC,IAAMC,EAAa,aAAa,QAAQD,CAAG,EAE3C,GAAI,CAACC,EAAY,OAAO,KAExB,IAAMC,EAAO,KAAK,MAAMD,CAAU,EAElC,OAAI,KAAK,IAAI,EAAIC,EAAK,SACpB,aAAa,WAAWF,CAAG,EAEpB,MAGFE,EAAK,KACd,EAEOC,EAAQJ,EChBf,IAAMK,EAAoB,CAACC,EAAaC,EAAeC,IAAgB,CACrE,IAAMC,EAAO,CACX,QAAS,KAAK,IAAI,EAAID,EACtB,MAAAD,CACF,EAEA,aAAa,QAAQD,EAAK,KAAK,UAAUG,CAAI,CAAC,CAChD,EAEOC,EAAQL,ECFR,IAAMM,EAAU,oBAQVC,EAAM,IAAO,GAAK,GAAK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":["createClient","CONVERSATION_ID","deleteConversationId","getConversationId","setConversationId","conversationId","SESSION_ID","getSessionId","setSessionId","sessionId","getItemWithExpiry","key","itemString","item","getItemWithExpiry_default","setItemWithExpiry","key","value","ttl","item","setItemWithExpiry_default","USER_ID","TTL","getUserId","getItemWithExpiry_default","setUserId","userId","setItemWithExpiry_default","authMiddleware","accessToken","request","auth_default","version","Client","customerId","fetch","conversationUrl","frontendUrl","headers","version","createClient","getConversationId","getSessionId","getUserId","conversationId","sessionId","userId","data","setSessionId","setUserId","endpont","auth_default","deleteConversationId","conversationIdMessage","openingMessage","setConversationId","userMessage","message","eventName","properties","body"]}
|