@yourgpt/widget-web-sdk
Version:
Official YourGPT SDK for JavaScript/TypeScript and React applications
386 lines (375 loc) • 10.4 kB
text/typescript
declare enum WidgetRenderModeE {
floating = "floating",
embedded = "embedded",
iframe = "iframe"
}
/**
* Core Types for YourGPT SDK
*/
interface YourGPTConfig {
widgetId: string;
endpoint?: string;
autoLoad?: boolean;
debug?: boolean;
whitelabel?: boolean;
mode?: WidgetRenderModeE;
}
interface WidgetState {
isOpen: boolean;
isVisible: boolean;
isConnected: boolean;
isLoaded: boolean;
lastMessageId?: string;
messageCount: number;
connectionRetries: number;
}
type EventHandler<T = any> = (data: T) => void;
type EventUnsubscriber = () => void;
declare class YourGPTError extends Error {
code?: string | undefined;
constructor(message: string, code?: string | undefined);
}
/**
* YourGPT SDK Types
*/
interface MessageData {
id: string;
content: string;
timestamp: string;
sender: "user" | "bot" | "agent";
metadata?: Record<string, any>;
}
interface EscalationData {
mode: string;
modeKey: string;
timestamp: string;
reason?: string;
agentId?: string;
}
interface GameOptions {
showExitConfirmation?: boolean;
leadCapture?: boolean;
gameConfig?: Record<string, any>;
}
interface SessionData {
[key: string]: any;
}
interface VisitorData {
[key: string]: any;
}
interface ContactData {
email?: string;
phone?: string;
name?: string;
user_hash?: string;
[key: string]: any;
}
interface AIActionData {
action: {
tool?: {
function?: {
arguments: string;
name: string;
};
};
id: string;
};
session_data: {
session_uid: number;
[key: string]: any;
};
session_uid: number;
message_id: any;
}
interface AIActionHelpers {
respond: (message: string) => void;
confirm: (options: ConfirmOptions) => Promise<boolean>;
}
interface ConfirmOptions {
title: string;
description: string;
acceptLabel?: string;
rejectLabel?: string;
}
type AIActionHandler = (data: AIActionData, helpers: AIActionHelpers) => Promise<void> | void;
interface WidgetControls {
open: () => void;
close: () => void;
toggle: () => void;
show: () => void;
hide: () => void;
}
interface MessagingControls {
sendMessage: (text: string, autoSend?: boolean) => void;
}
interface AdvancedFeatures {
openBottomSheet: (url: string) => void;
startGame: (gameId: string, options?: GameOptions) => void;
}
interface DataManagement {
setSessionData: (data: SessionData) => void;
setVisitorData: (data: VisitorData) => void;
setContactData: (data: ContactData) => void;
}
interface EventListeners {
onInit: (callback: EventHandler<void>) => EventUnsubscriber;
onMessageReceived: (callback: EventHandler<MessageData>) => EventUnsubscriber;
onEscalatedToHuman: (callback: EventHandler<EscalationData>) => EventUnsubscriber;
onWidgetPopup: (callback: EventHandler<boolean>) => EventUnsubscriber;
}
interface ChatbotAPI extends WidgetState, WidgetControls, MessagingControls, AdvancedFeatures, DataManagement, EventListeners {
}
interface AIActionsAPI {
registerAction: (actionName: string, handler: AIActionHandler) => void;
unregisterAction: (actionName: string) => void;
registerActions: (actions: Record<string, AIActionHandler>) => void;
getRegisteredActions: () => string[];
registeredActions: string[];
}
declare global {
interface Window {
$yourgptChatbot?: {
q?: any[];
execute?: (action: string, ...args: any[]) => void;
on?: (event: string, callback: Function) => void;
off?: (event: string, callback?: Function) => void;
set?: (key: string, value: any) => void;
push?: (action: any[]) => void;
WIDGET_ENDPOINT?: string;
};
YOURGPT_WIDGET_UID?: string;
YGC_WIDGET_RENDER_MODE: WidgetRenderModeE;
}
}
/**
* YourGPT SDK Utilities
*/
/**
* Check if we're in a browser environment
*/
declare const isBrowser: () => boolean;
/**
* Check if we're in a development environment
*/
declare const isDevelopment: () => boolean;
/**
* Create a debug logger that only logs in development
*/
declare const createDebugLogger: (namespace: string) => {
log: (message: string, ...args: any[]) => void;
warn: (message: string, ...args: any[]) => void;
error: (message: string, ...args: any[]) => void;
};
/**
* Wait for a condition to be true
*/
declare const waitFor: (condition: () => boolean, timeout?: number, interval?: number) => Promise<void>;
/**
* Retry a function with exponential backoff
*/
declare const withRetry: <T>(operation: () => Promise<T>, maxRetries?: number, baseDelay?: number) => Promise<T>;
/**
* Deep merge objects
*/
declare const deepMerge: <T extends Record<string, any>>(target: T, source: Partial<T>) => T;
/**
* Generate a unique ID
*/
declare const generateId: () => string;
/**
* Validate widget ID format
*/
declare const validateWidgetId: (widgetId: string) => boolean;
/**
* Validate URL format
*/
declare const validateUrl: (url: string) => boolean;
/**
* Sanitize HTML content
*/
declare const sanitizeHtml: (html: string) => string;
/**
* Debounce function
*/
declare const debounce: <T extends (...args: any[]) => any>(func: T, wait: number) => ((...args: Parameters<T>) => void);
/**
* Throttle function
*/
declare const throttle: <T extends (...args: any[]) => any>(func: T, wait: number) => ((...args: Parameters<T>) => void);
/**
* Check if element is in viewport
*/
declare const isInViewport: (element: Element) => boolean;
/**
* Load external script
*/
declare const loadScript: (src: string, async?: boolean) => Promise<void>;
/**
* Load external CSS
*/
declare const loadCSS: (href: string) => Promise<void>;
/**
* Event emitter utility
*/
declare class EventEmitter<T extends Record<string, any>> {
private events;
on<K extends keyof T>(event: K, callback: (data: T[K]) => void): () => void;
off<K extends keyof T>(event: K, callback?: (data: T[K]) => void): void;
emit<K extends keyof T>(event: K, data: T[K]): void;
removeAllListeners(): void;
}
/**
* YourGPT Core SDK
*/
interface YourGPTEvents {
stateChange: WidgetState;
init: void;
messageReceived: MessageData;
escalatedToHuman: EscalationData;
widgetPopup: boolean;
}
/**
* Main YourGPT SDK class
*/
declare class YourGPTSDK extends EventEmitter<YourGPTEvents> {
private static instance;
private config;
private isInitialized;
private logger;
private state;
private aiActionHandlers;
private constructor();
/**
* Get singleton instance
*/
static getInstance(): YourGPTSDK;
/**
* Initialize the SDK
*/
init(config: YourGPTConfig): Promise<YourGPTSDK>;
/**
* Validate configuration
*/
private validateConfig;
/**
* Set up global variables
*/
private setupGlobalVariables;
/**
* Get endpoint URL
*/
private getEndpoint;
/**
* Load widget assets
*/
private loadWidget;
/**
* Create root container for widget
*/
private createRootContainer;
/**
* Check if widget is ready
*/
private isWidgetReady;
/**
* Set up global API for backwards compatibility
*/
private setupGlobalAPI;
/**
* Update widget state
*/
private updateState;
/**
* Execute widget command
*/
private executeCommand;
/**
* Register event listener
*/
private registerEventListener;
/**
* Set widget data
*/
private setWidgetData;
/**
* Get current configuration
*/
getConfig(): YourGPTConfig | null;
/**
* Get current state
*/
getState(): WidgetState;
/**
* Check if SDK is initialized
*/
isReady(): boolean;
/**
* Widget Controls
*/
open(): void;
close(): void;
toggle(): void;
show(): void;
hide(): void;
/**
* Messaging
*/
sendMessage(text: string, autoSend?: boolean): void;
/**
* Advanced Features
*/
openBottomSheet(url: string): void;
startGame(gameId: string, options?: GameOptions): void;
/**
* Data Management
*/
setSessionData(data: SessionData): void;
setVisitorData(data: VisitorData): void;
setContactData(data: ContactData): void;
/**
* Event Listeners
*/
onInit(callback: EventHandler<void>): EventUnsubscriber;
onMessageReceived(callback: EventHandler<MessageData>): EventUnsubscriber;
onEscalatedToHuman(callback: EventHandler<EscalationData>): EventUnsubscriber;
onWidgetPopup(callback: EventHandler<boolean>): EventUnsubscriber;
/**
* AI Actions
*/
registerAIAction(actionName: string, handler: AIActionHandler): void;
unregisterAIAction(actionName: string): void;
getRegisteredAIActions(): string[];
/**
* Create complete chatbot API
*/
createChatbotAPI(): ChatbotAPI;
/**
* Create AI Actions API
*/
createAIActionsAPI(): AIActionsAPI;
/**
* Cleanup
*/
destroy(): void;
}
/**
* Static methods for easier usage
*/
declare const YourGPT: {
/**
* Initialize the SDK
*/
init: (config: YourGPTConfig) => Promise<YourGPTSDK>;
/**
* Get the SDK instance
*/
getInstance: () => YourGPTSDK;
};
/**
* YourGPT SDK - Main Entry Point
*
* This is the core SDK that works with vanilla JavaScript/TypeScript
* For React-specific functionality, use @yourgpt/sdk/react
*/
declare const VERSION = "1.0.0";
export { type AIActionData, type AIActionHandler, type AIActionHelpers, type AIActionsAPI, type AdvancedFeatures, type ChatbotAPI, type ConfirmOptions, type ContactData, type DataManagement, type EscalationData, EventEmitter, type EventHandler, type EventListeners, type EventUnsubscriber, type GameOptions, type MessageData, type MessagingControls, type SessionData, VERSION, type VisitorData, type WidgetControls, WidgetRenderModeE, type WidgetState, YourGPT, type YourGPTConfig, YourGPTError, YourGPTSDK, createDebugLogger, debounce, deepMerge, YourGPT as default, generateId, isBrowser, isDevelopment, isInViewport, loadCSS, loadScript, sanitizeHtml, throttle, validateUrl, validateWidgetId, waitFor, withRetry };