@vezlo/assistant-chat 1.8.0 → 1.9.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/PACKAGE_README.md CHANGED
@@ -67,6 +67,7 @@ The `WidgetConfig` interface includes:
67
67
  - `defaultOpen`: Whether widget opens by default
68
68
  - `supabaseUrl`: Supabase project URL (optional, required for realtime updates)
69
69
  - `supabaseAnonKey`: Supabase anon key (optional, required for realtime updates)
70
+ - `userContext`: Object containing user identifiers for database query filtering (optional)
70
71
 
71
72
  ### Configuration Options Table
72
73
 
@@ -85,6 +86,7 @@ The `WidgetConfig` interface includes:
85
86
  | `apiKey` | string | Required | API key for authentication |
86
87
  | `supabaseUrl` | string | Optional | Supabase project URL (for realtime updates) |
87
88
  | `supabaseAnonKey` | string | Optional | Supabase anon key (for realtime updates) |
89
+ | `userContext` | object | Optional | User identifiers for database filtering (e.g., `{ user_uuid, company_uuid }`) |
88
90
 
89
91
  ## API Integration
90
92
 
@@ -156,6 +158,39 @@ function MyApp() {
156
158
  }
157
159
  ```
158
160
 
161
+ ### With User Context (Database Tools)
162
+
163
+ ```tsx
164
+ import { Widget } from '@vezlo/assistant-chat';
165
+
166
+ function MyApp() {
167
+ // Get current user from your auth system
168
+ const currentUser = useAuth(); // Your auth hook
169
+
170
+ return (
171
+ <Widget
172
+ config={{
173
+ uuid: 'my-widget-123',
174
+ apiUrl: 'http://localhost:3000',
175
+ apiKey: 'your-api-key',
176
+ title: 'AI Assistant',
177
+ themeColor: '#10b981',
178
+ // Pass user context for database query filtering
179
+ userContext: {
180
+ user_uuid: currentUser.uuid,
181
+ company_uuid: currentUser.companyUuid,
182
+ // Optional: numeric IDs if your database uses them
183
+ user_id: currentUser.id,
184
+ company_id: currentUser.companyId
185
+ }
186
+ }}
187
+ />
188
+ );
189
+ }
190
+ ```
191
+
192
+ **Note:** `userContext` is optional. The widget works fine without it. If provided, it enables user-specific database queries when Database Tools are configured in the admin dashboard.
193
+
159
194
  ### With Callbacks
160
195
 
161
196
  ```tsx
package/README.md CHANGED
@@ -101,6 +101,7 @@ npm run dev
101
101
  - ✅ Multiple widget management
102
102
  - ✅ **Human agent support** (conversation management, agent handoff)
103
103
  - ✅ **Realtime updates** (live message synchronization)
104
+ - ✅ **Database tools** (connect external databases for natural language queries - [docs](./docs/DATABASE_TOOLS.md))
104
105
  - ✅ Docker support
105
106
  - ✅ Vercel deployment
106
107
 
