@botzki/react 0.0.0-stage → 0.1.1
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/README.md +188 -2
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +426 -0
- package/dist/index.d.ts +426 -0
- package/dist/index.mjs +4 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import React__default from 'react';
|
|
3
|
+
import { Citation, ChatResponse, Botzki, BotzkiUser, WidgetOptions } from '@botzki/js';
|
|
4
|
+
export { BotzkiConfig, BotzkiUser, ChatOptions, ChatResponse, Citation, WidgetOptions } from '@botzki/js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Message representation inside React chat interfaces.
|
|
8
|
+
*/
|
|
9
|
+
interface BotzkiMessage {
|
|
10
|
+
id: string;
|
|
11
|
+
role: "user" | "assistant" | "system";
|
|
12
|
+
content: string;
|
|
13
|
+
createdAt: Date;
|
|
14
|
+
citations?: Citation[];
|
|
15
|
+
isStreaming?: boolean;
|
|
16
|
+
error?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Configuration options for the `useChat` hook.
|
|
20
|
+
*/
|
|
21
|
+
interface UseChatOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Target bot identifier. Inherited from `<BotzkiProvider>` if omitted.
|
|
24
|
+
*/
|
|
25
|
+
botId?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Publishable API key. Inherited from `<BotzkiProvider>` if omitted.
|
|
28
|
+
*/
|
|
29
|
+
publishableKey?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Custom backend API base URL (e.g. for local development or custom proxy).
|
|
32
|
+
*/
|
|
33
|
+
baseUrl?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Alias for `baseUrl`.
|
|
36
|
+
*/
|
|
37
|
+
apiHost?: string;
|
|
38
|
+
/**
|
|
39
|
+
* Unique session identifier. Auto-generated and persisted if omitted.
|
|
40
|
+
*/
|
|
41
|
+
sessionId?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Initial messages to preload into the conversation.
|
|
44
|
+
*/
|
|
45
|
+
initialMessages?: BotzkiMessage[];
|
|
46
|
+
/**
|
|
47
|
+
* Whether to persist the conversation and session in browser localStorage.
|
|
48
|
+
* @default true
|
|
49
|
+
*/
|
|
50
|
+
persistSession?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Custom localStorage key prefix for session and message caching.
|
|
53
|
+
*/
|
|
54
|
+
storageKey?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Preferred ISO 639-1 language code (e.g. 'en', 'es', 'de').
|
|
57
|
+
*/
|
|
58
|
+
language?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Whether to stream answers in real-time token-by-token.
|
|
61
|
+
* @default true
|
|
62
|
+
*/
|
|
63
|
+
stream?: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Callback fired whenever a full response is received from the bot.
|
|
66
|
+
*/
|
|
67
|
+
onResponse?: (response: ChatResponse) => void;
|
|
68
|
+
/**
|
|
69
|
+
* Callback fired when a message turn finishes (streaming completed).
|
|
70
|
+
*/
|
|
71
|
+
onFinish?: (message: BotzkiMessage) => void;
|
|
72
|
+
/**
|
|
73
|
+
* Callback fired when an error occurs during message transmission.
|
|
74
|
+
*/
|
|
75
|
+
onError?: (error: Error) => void;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Return type and state of the `useChat` hook.
|
|
79
|
+
*/
|
|
80
|
+
interface UseChatReturn {
|
|
81
|
+
/**
|
|
82
|
+
* Array of conversation messages in chronological order.
|
|
83
|
+
*/
|
|
84
|
+
messages: BotzkiMessage[];
|
|
85
|
+
/**
|
|
86
|
+
* Current text in the input box.
|
|
87
|
+
*/
|
|
88
|
+
input: string;
|
|
89
|
+
/**
|
|
90
|
+
* Sets input box value manually.
|
|
91
|
+
*/
|
|
92
|
+
setInput: (value: string) => void;
|
|
93
|
+
/**
|
|
94
|
+
* Standard React onChange handler for input and textarea elements.
|
|
95
|
+
*/
|
|
96
|
+
handleInputChange: (e: React__default.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
|
|
97
|
+
/**
|
|
98
|
+
* Form submission handler. Submits current `input` and clears the input box.
|
|
99
|
+
*/
|
|
100
|
+
handleSubmit: (e?: React__default.FormEvent, options?: {
|
|
101
|
+
imageBase64?: string;
|
|
102
|
+
imageMimeType?: string;
|
|
103
|
+
}) => Promise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Programmatically sends a message with optional image attachment.
|
|
106
|
+
*/
|
|
107
|
+
sendMessage: (content: string, options?: {
|
|
108
|
+
imageBase64?: string;
|
|
109
|
+
imageMimeType?: string;
|
|
110
|
+
}) => Promise<void>;
|
|
111
|
+
/**
|
|
112
|
+
* Appends a message to the conversation history without triggering an API call.
|
|
113
|
+
*/
|
|
114
|
+
append: (message: Partial<BotzkiMessage> & {
|
|
115
|
+
content: string;
|
|
116
|
+
}) => void;
|
|
117
|
+
/**
|
|
118
|
+
* Re-sends the last user message to regenerate the assistant response.
|
|
119
|
+
*/
|
|
120
|
+
reload: () => Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* Aborts the active streaming generation immediately.
|
|
123
|
+
*/
|
|
124
|
+
stop: () => void;
|
|
125
|
+
/**
|
|
126
|
+
* Clears the current conversation history.
|
|
127
|
+
*/
|
|
128
|
+
clearMessages: () => void;
|
|
129
|
+
/**
|
|
130
|
+
* Direct state setter for messages array.
|
|
131
|
+
*/
|
|
132
|
+
setMessages: React__default.Dispatch<React__default.SetStateAction<BotzkiMessage[]>>;
|
|
133
|
+
/**
|
|
134
|
+
* True if waiting for a response or streaming tokens.
|
|
135
|
+
*/
|
|
136
|
+
isLoading: boolean;
|
|
137
|
+
/**
|
|
138
|
+
* True specifically when tokens are actively streaming in.
|
|
139
|
+
*/
|
|
140
|
+
isStreaming: boolean;
|
|
141
|
+
/**
|
|
142
|
+
* Error object if the last operation failed, or null.
|
|
143
|
+
*/
|
|
144
|
+
error: Error | null;
|
|
145
|
+
/**
|
|
146
|
+
* Active conversation session identifier.
|
|
147
|
+
*/
|
|
148
|
+
sessionId: string;
|
|
149
|
+
/**
|
|
150
|
+
* Sets or updates active conversation session identifier.
|
|
151
|
+
*/
|
|
152
|
+
setSessionId: (id: string) => void;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Properties for `<BotzkiProvider>`.
|
|
156
|
+
*/
|
|
157
|
+
interface BotzkiProviderProps {
|
|
158
|
+
/**
|
|
159
|
+
* Target bot identifier.
|
|
160
|
+
*/
|
|
161
|
+
botId: string;
|
|
162
|
+
/**
|
|
163
|
+
* Publishable API key (`botz_pk_live_...`). Safe to expose in frontend bundles.
|
|
164
|
+
*/
|
|
165
|
+
publishableKey: string;
|
|
166
|
+
/**
|
|
167
|
+
* Optional custom backend API base URL (defaults to https://api.botzki.com).
|
|
168
|
+
*/
|
|
169
|
+
baseUrl?: string;
|
|
170
|
+
/**
|
|
171
|
+
* Alias for `baseUrl`.
|
|
172
|
+
*/
|
|
173
|
+
apiHost?: string;
|
|
174
|
+
/**
|
|
175
|
+
* Optional visitor user details to identify customer sessions.
|
|
176
|
+
*/
|
|
177
|
+
user?: BotzkiUser;
|
|
178
|
+
/**
|
|
179
|
+
* Optional persistent session ID. Auto-generated if omitted.
|
|
180
|
+
*/
|
|
181
|
+
defaultSessionId?: string;
|
|
182
|
+
/**
|
|
183
|
+
* Optional pre-instantiated Botzki client instance.
|
|
184
|
+
*/
|
|
185
|
+
client?: Botzki;
|
|
186
|
+
/**
|
|
187
|
+
* React tree to wrap with Botzki context.
|
|
188
|
+
*/
|
|
189
|
+
children: React__default.ReactNode;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Value exposed by the Botzki React Context.
|
|
193
|
+
*/
|
|
194
|
+
interface BotzkiContextValue {
|
|
195
|
+
client: Botzki;
|
|
196
|
+
botId: string;
|
|
197
|
+
publishableKey: string;
|
|
198
|
+
baseUrl: string;
|
|
199
|
+
apiHost: string;
|
|
200
|
+
user?: BotzkiUser;
|
|
201
|
+
sessionId: string;
|
|
202
|
+
setSessionId: (id: string) => void;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Imperative handle exposed via React ref for `<BotzkiWidget />`.
|
|
206
|
+
*/
|
|
207
|
+
interface BotzkiWidgetRef {
|
|
208
|
+
/** Opens the floating chat popup */
|
|
209
|
+
open: () => void;
|
|
210
|
+
/** Closes the floating chat popup */
|
|
211
|
+
close: () => void;
|
|
212
|
+
/** Toggles open / close state */
|
|
213
|
+
toggle: () => void;
|
|
214
|
+
/** Returns true if the chat popup is currently open */
|
|
215
|
+
isOpen: () => boolean;
|
|
216
|
+
/** Shows the floating launcher bubble */
|
|
217
|
+
show: () => void;
|
|
218
|
+
/** Hides the floating launcher bubble */
|
|
219
|
+
hide: () => void;
|
|
220
|
+
/** Sends a message programmatically through the widget */
|
|
221
|
+
sendMessage: (message: string, imageBase64?: string) => Promise<void>;
|
|
222
|
+
/** Clears widget chat history */
|
|
223
|
+
clearMessages: () => void;
|
|
224
|
+
/** Dynamically updates widget theme */
|
|
225
|
+
setTheme: (theme: "light" | "dark" | "auto") => void;
|
|
226
|
+
/** Dynamically updates widget primary accent color */
|
|
227
|
+
setPrimaryColor: (color: string) => void;
|
|
228
|
+
/** Updates identified visitor details */
|
|
229
|
+
setUser: (user: BotzkiUser) => void;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Props for `<BotzkiWidget />`.
|
|
233
|
+
*/
|
|
234
|
+
interface BotzkiWidgetProps extends WidgetOptions {
|
|
235
|
+
/**
|
|
236
|
+
* Optional bot ID. If omitted, uses value from `<BotzkiProvider>`.
|
|
237
|
+
*/
|
|
238
|
+
botId?: string;
|
|
239
|
+
/**
|
|
240
|
+
* Optional publishable key. If omitted, uses value from `<BotzkiProvider>`.
|
|
241
|
+
*/
|
|
242
|
+
publishableKey?: string;
|
|
243
|
+
/**
|
|
244
|
+
* Optional custom base URL.
|
|
245
|
+
*/
|
|
246
|
+
baseUrl?: string;
|
|
247
|
+
/**
|
|
248
|
+
* Optional visitor details.
|
|
249
|
+
*/
|
|
250
|
+
user?: BotzkiUser;
|
|
251
|
+
/**
|
|
252
|
+
* Callback fired when the widget chat window opens.
|
|
253
|
+
*/
|
|
254
|
+
onOpen?: () => void;
|
|
255
|
+
/**
|
|
256
|
+
* Callback fired when the widget chat window closes.
|
|
257
|
+
*/
|
|
258
|
+
onClose?: () => void;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Root context provider for Botzki AI. Wraps your React component tree and shares
|
|
263
|
+
* client instances and configuration with all child hooks and components.
|
|
264
|
+
*/
|
|
265
|
+
declare function BotzkiProvider({ botId, publishableKey, baseUrl, apiHost, user, defaultSessionId, client: customClient, children, }: BotzkiProviderProps): React.JSX.Element;
|
|
266
|
+
/**
|
|
267
|
+
* Hook to access the current Botzki context value (client instance, botId, sessionId).
|
|
268
|
+
* Throws a helpful error if used outside a `<BotzkiProvider>`.
|
|
269
|
+
*/
|
|
270
|
+
declare function useBotzki(): BotzkiContextValue;
|
|
271
|
+
/**
|
|
272
|
+
* Optional hook to access the Botzki context, returning null instead of throwing
|
|
273
|
+
* if called outside `<BotzkiProvider>`. Useful for components that can be used standalone.
|
|
274
|
+
*/
|
|
275
|
+
declare function useOptionalBotzki(): BotzkiContextValue | null;
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Drop-in floating chat widget component for React.
|
|
279
|
+
* Implemented as a native, zero-dependency React floating modal and launcher button.
|
|
280
|
+
* Supports React StrictMode, responsive layouts, portals, themes, custom colors,
|
|
281
|
+
* and complete imperative control via ref.
|
|
282
|
+
*/
|
|
283
|
+
declare const BotzkiWidget: React.ForwardRefExoticComponent<BotzkiWidgetProps & React.RefAttributes<BotzkiWidgetRef>>;
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Headless React hook for building rich, interactive AI chat interfaces with real-time streaming,
|
|
287
|
+
* session persistence, optimistic UI updates, error recovery, and multimodal support.
|
|
288
|
+
*/
|
|
289
|
+
declare function useChat(options?: UseChatOptions): UseChatReturn;
|
|
290
|
+
|
|
291
|
+
interface BotzkiChatProps extends UseChatOptions {
|
|
292
|
+
/**
|
|
293
|
+
* Title shown in the chat window header. Defaults to bot name or "AI Assistant".
|
|
294
|
+
*/
|
|
295
|
+
title?: string;
|
|
296
|
+
/**
|
|
297
|
+
* Subtitle shown in the chat window header. Defaults to "Online".
|
|
298
|
+
*/
|
|
299
|
+
subtitle?: string;
|
|
300
|
+
/**
|
|
301
|
+
* Welcome greeting when conversation starts.
|
|
302
|
+
*/
|
|
303
|
+
greeting?: string;
|
|
304
|
+
/**
|
|
305
|
+
* List of clickable starter prompt questions.
|
|
306
|
+
*/
|
|
307
|
+
starterQuestions?: string[];
|
|
308
|
+
/**
|
|
309
|
+
* Visual theme ("light" | "dark" | "auto"). Defaults to "auto".
|
|
310
|
+
*/
|
|
311
|
+
theme?: "light" | "dark" | "auto";
|
|
312
|
+
/**
|
|
313
|
+
* Primary accent color (hex or rgb). Defaults to "#0ea5e9".
|
|
314
|
+
*/
|
|
315
|
+
primaryColor?: string;
|
|
316
|
+
/**
|
|
317
|
+
* Custom CSS class name for the outer container.
|
|
318
|
+
*/
|
|
319
|
+
className?: string;
|
|
320
|
+
/**
|
|
321
|
+
* Custom style object for the outer container.
|
|
322
|
+
*/
|
|
323
|
+
style?: React__default.CSSProperties;
|
|
324
|
+
/**
|
|
325
|
+
* Placeholder text for the message input.
|
|
326
|
+
*/
|
|
327
|
+
placeholder?: string;
|
|
328
|
+
/**
|
|
329
|
+
* Optional close button callback for header.
|
|
330
|
+
*/
|
|
331
|
+
onClose?: () => void;
|
|
332
|
+
/**
|
|
333
|
+
* Whether to display the close button in the header.
|
|
334
|
+
*/
|
|
335
|
+
showCloseButton?: boolean;
|
|
336
|
+
/**
|
|
337
|
+
* Whether to display the clear messages button. Defaults to true.
|
|
338
|
+
*/
|
|
339
|
+
showClearButton?: boolean;
|
|
340
|
+
/**
|
|
341
|
+
* Optional external chat instance from useChat().
|
|
342
|
+
*/
|
|
343
|
+
chat?: ReturnType<typeof useChat>;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Embedded, full-featured AI chat container for dashboards, sidebars, and dedicated support pages.
|
|
347
|
+
* Fully responsive and self-contained with no external CSS dependencies.
|
|
348
|
+
*/
|
|
349
|
+
declare function BotzkiChat({ title, subtitle, greeting, starterQuestions, theme, primaryColor, className, style, placeholder, onClose, showCloseButton, showClearButton, chat: externalChat, ...chatOptions }: BotzkiChatProps): React__default.JSX.Element;
|
|
350
|
+
|
|
351
|
+
interface BotInfoData {
|
|
352
|
+
id?: string;
|
|
353
|
+
name?: string;
|
|
354
|
+
description?: string;
|
|
355
|
+
primaryColor?: string;
|
|
356
|
+
theme?: string;
|
|
357
|
+
avatarUrl?: string;
|
|
358
|
+
greeting?: string;
|
|
359
|
+
starterQuestions?: string[];
|
|
360
|
+
capabilities?: string[];
|
|
361
|
+
[key: string]: unknown;
|
|
362
|
+
}
|
|
363
|
+
interface UseBotInfoReturn {
|
|
364
|
+
data: BotInfoData | null;
|
|
365
|
+
isLoading: boolean;
|
|
366
|
+
error: Error | null;
|
|
367
|
+
refetch: () => Promise<void>;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Hook to retrieve public bot configuration, branding, avatar, and starter questions.
|
|
371
|
+
*/
|
|
372
|
+
declare function useBotInfo(): UseBotInfoReturn;
|
|
373
|
+
|
|
374
|
+
interface FeedbackPayload {
|
|
375
|
+
messageId?: string;
|
|
376
|
+
query?: string;
|
|
377
|
+
rating: number;
|
|
378
|
+
comment?: string;
|
|
379
|
+
category?: string;
|
|
380
|
+
}
|
|
381
|
+
interface UseFeedbackReturn {
|
|
382
|
+
submitFeedback: (payload: FeedbackPayload) => Promise<boolean>;
|
|
383
|
+
isSubmitting: boolean;
|
|
384
|
+
isSuccess: boolean;
|
|
385
|
+
error: Error | null;
|
|
386
|
+
reset: () => void;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Hook to submit visitor ratings and feedback on bot answers.
|
|
390
|
+
*/
|
|
391
|
+
declare function useFeedback(): UseFeedbackReturn;
|
|
392
|
+
|
|
393
|
+
interface LeadCapturePayload {
|
|
394
|
+
email: string;
|
|
395
|
+
name?: string;
|
|
396
|
+
phone?: string;
|
|
397
|
+
company?: string;
|
|
398
|
+
notes?: string;
|
|
399
|
+
metadata?: Record<string, unknown>;
|
|
400
|
+
customData?: Record<string, unknown>;
|
|
401
|
+
}
|
|
402
|
+
interface UseLeadCaptureReturn {
|
|
403
|
+
captureLead: (payload: LeadCapturePayload) => Promise<boolean>;
|
|
404
|
+
isSubmitting: boolean;
|
|
405
|
+
isSuccess: boolean;
|
|
406
|
+
error: Error | null;
|
|
407
|
+
reset: () => void;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Hook to capture customer lead contact details directly from custom React forms or chat widgets.
|
|
411
|
+
*/
|
|
412
|
+
declare function useLeadCapture(): UseLeadCaptureReturn;
|
|
413
|
+
|
|
414
|
+
interface UseVoiceTranscriptionReturn {
|
|
415
|
+
transcribe: (audio: Blob | File) => Promise<string | null>;
|
|
416
|
+
isTranscribing: boolean;
|
|
417
|
+
transcript: string | null;
|
|
418
|
+
error: Error | null;
|
|
419
|
+
reset: () => void;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Hook to transcribe audio recordings directly to text using the Botzki AI audio transcription endpoint.
|
|
423
|
+
*/
|
|
424
|
+
declare function useVoiceTranscription(): UseVoiceTranscriptionReturn;
|
|
425
|
+
|
|
426
|
+
export { type BotInfoData, BotzkiChat, type BotzkiChatProps, type BotzkiContextValue, type BotzkiMessage, BotzkiProvider, type BotzkiProviderProps, BotzkiWidget, type BotzkiWidgetProps, type BotzkiWidgetRef, type FeedbackPayload, type LeadCapturePayload, type UseBotInfoReturn, type UseChatOptions, type UseChatReturn, type UseFeedbackReturn, type UseLeadCaptureReturn, type UseVoiceTranscriptionReturn, useBotInfo, useBotzki, useChat, useFeedback, useLeadCapture, useOptionalBotzki, useVoiceTranscription };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {createContext,forwardRef,useState,useEffect,useCallback,useImperativeHandle,useContext,useMemo,useRef}from'react';import {Botzki}from'@botzki/js';import {jsxs,jsx}from'react/jsx-runtime';import {createPortal}from'react-dom';var ie=createContext(null);function ae(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"sess_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function Te({botId:t,publishableKey:e,baseUrl:l,apiHost:p,user:b,defaultSessionId:a,client:m,children:y}){let g=p||l||"https://api.botzki.com",[u,c]=useState(()=>{if(a)return a;if(typeof window<"u")try{let h=localStorage.getItem(`botzki_session_${t}`);if(h)return h;let M=ae();return localStorage.setItem(`botzki_session_${t}`,M),M}catch{return ae()}return a||ae()}),n=useMemo(()=>m||new Botzki({botId:t,publishableKey:e,apiHost:g}),[m,t,e,g]);useEffect(()=>{b&&n&&typeof n.setUser=="function"&&n.setUser(b);},[n,b]);let w=useMemo(()=>({client:n,botId:t,publishableKey:e,baseUrl:g,apiHost:g,user:b,sessionId:u,setSessionId:c}),[n,t,e,g,b,u]);return jsx(ie.Provider,{value:w,children:y})}function O(){let t=useContext(ie);if(!t)throw new Error("useBotzki must be used within a <BotzkiProvider>. Wrap your application or component with <BotzkiProvider botId='...' publishableKey='...'>.");return t}function te(){return useContext(ie)}function le(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"msg_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function oe(t={}){let e=te(),l=t.botId||e?.botId,p=t.publishableKey||e?.publishableKey,b=t.baseUrl||e?.baseUrl||"https://api.botzki.com",a=useMemo(()=>e?.client&&(!t.botId||t.botId===e.botId)?e.client:l&&p?new Botzki({botId:l,publishableKey:p,apiHost:b}):null,[e?.client,e?.botId,t.botId,l,p,b]),m=t.storageKey||(l?`botzki_chat_history_${l}`:"botzki_chat_history"),y=t.persistSession??true,[g,u]=useState(()=>t.sessionId?t.sessionId:e?.sessionId?e.sessionId:"sess_"+Math.random().toString(36).substring(2,9)),[c,n]=useState(t.initialMessages||[]),[w,h]=useState(""),[M,S]=useState(false),[P,B]=useState(false),[Q,U]=useState(null),R=useRef(null),$=useRef(c);$.current=c,useEffect(()=>{if(!(!y||typeof window>"u"||t.initialMessages?.length))try{let o=localStorage.getItem(m);if(o){let f=JSON.parse(o);Array.isArray(f)&&n(f.map(x=>({...x,createdAt:new Date(x.createdAt)})));}}catch{}},[y,m,t.initialMessages?.length]),useEffect(()=>{if(!(!y||typeof window>"u"))try{c.length>0&&localStorage.setItem(m,JSON.stringify(c));}catch{}},[c,y,m]);let z=useCallback(()=>{R.current&&(R.current.abort(),R.current=null),S(false),B(false);},[]),T=useCallback(async(o,f)=>{let x=o.trim();if(!x&&!f?.imageBase64)return;if(!l){let d=new Error("botId is required. Provide botId in options or wrap your component tree in <BotzkiProvider botId='...'>");U(d),t.onError?.(d);return}U(null),S(true),B(t.stream!==false);let j={id:le(),role:"user",content:x,createdAt:new Date},k=le(),L={id:k,role:"assistant",content:"",createdAt:new Date,isStreaming:t.stream!==false};n(d=>[...d,j,L]);let I=new AbortController;R.current=I;try{if(t.stream!==!1){let d="";if(a&&typeof a.chatStream=="function")await a.chatStream({message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType,onDelta:i=>{I.signal.aborted||(d+=i,n(s=>s.map(r=>r.id===k?{...r,content:d}:r)));},onDone:i=>{if(I.signal.aborted)return;let s={id:k,role:"assistant",content:i.reply||d,createdAt:new Date,citations:i.citations,isStreaming:!1};n(r=>r.map(C=>C.id===k?s:C)),S(!1),B(!1),t.onResponse?.(i),t.onFinish?.(s);},onError:i=>{I.signal.aborted||(U(i),S(!1),B(!1),n(s=>s.map(r=>r.id===k?{...r,isStreaming:!1,error:i.message}:r)),t.onError?.(i));}});else if(a&&typeof a.stream=="function")await a.stream({message:x,sessionId:g,language:t.language,onToken:i=>{I.signal.aborted||(d+=i,n(s=>s.map(r=>r.id===k?{...r,content:d}:r)));},onDone:i=>{if(I.signal.aborted)return;let s={id:k,role:"assistant",content:i||d,createdAt:new Date,isStreaming:!1};n(r=>r.map(C=>C.id===k?s:C)),S(!1),B(!1),t.onFinish?.(s);},onError:i=>{I.signal.aborted||(U(i),S(!1),B(!1),n(s=>s.map(r=>r.id===k?{...r,isStreaming:!1,error:i.message}:r)),t.onError?.(i));}});else {let i=b?b.replace(/\/+$/,""):"https://api.botzki.com",s={"Content-Type":"application/json"};p&&(s.Authorization=`Bearer ${p}`);let r=await fetch(`${i}/api/v1/public/chat/${l}/stream`,{method:"POST",headers:s,body:JSON.stringify({query:x,message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType}),signal:I.signal});if(!r.ok){let G=`Chat request failed with status ${r.status}`;try{let N=await r.json();N?.message&&(G=N.message);}catch{}throw new Error(G)}let C=r.body?.getReader();if(!C)throw new Error("Response body is not readable.");let A=new TextDecoder("utf-8"),_="",V=[];for(;;){let{done:G,value:N}=await C.read();if(G||I.signal.aborted)break;_+=A.decode(N,{stream:!0});let me=_.split(`
|
|
2
|
+
`);_=me.pop()||"";for(let re of me)if(re=re.trim(),re.startsWith("data: ")){let Se=re.slice(6);try{let X=JSON.parse(Se);X.delta&&(d+=X.delta,n(ze=>ze.map(se=>se.id===k?{...se,content:d}:se))),X.answer&&(d=X.answer),X.citations&&(V=X.citations);}catch{}}}let ee={id:k,role:"assistant",content:d,createdAt:new Date,citations:V.length>0?V:void 0,isStreaming:!1};n(G=>G.map(N=>N.id===k?ee:N)),S(!1),B(!1),t.onResponse?.({reply:d,answer:d,citations:V,insufficientEvidence:!1,sessionId:g}),t.onFinish?.(ee);}}else {let d="",i=[];if(a&&typeof a.chat=="function"){let r=await a.chat({message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType});d=r.reply||r.answer,i=r.citations||[];}else {let r=b?b.replace(/\/+$/,""):"https://api.botzki.com",C={"Content-Type":"application/json"};p&&(C.Authorization=`Bearer ${p}`);let A=await fetch(`${r}/api/v1/public/chat/${l}`,{method:"POST",headers:C,body:JSON.stringify({query:x,message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType}),signal:I.signal});if(!A.ok){let V=`Chat request failed with status ${A.status}`;try{let ee=await A.json();ee?.message&&(V=ee.message);}catch{}throw new Error(V)}let _=await A.json();d=_.reply||_.answer||"",i=_.citations||[];}let s={id:k,role:"assistant",content:d,createdAt:new Date,citations:i.length>0?i:void 0,isStreaming:!1};n(r=>r.map(C=>C.id===k?s:C)),S(!1),B(!1),t.onResponse?.({reply:d,answer:d,citations:i,insufficientEvidence:!1,sessionId:g}),t.onFinish?.(s);}}catch(d){if(!I.signal.aborted){let i=d instanceof Error?d:new Error(String(d));U(i),S(false),B(false),n(s=>s.map(r=>r.id===k?{...r,isStreaming:false,error:i.message}:r)),t.onError?.(i);}}finally{R.current===I&&(R.current=null);}},[a,t,g]),F=useCallback(o=>{h(o.target.value);},[]),W=useCallback(async(o,f)=>{o&&typeof o.preventDefault=="function"&&o.preventDefault();let x=w;h(""),await T(x,f);},[w,T]),D=useCallback(o=>{let f={id:o.id||le(),role:o.role||"user",content:o.content,createdAt:o.createdAt||new Date,citations:o.citations,isStreaming:o.isStreaming,error:o.error};n(x=>[...x,f]);},[]),H=useCallback(async()=>{let o=$.current;if(o.length===0)return;let f=o.map(j=>j.role).lastIndexOf("user");if(f===-1)return;let x=o[f];n(o.slice(0,f)),await T(x.content);},[T]),Y=useCallback(()=>{if(z(),n([]),y&&typeof window<"u")try{localStorage.removeItem(m);}catch{}},[z,y,m]);return {messages:c,input:w,setInput:h,handleInputChange:F,handleSubmit:W,sendMessage:T,append:D,reload:H,stop:z,clearMessages:Y,setMessages:n,isLoading:M,isStreaming:P,error:Q,sessionId:g,setSessionId:u}}function de(){let{client:t,botId:e,baseUrl:l}=O(),[p,b]=useState(null),[a,m]=useState(true),[y,g]=useState(null),u=useCallback(async()=>{m(true),g(null);try{let c;if(typeof t.getBotInfo=="function")c=await t.getBotInfo();else {let n=l?l.replace(/\/+$/,""):"https://api.botzki.com";c=await(await fetch(`${n}/api/v1/public/chat/${e}`)).json();}b(c);}catch(c){g(c instanceof Error?c:new Error(String(c)));}finally{m(false);}},[t,e,l]);return useEffect(()=>{u();},[u,e]),{data:p,isLoading:a,error:y,refetch:u}}function ue({title:t,subtitle:e="Online",greeting:l="Hello! How can I help you today?",starterQuestions:p,theme:b="auto",primaryColor:a="#0ea5e9",className:m="",style:y,placeholder:g="Ask a question...",onClose:u,showCloseButton:c=false,showClearButton:n=true,chat:w,...h}){let M=oe(h),S=w||M,{messages:P,input:B,handleInputChange:Q,handleSubmit:U,sendMessage:R,clearMessages:$,isLoading:z,isStreaming:T,error:F}=S,{data:W}=de(),D=useRef(null);useEffect(()=>{D.current&&(D.current.scrollTop=D.current.scrollHeight);},[P,T]);let H=t||W?.name||"AI Assistant",Y=p||W?.starterQuestions||[],o=b==="dark"||b==="auto"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches,f=o?"#0f172a":"#ffffff",x=o?"#1e293b":"#f8fafc",j=o?"#f8fafc":"#0f172a",k=o?"#94a3b8":"#64748b",L=o?"#334155":"#e2e8f0",I=a,d=o?"#1e293b":"#f1f5f9",i=o?"#f1f5f9":"#1e293b";return jsxs("div",{className:m,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:"450px",backgroundColor:f,color:j,borderRadius:"16px",border:`1px solid ${L}`,overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',boxSizing:"border-box",...y},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",backgroundColor:x,borderBottom:`1px solid ${L}`},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[jsx("div",{style:{width:"36px",height:"36px",borderRadius:"50%",backgroundColor:a,display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",fontWeight:"bold",fontSize:"15px"},children:H.charAt(0).toUpperCase()}),jsxs("div",{children:[jsx("div",{style:{fontWeight:600,fontSize:"14px",lineHeight:1.2},children:H}),jsxs("div",{style:{fontSize:"12px",color:k,display:"flex",alignItems:"center",gap:"5px",marginTop:"2px"},children:[jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",backgroundColor:"#22c55e",display:"inline-block"}}),e]})]})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[P.length>0&&n&&jsx("button",{onClick:$,title:"Clear Chat",type:"button",style:{background:"transparent",border:"none",color:k,cursor:"pointer",fontSize:"12px",padding:"4px 8px",borderRadius:"6px"},children:"Clear"}),c&&u&&jsx("button",{onClick:u,title:"Close Chat",type:"button",style:{background:"transparent",border:"none",color:k,cursor:"pointer",fontSize:"16px",padding:"4px 8px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center"},children:"\u2715"})]})]}),jsxs("div",{ref:D,style:{flex:1,overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px"},children:[l&&jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:jsx("div",{style:{maxWidth:"80%",padding:"10px 14px",borderRadius:"14px",backgroundColor:d,color:i,fontSize:"14px",lineHeight:1.45},children:l})}),P.length===0&&Y.length>0&&jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px",marginTop:"8px"},children:[jsx("span",{style:{fontSize:"11px",color:k,fontWeight:500},children:"SUGGESTED QUESTIONS"}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Y.map((s,r)=>jsx("button",{onClick:()=>R(s),style:{backgroundColor:o?"#1e293b":"#f1f5f9",color:j,border:`1px solid ${L}`,padding:"6px 12px",borderRadius:"20px",fontSize:"12px",cursor:"pointer",textAlign:"left",transition:"all 0.15s ease"},children:s},r))})]}),P.map(s=>{let r=s.role==="user";return jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"flex-start"},children:jsxs("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"14px",backgroundColor:r?I:d,color:r?"#ffffff":i,fontSize:"14px",lineHeight:1.45,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[s.content,s.citations&&s.citations.length>0&&jsxs("div",{style:{marginTop:"8px",paddingTop:"6px",borderTop:`1px solid ${r?"rgba(255,255,255,0.2)":L}`,fontSize:"11px",display:"flex",flexWrap:"wrap",gap:"4px"},children:[jsx("span",{style:{opacity:.8},children:"Sources:"}),s.citations.map((C,A)=>jsxs("span",{style:{backgroundColor:r?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.06)",padding:"2px 6px",borderRadius:"4px",fontWeight:500},children:[C.source," ",C.page_number?`p.${C.page_number}`:""]},A))]}),s.error&&jsxs("div",{style:{marginTop:"6px",fontSize:"12px",color:"#ef4444"},children:["Error: ",s.error]})]})},s.id)}),z&&!T&&jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:jsx("div",{style:{padding:"8px 14px",borderRadius:"14px",backgroundColor:d,color:k,fontSize:"13px"},children:"Thinking..."})}),F&&jsx("div",{style:{padding:"8px 12px",borderRadius:"8px",backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#ef4444",fontSize:"12px"},children:F.message})]}),jsxs("form",{onSubmit:U,style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",borderTop:`1px solid ${L}`,backgroundColor:x},children:[jsx("input",{type:"text",value:B,onChange:Q,placeholder:g,disabled:z,style:{flex:1,padding:"10px 14px",borderRadius:"22px",border:`1px solid ${L}`,backgroundColor:f,color:j,fontSize:"14px",outline:"none"}}),jsx("button",{type:"submit",disabled:z||!B.trim(),style:{backgroundColor:a,color:"#ffffff",border:"none",borderRadius:"20px",padding:"10px 18px",fontWeight:600,fontSize:"13px",cursor:z||!B.trim()?"not-allowed":"pointer",opacity:z||!B.trim()?.5:1,transition:"opacity 0.2s ease"},children:"Send"})]})]})}var je=forwardRef(function(e,l){let p=te(),b=e.botId||p?.botId,a=e.publishableKey||p?.publishableKey,m=e.baseUrl||p?.baseUrl||"https://api.botzki.com",[y,g]=useState(false),[u,c]=useState(false),[n,w]=useState(true),[h,M]=useState(e.theme||"dark"),[S,P]=useState(e.primaryColor||"#0ea5e9"),[,B]=useState(e.user||p?.user),[Q,U]=useState(false);useEffect(()=>{e.theme&&M(e.theme);},[e.theme]),useEffect(()=>{e.primaryColor&&P(e.primaryColor);},[e.primaryColor]),useEffect(()=>{e.user&&B(e.user);},[e.user]),useEffect(()=>{g(true);},[]);let R=oe({botId:b,publishableKey:a,baseUrl:m,persistSession:e.persistSession??true,onResponse:e.onMessage?o=>e.onMessage?.({role:"assistant",content:o.reply}):void 0,onError:e.onError}),$=useCallback(()=>{c(true),e.onOpen?.();},[e.onOpen]),z=useCallback(()=>{c(false),e.onClose?.();},[e.onClose]),T=useCallback(()=>{c(o=>{let f=!o;return f?e.onOpen?.():e.onClose?.(),f});},[e.onOpen,e.onClose]);if(useImperativeHandle(l,()=>({open:$,close:z,toggle:T,isOpen:()=>u,show:()=>w(true),hide:()=>{w(false),z();},sendMessage:async(o,f)=>{$(),await R.sendMessage(o,f?{imageBase64:f}:void 0);},clearMessages:()=>R.clearMessages(),setTheme:o=>M(o),setPrimaryColor:o=>P(o),setUser:o=>B(o)}),[$,z,T,u,R]),!y||typeof document>"u")return null;let F=e.position==="bottom-left",W=e.offset?.x??24,D=e.offset?.y??24,H=e.zIndex??2147483647,Y=jsxs("div",{id:"botzki-react-widget-container",style:{display:n?"block":"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[jsx("div",{role:"dialog","aria-label":"Botzki AI Chat",style:{position:"fixed",bottom:D+68,[F?"left":"right"]:W,width:"380px",maxWidth:"calc(100vw - 32px)",height:"580px",maxHeight:"calc(100vh - 110px)",zIndex:H,boxShadow:"0 20px 40px -10px rgba(0, 0, 0, 0.4), 0 0 1px 1px rgba(255, 255, 255, 0.1)",borderRadius:"16px",overflow:"hidden",transition:"opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1), visibility 0.25s",opacity:u?1:0,transform:u?"translateY(0) scale(1)":"translateY(16px) scale(0.95)",visibility:u?"visible":"hidden",pointerEvents:u?"auto":"none"},children:jsx(ue,{chat:R,title:e.widgetTitle,subtitle:e.widgetSubtitle||"Online",greeting:e.greeting,starterQuestions:e.starterPrompts,theme:h,primaryColor:S,showCloseButton:e.showCloseButton!==false,showClearButton:e.showClearButton!==false,onClose:z,style:{height:"100%",borderRadius:"16px"}})}),jsx("button",{type:"button",onClick:T,onMouseEnter:()=>U(true),onMouseLeave:()=>U(false),"aria-label":u?"Close AI Support Chat":"Open AI Support Chat",style:{position:"fixed",bottom:D,[F?"left":"right"]:W,width:"56px",height:"56px",borderRadius:"50%",backgroundColor:S,color:"#ffffff",border:"none",outline:"none",cursor:"pointer",boxShadow:Q?"0 10px 24px rgba(0, 0, 0, 0.35), 0 4px 8px rgba(0, 0, 0, 0.2)":"0 6px 16px rgba(0, 0, 0, 0.24), 0 3px 6px rgba(0, 0, 0, 0.12)",zIndex:H,display:"flex",alignItems:"center",justifyContent:"center",transform:Q?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), box-shadow 0.2s ease"},children:u?jsxs("svg",{viewBox:"0 0 24 24",width:"24",height:"24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):jsx("svg",{viewBox:"0 0 24 24",width:"26",height:"26",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})]});return createPortal(Y,document.body)});function _e(){let{client:t,botId:e,baseUrl:l,sessionId:p}=O(),[b,a]=useState(false),[m,y]=useState(false),[g,u]=useState(null),c=useCallback(async w=>{a(true),u(null),y(false);try{if(typeof t.submitFeedback=="function")await t.submitFeedback({...w,sessionId:p});else {let h=l?l.replace(/\/+$/,""):"https://api.botzki.com";await fetch(`${h}/api/v1/public/chat/${e}/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...w,sessionId:p})});}return y(!0),!0}catch(h){let M=h instanceof Error?h:new Error(String(h));return u(M),false}finally{a(false);}},[t,e,l,p]),n=useCallback(()=>{a(false),y(false),u(null);},[]);return {submitFeedback:c,isSubmitting:b,isSuccess:m,error:g,reset:n}}function Ve(){let{client:t,botId:e,baseUrl:l,sessionId:p}=O(),[b,a]=useState(false),[m,y]=useState(false),[g,u]=useState(null),c=useCallback(async w=>{a(true),u(null),y(false);try{if(typeof t.captureLead=="function")await t.captureLead({...w,sessionId:p});else {let h=l?l.replace(/\/+$/,""):"https://api.botzki.com";await fetch(`${h}/api/v1/public/chat/${e}/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...w,sessionId:p})});}return y(!0),!0}catch(h){let M=h instanceof Error?h:new Error(String(h));return u(M),false}finally{a(false);}},[t,e,l,p]),n=useCallback(()=>{a(false),y(false),u(null);},[]);return {captureLead:c,isSubmitting:b,isSuccess:m,error:g,reset:n}}function Ne(){let{client:t}=O(),[e,l]=useState(false),[p,b]=useState(null),[a,m]=useState(null),y=useCallback(async u=>{l(true),m(null);try{let n=(await t.transcribeAudio(u)).text||"";return b(n),n}catch(c){let n=c instanceof Error?c:new Error(String(c));return m(n),null}finally{l(false);}},[t]),g=useCallback(()=>{l(false),b(null),m(null);},[]);return {transcribe:y,isTranscribing:e,transcript:p,error:a,reset:g}}
|
|
3
|
+
export{ue as BotzkiChat,Te as BotzkiProvider,je as BotzkiWidget,de as useBotInfo,O as useBotzki,oe as useChat,_e as useFeedback,Ve as useLeadCapture,te as useOptionalBotzki,Ne as useVoiceTranscription};//# sourceMappingURL=index.mjs.map
|
|
4
|
+
//# sourceMappingURL=index.mjs.map
|