@99xio/xians-sdk-typescript
Version:
A lightweight, framework-agnostic SDK for Agent WebSocket/SignalR communication
205 lines • 6.03 kB
TypeScript
/**
* Rest SDK for HTTP-based chat communication with UserApi endpoints
*/
import { Message, BaseMessageRequest, BaseSDKOptions, AuthType } from './types';
/**
* Rest request structure for HTTP communication
* Similar to MessageRequest but tailored for REST endpoints
*/
export interface RestMessageRequest extends BaseMessageRequest {
timeoutSeconds?: number;
}
/**
* Response structure for REST endpoints
*/
export interface RestResponse<T = any> {
success: boolean;
data?: T;
error?: string;
statusCode?: number;
}
/**
* History request parameters
*/
export interface HistoryRequest {
workflow: string;
participantId: string;
page?: number;
pageSize?: number;
scope?: string;
}
/**
* Configuration options for the Rest SDK
*
* @example
* ```typescript
* const restSDK = new RestSDK({
* tenantId: 'my-tenant',
* apiKey: 'sk-123',
* serverUrl: 'https://api.example.com'
* });
* ```
*/
export interface RestSDKOptions extends BaseSDKOptions {
/**
* Request timeout in milliseconds (default: 30000)
*/
requestTimeout?: number;
/**
* Default timeout for converse operations in seconds (default: 60)
*/
defaultConverseTimeout?: number;
/**
* Maximum timeout for converse operations in seconds (default: 300)
*/
maxConverseTimeout?: number;
}
/**
* Rest SDK class for HTTP-based chat communication
*/
export declare class RestSDK {
private options;
private isDisposed;
constructor(options: RestSDKOptions);
/**
* Get JWT token for Authorization header
* @returns JWT token
*/
private getJwtToken;
/**
* Builds query parameters for requests
*/
private buildQueryParams;
/**
* Makes an HTTP request with authentication and error handling
* Supports multiple authentication methods: apikey query param, Authorization header, or access_token query param fallback
* Can use both API key and JWT simultaneously when both are provided
*/
private makeRequest;
/**
* Sends a message to a workflow without waiting for response
*/
send(request: RestMessageRequest): Promise<RestResponse<any>>;
/**
* Sends a message to a workflow and waits synchronously for response
*/
converse(request: RestMessageRequest): Promise<RestResponse<Message[]>>;
/**
* Gets conversation history for a workflow and participant
*/
getHistory(request: HistoryRequest): Promise<RestResponse<Message[]>>;
/**
* Gets the tenant ID
*/
getTenantId(): string;
/**
* Gets the authentication type being used
* When both API key and JWT methods are provided, JWT takes precedence
*/
getAuthType(): AuthType;
/**
* Updates the API key (switches to API key authentication)
*/
updateApiKey(apiKey: string): void;
/**
* Updates the JWT token (switches to JWT token authentication)
*/
updateJwtToken(jwtToken: string): void;
/**
* Updates the JWT token callback (switches to JWT callback authentication)
*/
updateJwtTokenCallback(getJwtToken: () => Promise<string> | string): void;
/**
* Disposes the SDK and cleans up resources
*/
dispose(): void;
}
/**
* Example usage:
*
* ```typescript
* // Option 1: Create Rest SDK with API key authentication
* const restSDKWithApiKey = new RestSDK({
* tenantId: 'my-tenant-123',
* apiKey: 'sk-1234567890',
* serverUrl: 'http://localhost:5000',
* namespace: 'MyApp',
* logger: (level, message, data) => {
* console.log(`[${level.toUpperCase()}] ${message}`, data || '');
* }
* });
*
* // Option 2: Create Rest SDK with callback-based JWT authentication (recommended)
* const restSDKWithCallback = new RestSDK({
* tenantId: 'my-tenant-123',
* serverUrl: 'http://localhost:5000',
* getJwtToken: async () => {
* const response = await fetch('/api/auth/token');
* const { token } = await response.json();
* return token;
* }
* });
*
* // Option 3: Create Rest SDK with combined authentication (API key + JWT)
* // JWT takes precedence for primary auth, API key can be used as fallback or for specific scenarios
* const restSDKWithBoth = new RestSDK({
* tenantId: 'my-tenant-123',
* apiKey: 'sk-fallback-key',
* serverUrl: 'http://localhost:5000',
* getJwtToken: async () => {
* // Primary authentication method (sent in Authorization header)
* const response = await fetch('/api/auth/token');
* const { token } = await response.json();
* return token;
* }
* });
*
* // Send a message without waiting for response
* const sendResult = await restSDKWithCallback.send({
* workflow: 'customer-support',
* type: 'Chat',
* participantId: 'user-123',
* text: 'Hello, I need help with my order',
* data: { priority: 'high' }
* });
*
* if (sendResult.success) {
* console.log('Message sent successfully');
* } else {
* console.error('Failed to send message:', sendResult.error);
* }
*
* // Send a message and wait for response
* const converseResult = await restSDKWithCallback.converse({
* workflow: 'customer-support',
* type: 'Chat',
* participantId: 'user-123',
* text: 'What is my order status?',
* timeoutSeconds: 30
* });
*
* if (converseResult.success && converseResult.data) {
* console.log('Received responses:', converseResult.data);
* } else {
* console.error('Conversation failed:', converseResult.error);
* }
*
* // Get conversation history
* const historyResult = await restSDKWithCallback.getHistory({
* workflow: 'customer-support',
* participantId: 'user-123',
* page: 1,
* pageSize: 20,
* scope: 'support'
* });
*
* if (historyResult.success && historyResult.data) {
* console.log('History loaded:', historyResult.data.length, 'messages');
* }
*
* // Clean up when done
* restSDKWithCallback.dispose();
* ```
*/
export default RestSDK;
//# sourceMappingURL=RestSDK.d.ts.map