@@ -75,7 +75,7 @@ export declare function generateAIResponse(userMessageUuid: string, apiUrl?: str
75
75
  * Stream AI response using Server-Sent Events (SSE)
76
76
  * This is the recommended approach for real-time streaming
77
77
  */
78
- export declare function streamAIResponse(userMessageUuid: string, callbacks: StreamCallbacks, apiUrl?: string): Promise<void>;
78
+ export declare function streamAIResponse(userMessageUuid: string, callbacks: StreamCallbacks, apiUrl?: string, userContext?: Record<string, any>): Promise<void>;
79
79
  /**
80
80
  * Feedback API
81
81
  */
@@ -58,14 +58,16 @@ export async function generateAIResponse(userMessageUuid, apiUrl) {
58
58
  * Stream AI response using Server-Sent Events (SSE)
59
59
  * This is the recommended approach for real-time streaming
60
60
  */
61
- export async function streamAIResponse(userMessageUuid, callbacks, apiUrl) {
61
+ export async function streamAIResponse(userMessageUuid, callbacks, apiUrl, userContext) {
62
62
  const API_BASE_URL = apiUrl || DEFAULT_API_BASE_URL;
63
63
  try {
64
64
  const response = await fetch(`${API_BASE_URL}/api/messages/${userMessageUuid}/generate`, {
65
65
  method: 'POST',
66
66
  headers: {
67
67
  'Accept': 'text/event-stream',
68
+ 'Content-Type': 'application/json',
68
69
  },
70
+ body: userContext ? JSON.stringify({ user_context: userContext }) : undefined,
69
71
  });
70
72
  if (!response.ok) {
71
73
  // Try to parse error as JSON first
@@ -259,7 +259,8 @@ export function Widget({ config, isPlayground = false, onOpen, onClose, onMessag
259
259
  // Ensure loading is hidden
260
260
  setIsLoading(false);
261
261
  },
262
- }, config.apiUrl);
262
+ }, config.apiUrl, config.userContext // Pass user context for database filtering
263
+ );
263
264
  }
264
265
  else {
265
266
  // Agent has joined, don't generate AI response
@@ -0,0 +1,8 @@
1
+ import type { ChatSource } from '../../types';
2
+ interface NextStepsProps {
3
+ content: string;
4
+ sources?: ChatSource[];
5
+ }
6
+ export declare function extractRoutesFromText(text: string): string[];
7
+ export declare function NextSteps({ content, sources }: NextStepsProps): import("react/jsx-runtime").JSX.Element;
8
+ export {};
@@ -0,0 +1,156 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { ArrowRight, Navigation, MapPin, ExternalLink } from 'lucide-react';
3
+ // Extract routes mentioned in text
4
+ export function extractRoutesFromText(text) {
5
+ const routes = [];
6
+ // Match routes like "/settings", "/login", "/widget/:uuid"
7
+ const routePattern = /(\/[\w\/:*-]+)/g;
8
+ const matches = text.matchAll(routePattern);
9
+ for (const match of matches) {
10
+ const route = match[1];
11
+ if (route && !routes.includes(route)) {
12
+ routes.push(route);
13
+ }
14
+ }
15
+ return routes;
16
+ }
17
+ export function NextSteps({ content, sources }) {
18
+ // Extract all routes from sources
19
+ const allRoutes = sources
20
+ ?.filter(s => s.navigationMetadata?.routes && s.navigationMetadata.routes.length > 0)
21
+ .flatMap(s => s.navigationMetadata.routes) || [];
22
+ // Parse "Next Steps" section from AI response
23
+ const parseNextSteps = (text) => {
24
+ const steps = [];
25
+ // Look for "Next Steps:" or "**Next Steps:**" section
26
+ const nextStepsMatch = text.match(/(?:\*\*)?Next Steps:?\*\*(?:[\s\S]*?)(?:\n-|\n\*|\n\d+\.)\s*(.+?)(?=\n\n|\n\*\*|$)/gi);
27
+ if (!nextStepsMatch) {
28
+ // Try to find bullet points after "Next Steps"
29
+ const sectionMatch = text.match(/(?:Next Steps|Next steps|NEXT STEPS)[:\s]*\n((?:[-*•]\s*.+?\n?)+)/i);
30
+ if (sectionMatch) {
31
+ const bullets = sectionMatch[1].match(/[-*•]\s*(.+?)(?=\n[-*•]|\n\n|$)/g);
32
+ if (bullets) {
33
+ bullets.forEach(bullet => {
34
+ const stepText = bullet.replace(/^[-*•]\s*/, '').trim();
35
+ const route = extractRoute(stepText);
36
+ steps.push({
37
+ text: stepText,
38
+ route,
39
+ action: route ? 'navigate' : 'info'
40
+ });
41
+ });
42
+ }
43
+ }
44
+ }
45
+ else {
46
+ // Parse structured next steps
47
+ const lines = text.split('\n');
48
+ let inNextSteps = false;
49
+ for (const line of lines) {
50
+ if (line.match(/Next Steps/i)) {
51
+ inNextSteps = true;
52
+ continue;
53
+ }
54
+ if (inNextSteps) {
55
+ // Stop at next section (## or **)
56
+ if (line.match(/^##|^\*\*/) && !line.match(/Next Steps/i)) {
57
+ break;
58
+ }
59
+ // Match bullet points
60
+ const bulletMatch = line.match(/^[-*•]\s*(.+)$/);
61
+ if (bulletMatch) {
62
+ const stepText = bulletMatch[1].trim();
63
+ const route = extractRoute(stepText);
64
+ steps.push({
65
+ text: stepText,
66
+ route,
67
+ action: route ? 'navigate' : 'info'
68
+ });
69
+ }
70
+ }
71
+ }
72
+ }
73
+ // If no structured steps found, try to extract navigation suggestions from the content
74
+ if (steps.length === 0) {
75
+ const navigationPhrases = [
76
+ /(?:navigate to|go to|visit|access|open)\s+([\/\w:]+)/gi,
77
+ /(?:route|path)\s+([\/\w:]+)/gi,
78
+ /(?:at|to)\s+([\/\w:]+)/gi
79
+ ];
80
+ navigationPhrases.forEach(pattern => {
81
+ const matches = text.matchAll(pattern);
82
+ for (const match of matches) {
83
+ const route = match[1];
84
+ if (route && allRoutes.some(r => r.path === route)) {
85
+ const context = text.substring(Math.max(0, match.index - 50), match.index + match[0].length + 50);
86
+ steps.push({
87
+ text: context.trim(),
88
+ route,
89
+ action: 'navigate'
90
+ });
91
+ }
92
+ }
93
+ });
94
+ }
95
+ return steps.slice(0, 5); // Limit to 5 steps
96
+ };
97
+ // Extract route path from text
98
+ const extractRoute = (text) => {
99
+ // Match routes like "/settings", "/login", "/widget/:uuid"
100
+ const routeMatch = text.match(/(\/[\w\/:*-]+)/);
101
+ if (routeMatch) {
102
+ const route = routeMatch[1];
103
+ // Verify it exists in available routes
104
+ if (allRoutes.some(r => r.path === route || route.startsWith(r.path))) {
105
+ return route;
106
+ }
107
+ }
108
+ return undefined;
109
+ };
110
+ const steps = parseNextSteps(content);
111
+ // If no steps found, try to generate from available routes
112
+ if (steps.length === 0 && allRoutes.length > 0) {
113
+ // Generate suggestions based on common routes
114
+ const commonRoutes = allRoutes
115
+ .filter(r => !r.dynamic)
116
+ .slice(0, 3)
117
+ .map(r => ({
118
+ text: `Navigate to ${r.path}`,
119
+ route: r.path,
120
+ action: 'navigate'
121
+ }));
122
+ if (commonRoutes.length > 0) {
123
+ return (_jsxs("div", { className: "mt-3 bg-gradient-to-r from-emerald-50 to-teal-50 border-2 border-emerald-300 rounded-lg p-3 shadow-sm", children: [_jsxs("div", { className: "flex items-center gap-2 mb-2", children: [_jsx(Navigation, { className: "w-4 h-4 text-emerald-600 flex-shrink-0" }), _jsx("div", { className: "text-sm font-bold text-emerald-900", children: "\uD83E\uDDED Suggested Navigation" })] }), _jsx("div", { className: "space-y-2", children: commonRoutes.map((step, idx) => {
124
+ const fullUrl = step.route && typeof window !== 'undefined' ? `${window.location.origin}${step.route}` : step.route;
125
+ return (_jsxs("button", { onClick: () => {
126
+ if (fullUrl) {
127
+ if (typeof window !== 'undefined' && window.location) {
128
+ window.location.href = fullUrl;
129
+ }
130
+ else {
131
+ navigator.clipboard.writeText(fullUrl);
132
+ }
133
+ }
134
+ }, className: "w-full text-left px-3 py-2 bg-white border-2 border-emerald-400 rounded-md text-sm font-medium text-emerald-900 hover:bg-emerald-50 hover:border-emerald-500 hover:shadow-md transition-all flex items-center justify-between group cursor-pointer", title: `Click to navigate to ${fullUrl}`, children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(MapPin, { className: "w-4 h-4 text-emerald-600" }), _jsx("span", { children: step.text })] }), _jsx(ArrowRight, { className: "w-4 h-4 text-emerald-600 opacity-0 group-hover:opacity-100 transition-opacity" })] }, idx));
135
+ }) })] }));
136
+ }
137
+ }
138
+ if (steps.length === 0) {
139
+ return null;
140
+ }
141
+ return (_jsxs("div", { className: "mt-3 bg-gradient-to-r from-emerald-50 to-teal-50 border-2 border-emerald-300 rounded-lg p-3 shadow-sm", children: [_jsxs("div", { className: "flex items-center gap-2 mb-2", children: [_jsx(Navigation, { className: "w-4 h-4 text-emerald-600 flex-shrink-0" }), _jsx("div", { className: "text-sm font-bold text-emerald-900", children: "\uD83E\uDDED Next Steps" })] }), _jsx("div", { className: "space-y-2", children: steps.map((step, idx) => {
142
+ const fullUrl = step.route && typeof window !== 'undefined' ? `${window.location.origin}${step.route}` : step.route;
143
+ return (_jsxs("button", { onClick: () => {
144
+ if (fullUrl) {
145
+ if (typeof window !== 'undefined' && window.location) {
146
+ window.location.href = fullUrl;
147
+ }
148
+ else {
149
+ navigator.clipboard.writeText(fullUrl);
150
+ }
151
+ }
152
+ }, className: `w-full text-left px-3 py-2 rounded-md text-sm transition-all flex items-start gap-2 group ${step.route
153
+ ? 'bg-white border-2 border-emerald-400 text-emerald-900 hover:bg-emerald-50 hover:border-emerald-500 hover:shadow-md font-medium cursor-pointer'
154
+ : 'bg-emerald-100/50 border border-emerald-300 text-emerald-800 cursor-default'}`, title: fullUrl ? `Click to navigate to ${fullUrl}` : undefined, children: [_jsxs("div", { className: "flex items-center gap-2 flex-1", children: [step.route ? (_jsx(MapPin, { className: "w-4 h-4 text-emerald-600 flex-shrink-0 mt-0.5" })) : (_jsx(ArrowRight, { className: "w-4 h-4 text-emerald-600 flex-shrink-0 mt-0.5" })), _jsx("span", { className: "flex-1", children: step.text })] }), step.route && (_jsx(ExternalLink, { className: "w-4 h-4 text-emerald-600 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0 mt-0.5" }))] }, idx));
155
+ }) })] }));
156
+ }
@@ -16,6 +16,7 @@ export interface WidgetConfig {
16
16
  defaultOpen?: boolean;
17
17
  supabaseUrl?: string;
18
18
  supabaseAnonKey?: string;
19
+ userContext?: Record<string, any>;
19
20
  }
20
21
  export interface ChatMessage {
21
22
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vezlo/assistant-chat",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "description": "React component library for AI-powered chat widgets with RAG knowledge base integration, realtime updates, and human agent support",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -37,6 +37,7 @@
37
37
  "dompurify": "^3.3.1",
38
38
  "lucide-react": "^0.544.0",
39
39
  "marked": "^17.0.1",
40
+ "react-hot-toast": "^2.6.0",
40
41
  "react-router-dom": "^7.9.3",
41
42
  "tailwindcss": "^4.1.14"
42
43
  },
package/public/widget.js CHANGED
@@ -36,7 +36,8 @@
36
36
  placeholder: 'Type your message...',
37
37
  welcomeMessage: "Hello! I'm your AI assistant. How can I help you today?",
38
38
  apiKey: '',
39
- themeColor: '#059669'
39
+ themeColor: '#059669',
40
+ userContext: {} // Optional: user context for database filtering
40
41
  };
41
42
 
42
43
  // Merge with user config