API Reference
Complete technical reference for the Produck SDK.
Core SDK
createProduck()
Creates a new Produck SDK instance.
function createProduck(config: ProduckConfig): ProduckSDKParameters:
interface ProduckConfig {
sdkKey: string; // Required: Your SDK project key
apiUrl?: string; // Optional: API endpoint
onAction?: (key: string, payload: ActionPayload) => void; // Global action callback
onMessage?: (message: ChatMessage) => void; // Message callback
onError?: (error: Error) => void; // Error callback
}Returns: ProduckSDK instance
Example:
const produck = createProduck({
sdkKey: 'sdk_proj_abc123',
apiUrl: 'https://api.produck.io/api/v1',
onAction: (key, payload) => console.log('Action:', key),
onError: (error) => console.error(error),
});ProduckSDK Class
Methods
init()
Initialize the SDK and create a session.
async init(): Promise<void>Throws: Error if SDK key is invalid or API is unreachable
Example:
try {
await produck.init();
console.log('SDK ready');
} catch (error) {
console.error('Init failed:', error);
}register()
Register an action handler for an operation.
register(actionKey: string, handler: ActionHandler): voidParameters:
actionKey: The operation ID to listen forhandler: Function to call when operation triggers
Example:
produck.register('open-contact', async (payload) => {
await openContactModal();
console.log('Contact modal opened');
});unregister()
Remove an action handler.
unregister(actionKey: string): voidExample:
produck.unregister('open-contact');sendMessage()
Send a user message and receive AI response.
async sendMessage(message: string): Promise<ChatMessage>Parameters:
message: User's message text
Returns: ChatMessage with response and optional action
Example:
const response = await produck.sendMessage('Show pricing');
console.log(response.content);
if (response.action) {
console.log('Triggered:', response.action.name);
}on()
Subscribe to SDK events.
on(eventType: ProduckEventType, handler: Function): voidEvent Types:
'ready'- SDK initialized'action'- Action triggered'message'- New message'error'- Error occurred
Example:
produck.on('ready', () => console.log('Ready!'));
produck.on('action', (payload) => console.log(payload));
produck.on('error', (error) => console.error(error));off()
Unsubscribe from SDK events.
off(eventType: ProduckEventType, handler: Function): voidExample:
const handler = () => console.log('Ready');
produck.on('ready', handler);
produck.off('ready', handler);emit()
Emit an SDK event (advanced usage).
emit(eventType: ProduckEventType, data: any): voidgetSessionToken()
Get current session token.
getSessionToken(): string | nullReturns: Session token or null if not initialized
destroy()
Clean up SDK resources.
destroy(): voidExample:
// Cleanup on app unmount
produck.destroy();React Components
ProduckProvider
Context provider for React applications.
function ProduckProvider(props: ProduckProviderProps): JSX.ElementProps:
interface ProduckProviderProps {
config: {
sdkKey: string;
apiUrl?: string;
};
children: ReactNode;
onAction?: (key: string, payload: ActionPayload) => void;
onError?: (error: Error) => void;
}Example:
<ProduckProvider
config={{ sdkKey: 'your-key' }}
onAction={(key) => console.log(key)}
>
<App />
</ProduckProvider>ProduckChat
Pre-built chat widget component.
function ProduckChat(props: ProduckChatProps): JSX.ElementProps:
interface ProduckChatProps {
position?: 'bottom-right' | 'bottom-left' | 'inline';
theme?: 'light' | 'dark';
primaryColor?: string;
title?: string;
placeholder?: string;
className?: string;
style?: React.CSSProperties;
}Defaults:
position:'bottom-right'theme:'light'primaryColor:'#f97316'title:'Chat Assistant'placeholder:'Ask a question...'
Example:
<ProduckChat
position="bottom-right"
theme="dark"
primaryColor="#8b5cf6"
title="AI Assistant"
/>ProduckTarget
Wrapper component for auto-scroll and highlight.
function ProduckTarget(props: ProduckTargetProps): JSX.ElementProps:
interface ProduckTargetProps {
actionKey: string;
children: ReactNode;
onTrigger?: (payload: ActionPayload) => void;
scrollIntoView?: boolean;
highlightDuration?: number;
highlightStyle?: React.CSSProperties;
}Defaults:
scrollIntoView:truehighlightDuration:3000(ms)
Example:
<ProduckTarget
actionKey="show-pricing"
onTrigger={() => console.log('Viewed')}
highlightDuration={5000}
>
<PricingSection />
</ProduckTarget>React Hooks
useProduck()
Access full SDK context.
function useProduck(): ProduckContextValueReturns:
interface ProduckContextValue {
sdk: ProduckSDK | null;
isReady: boolean;
sessionToken: string | null;
messages: ChatMessage[];
isLoading: boolean;
sendMessage: (message: string) => Promise<void>;
register: (key: string, handler: ActionHandler) => void;
unregister: (key: string) => void;
}Example:
function Component() {
const { isReady, messages, sendMessage } = useProduck();
if (!isReady) return <div>Loading...</div>;
return <div>{messages.length} messages</div>;
}useProduckAction()
Register an action handler.
function useProduckAction(
actionKey: string,
handler: (payload: ActionPayload) => void | Promise<void>,
deps?: React.DependencyList
): voidParameters:
actionKey: Operation ID to listen forhandler: Function to call when triggereddeps: Optional dependency array (likeuseEffect)
Example:
function Component() {
const [count, setCount] = useState(0);
useProduckAction('increment', () => {
setCount(c => c + 1);
}, []);
return <div>Count: {count}</div>;
}useProduckMessages()
Access chat messages and send messages.
function useProduckMessages(): UseProduckMessagesReturnReturns:
interface UseProduckMessagesReturn {
messages: ChatMessage[];
isLoading: boolean;
sendMessage: (message: string) => Promise<void>;
}Example:
function CustomChat() {
const { messages, isLoading, sendMessage } = useProduckMessages();
return (
<div>
{messages.map((msg, i) => (
<div key={i}>{msg.content}</div>
))}
{isLoading && <Spinner />}
</div>
);
}useProduckReady()
Check if SDK is initialized.
function useProduckReady(): booleanReturns: true if SDK is ready, false otherwise
Example:
function Component() {
const isReady = useProduckReady();
return <div>SDK: {isReady ? 'Ready' : 'Loading'}</div>;
}TypeScript Types
ActionPayload
interface ActionPayload {
actionKey: string; // The operation ID
name: string; // Human-readable name
actionType: string; // Action type
actionConfig: Record<string, any>; // Custom configuration
responseMessage?: string; // AI response message
}ChatMessage
interface ChatMessage {
role: 'user' | 'assistant';
content: string;
action?: ActionPayload;
}ActionHandler
type ActionHandler = (payload: ActionPayload) => void | Promise<void>;ProduckEventType
type ProduckEventType = 'action' | 'message' | 'error' | 'ready';ProduckEvent
interface ProduckEvent {
type: ProduckEventType;
data: any;
}Error Types
Initialization Errors
// Missing SDK key
new Error('Either sdkKey or guiderId must be provided')
// API unreachable
new Error('Failed to create session: 500')Runtime Errors
// Send message before init
new Error('SDK not initialized. Call init() first.')
// Network errors
new Error('Failed to send message: 404')API Endpoints
Session Creation
POST /api/v1/sdk/session
X-SDK-Key: sdk_proj_abc123
Response:
{
"session_token": "sess_xyz789"
}Intent Matching
POST /api/v1/sdk/match-intent
X-SDK-Key: sdk_proj_abc123
Content-Type: application/json
{
"userMessage": "show pricing"
}
Response:
{
"matched": true,
"action": {
"actionKey": "show-pricing",
"name": "Show Pricing",
"actionType": "navigation",
"actionConfig": {},
"responseMessage": "Here's our pricing information."
}
}Send Message
POST /api/v1/chat/sessions/:sessionToken/message
Content-Type: application/json
{
"message": "How does this work?"
}
Response:
{
"response": "I can help you navigate the app..."
}Constants
// Default API URL
const DEFAULT_API_URL = 'http://localhost:4001/api/v1';
// Default highlight duration
const DEFAULT_HIGHLIGHT_DURATION = 3000; // ms
// Default chat position
const DEFAULT_CHAT_POSITION = 'bottom-right';