@inappai/react 0.1.0 → 1.0.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 +326 -17
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +207 -4
- package/dist/index.d.ts +207 -4
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +26 -12
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import React from 'react';
|
|
2
3
|
|
|
3
4
|
interface CustomStyles {
|
|
4
5
|
primaryColor?: string;
|
|
@@ -36,10 +37,22 @@ interface Tool {
|
|
|
36
37
|
parameters: any;
|
|
37
38
|
handler: (params: any) => Promise<any> | any;
|
|
38
39
|
}
|
|
40
|
+
interface Message {
|
|
41
|
+
id: string;
|
|
42
|
+
role: 'user' | 'assistant' | 'system';
|
|
43
|
+
content: string;
|
|
44
|
+
timestamp?: Date;
|
|
45
|
+
usage?: {
|
|
46
|
+
promptTokens: number;
|
|
47
|
+
completionTokens: number;
|
|
48
|
+
totalTokens: number;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
39
51
|
interface InAppAIProps {
|
|
40
|
-
endpoint
|
|
52
|
+
endpoint?: string;
|
|
53
|
+
agentId: string;
|
|
41
54
|
position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
|
|
42
|
-
displayMode?: 'popup' | 'sidebar-left' | 'sidebar-right' | 'panel-left' | 'panel-right';
|
|
55
|
+
displayMode?: 'popup' | 'sidebar-left' | 'sidebar-right' | 'panel-left' | 'panel-right' | 'embedded';
|
|
43
56
|
defaultFolded?: boolean;
|
|
44
57
|
theme?: 'light' | 'dark' | 'professional' | 'playful' | 'minimal' | 'ocean' | 'sunset';
|
|
45
58
|
context?: Record<string, any> | (() => Record<string, any>);
|
|
@@ -49,8 +62,198 @@ interface InAppAIProps {
|
|
|
49
62
|
panelMaxWidth?: string;
|
|
50
63
|
panelDefaultWidth?: string;
|
|
51
64
|
onPanelResize?: (width: number) => void;
|
|
65
|
+
messages: Message[];
|
|
66
|
+
onMessagesChange: (messages: Message[]) => void;
|
|
67
|
+
conversationId?: string;
|
|
68
|
+
showHeader?: boolean;
|
|
52
69
|
}
|
|
53
70
|
|
|
54
|
-
declare function InAppAI({ endpoint, position, displayMode, defaultFolded, theme, context, customStyles, tools, panelMinWidth, panelMaxWidth, panelDefaultWidth, onPanelResize }: InAppAIProps): react_jsx_runtime.JSX.Element;
|
|
71
|
+
declare function InAppAI({ endpoint, agentId, position, displayMode, defaultFolded, theme, context, customStyles, tools, panelMinWidth, panelMaxWidth, panelDefaultWidth, onPanelResize, conversationId: externalConversationId, messages: externalMessages, onMessagesChange, showHeader, }: InAppAIProps): react_jsx_runtime.JSX.Element;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Options for the useTools hook
|
|
75
|
+
*/
|
|
76
|
+
interface UseToolsOptions {
|
|
77
|
+
/**
|
|
78
|
+
* Initial tools to register
|
|
79
|
+
*/
|
|
80
|
+
initialTools?: Tool[];
|
|
81
|
+
/**
|
|
82
|
+
* Whether to automatically cleanup tools on unmount
|
|
83
|
+
* @default true
|
|
84
|
+
*/
|
|
85
|
+
autoCleanup?: boolean;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Return value from the useTools hook
|
|
89
|
+
*/
|
|
90
|
+
interface UseToolsReturn {
|
|
91
|
+
/**
|
|
92
|
+
* Current array of registered tools
|
|
93
|
+
*/
|
|
94
|
+
tools: Tool[];
|
|
95
|
+
/**
|
|
96
|
+
* Register a new tool
|
|
97
|
+
* @param tool - Tool to register
|
|
98
|
+
* @throws {Error} If tool with same name already exists
|
|
99
|
+
*/
|
|
100
|
+
registerTool: (tool: Tool) => void;
|
|
101
|
+
/**
|
|
102
|
+
* Unregister a tool by name
|
|
103
|
+
* @param name - Name of the tool to unregister
|
|
104
|
+
*/
|
|
105
|
+
unregisterTool: (name: string) => void;
|
|
106
|
+
/**
|
|
107
|
+
* Clear all registered tools
|
|
108
|
+
*/
|
|
109
|
+
clearTools: () => void;
|
|
110
|
+
/**
|
|
111
|
+
* Check if a tool with the given name exists
|
|
112
|
+
* @param name - Tool name to check
|
|
113
|
+
* @returns true if tool exists, false otherwise
|
|
114
|
+
*/
|
|
115
|
+
hasTool: (name: string) => boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Hook for managing tools dynamically in React components
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```tsx
|
|
122
|
+
* function MyComponent() {
|
|
123
|
+
* const { tools, registerTool, unregisterTool } = useTools();
|
|
124
|
+
* const [todos, setTodos] = useState([]);
|
|
125
|
+
*
|
|
126
|
+
* useEffect(() => {
|
|
127
|
+
* registerTool({
|
|
128
|
+
* name: 'addTodo',
|
|
129
|
+
* description: 'Add a new todo',
|
|
130
|
+
* parameters: {
|
|
131
|
+
* type: 'object',
|
|
132
|
+
* properties: {
|
|
133
|
+
* task: { type: 'string' }
|
|
134
|
+
* }
|
|
135
|
+
* },
|
|
136
|
+
* handler: async ({ task }) => {
|
|
137
|
+
* setTodos(prev => [...prev, { id: Date.now(), text: task }]);
|
|
138
|
+
* return { success: true };
|
|
139
|
+
* }
|
|
140
|
+
* });
|
|
141
|
+
*
|
|
142
|
+
* return () => unregisterTool('addTodo');
|
|
143
|
+
* }, [registerTool, unregisterTool, setTodos]);
|
|
144
|
+
*
|
|
145
|
+
* return <InAppAI endpoint="..." tools={tools} />;
|
|
146
|
+
* }
|
|
147
|
+
* ```
|
|
148
|
+
*
|
|
149
|
+
* @param options - Configuration options
|
|
150
|
+
* @returns Tool management functions and current tools array
|
|
151
|
+
*/
|
|
152
|
+
declare function useTools(options?: UseToolsOptions): UseToolsReturn;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Tool registry interface
|
|
156
|
+
*/
|
|
157
|
+
interface ToolRegistry {
|
|
158
|
+
/**
|
|
159
|
+
* Register tools under a namespace
|
|
160
|
+
* @param namespace - Unique namespace identifier
|
|
161
|
+
* @param tools - Array of tools to register
|
|
162
|
+
*/
|
|
163
|
+
register(namespace: string, tools: Tool[]): void;
|
|
164
|
+
/**
|
|
165
|
+
* Unregister all tools for a namespace
|
|
166
|
+
* @param namespace - Namespace to unregister
|
|
167
|
+
*/
|
|
168
|
+
unregister(namespace: string): void;
|
|
169
|
+
/**
|
|
170
|
+
* Get tools for a specific namespace
|
|
171
|
+
* @param namespace - Namespace to query
|
|
172
|
+
* @returns Array of tools for the namespace, or empty array if not found
|
|
173
|
+
*/
|
|
174
|
+
getTools(namespace: string): Tool[];
|
|
175
|
+
/**
|
|
176
|
+
* Get all registered tools from all namespaces
|
|
177
|
+
* @returns Combined array of all tools
|
|
178
|
+
*/
|
|
179
|
+
getAllTools(): Tool[];
|
|
180
|
+
/**
|
|
181
|
+
* Clear all registered tools from all namespaces
|
|
182
|
+
*/
|
|
183
|
+
clear(): void;
|
|
184
|
+
/**
|
|
185
|
+
* Get all registered namespace names
|
|
186
|
+
* @returns Array of namespace names
|
|
187
|
+
*/
|
|
188
|
+
getNamespaces(): string[];
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Props for ToolRegistryProvider
|
|
192
|
+
*/
|
|
193
|
+
interface ToolRegistryProviderProps {
|
|
194
|
+
/**
|
|
195
|
+
* Child components
|
|
196
|
+
*/
|
|
197
|
+
children: React.ReactNode;
|
|
198
|
+
/**
|
|
199
|
+
* Initial tools organized by namespace
|
|
200
|
+
*/
|
|
201
|
+
initialTools?: Record<string, Tool[]>;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Provider component for global tool registry
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```tsx
|
|
208
|
+
* function App() {
|
|
209
|
+
* return (
|
|
210
|
+
* <ToolRegistryProvider>
|
|
211
|
+
* <MyApp />
|
|
212
|
+
* </ToolRegistryProvider>
|
|
213
|
+
* );
|
|
214
|
+
* }
|
|
215
|
+
* ```
|
|
216
|
+
*/
|
|
217
|
+
declare function ToolRegistryProvider({ children, initialTools, }: ToolRegistryProviderProps): React.ReactElement;
|
|
218
|
+
/**
|
|
219
|
+
* Hook to access the tool registry
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```tsx
|
|
223
|
+
* function TodoPage() {
|
|
224
|
+
* const registry = useToolRegistry();
|
|
225
|
+
* const [todos, setTodos] = useState([]);
|
|
226
|
+
*
|
|
227
|
+
* useEffect(() => {
|
|
228
|
+
* registry.register('todos', [
|
|
229
|
+
* {
|
|
230
|
+
* name: 'addTodo',
|
|
231
|
+
* description: 'Add a todo',
|
|
232
|
+
* parameters: { type: 'object', properties: { task: { type: 'string' } } },
|
|
233
|
+
* handler: async ({ task }) => {
|
|
234
|
+
* setTodos(prev => [...prev, { id: Date.now(), text: task }]);
|
|
235
|
+
* return { success: true };
|
|
236
|
+
* }
|
|
237
|
+
* }
|
|
238
|
+
* ]);
|
|
239
|
+
*
|
|
240
|
+
* return () => registry.unregister('todos');
|
|
241
|
+
* }, [registry, todos, setTodos]);
|
|
242
|
+
*
|
|
243
|
+
* return <TodoList />;
|
|
244
|
+
* }
|
|
245
|
+
*
|
|
246
|
+
* function ChatWidget() {
|
|
247
|
+
* const registry = useToolRegistry();
|
|
248
|
+
* const allTools = registry.getAllTools();
|
|
249
|
+
*
|
|
250
|
+
* return <InAppAI endpoint="..." tools={allTools} />;
|
|
251
|
+
* }
|
|
252
|
+
* ```
|
|
253
|
+
*
|
|
254
|
+
* @throws {Error} If used outside of ToolRegistryProvider
|
|
255
|
+
* @returns Tool registry instance
|
|
256
|
+
*/
|
|
257
|
+
declare function useToolRegistry(): ToolRegistry;
|
|
55
258
|
|
|
56
|
-
export { type CustomStyles, InAppAI, type InAppAIProps, type Tool };
|
|
259
|
+
export { type CustomStyles, InAppAI, type InAppAIProps, type Message, type Tool, type ToolRegistry, ToolRegistryProvider, type ToolRegistryProviderProps, type UseToolsOptions, type UseToolsReturn, useToolRegistry, useTools };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import React from 'react';
|
|
2
3
|
|
|
3
4
|
interface CustomStyles {
|
|
4
5
|
primaryColor?: string;
|
|
@@ -36,10 +37,22 @@ interface Tool {
|
|
|
36
37
|
parameters: any;
|
|
37
38
|
handler: (params: any) => Promise<any> | any;
|
|
38
39
|
}
|
|
40
|
+
interface Message {
|
|
41
|
+
id: string;
|
|
42
|
+
role: 'user' | 'assistant' | 'system';
|
|
43
|
+
content: string;
|
|
44
|
+
timestamp?: Date;
|
|
45
|
+
usage?: {
|
|
46
|
+
promptTokens: number;
|
|
47
|
+
completionTokens: number;
|
|
48
|
+
totalTokens: number;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
39
51
|
interface InAppAIProps {
|
|
40
|
-
endpoint
|
|
52
|
+
endpoint?: string;
|
|
53
|
+
agentId: string;
|
|
41
54
|
position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
|
|
42
|
-
displayMode?: 'popup' | 'sidebar-left' | 'sidebar-right' | 'panel-left' | 'panel-right';
|
|
55
|
+
displayMode?: 'popup' | 'sidebar-left' | 'sidebar-right' | 'panel-left' | 'panel-right' | 'embedded';
|
|
43
56
|
defaultFolded?: boolean;
|
|
44
57
|
theme?: 'light' | 'dark' | 'professional' | 'playful' | 'minimal' | 'ocean' | 'sunset';
|
|
45
58
|
context?: Record<string, any> | (() => Record<string, any>);
|
|
@@ -49,8 +62,198 @@ interface InAppAIProps {
|
|
|
49
62
|
panelMaxWidth?: string;
|
|
50
63
|
panelDefaultWidth?: string;
|
|
51
64
|
onPanelResize?: (width: number) => void;
|
|
65
|
+
messages: Message[];
|
|
66
|
+
onMessagesChange: (messages: Message[]) => void;
|
|
67
|
+
conversationId?: string;
|
|
68
|
+
showHeader?: boolean;
|
|
52
69
|
}
|
|
53
70
|
|
|
54
|
-
declare function InAppAI({ endpoint, position, displayMode, defaultFolded, theme, context, customStyles, tools, panelMinWidth, panelMaxWidth, panelDefaultWidth, onPanelResize }: InAppAIProps): react_jsx_runtime.JSX.Element;
|
|
71
|
+
declare function InAppAI({ endpoint, agentId, position, displayMode, defaultFolded, theme, context, customStyles, tools, panelMinWidth, panelMaxWidth, panelDefaultWidth, onPanelResize, conversationId: externalConversationId, messages: externalMessages, onMessagesChange, showHeader, }: InAppAIProps): react_jsx_runtime.JSX.Element;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Options for the useTools hook
|
|
75
|
+
*/
|
|
76
|
+
interface UseToolsOptions {
|
|
77
|
+
/**
|
|
78
|
+
* Initial tools to register
|
|
79
|
+
*/
|
|
80
|
+
initialTools?: Tool[];
|
|
81
|
+
/**
|
|
82
|
+
* Whether to automatically cleanup tools on unmount
|
|
83
|
+
* @default true
|
|
84
|
+
*/
|
|
85
|
+
autoCleanup?: boolean;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Return value from the useTools hook
|
|
89
|
+
*/
|
|
90
|
+
interface UseToolsReturn {
|
|
91
|
+
/**
|
|
92
|
+
* Current array of registered tools
|
|
93
|
+
*/
|
|
94
|
+
tools: Tool[];
|
|
95
|
+
/**
|
|
96
|
+
* Register a new tool
|
|
97
|
+
* @param tool - Tool to register
|
|
98
|
+
* @throws {Error} If tool with same name already exists
|
|
99
|
+
*/
|
|
100
|
+
registerTool: (tool: Tool) => void;
|
|
101
|
+
/**
|
|
102
|
+
* Unregister a tool by name
|
|
103
|
+
* @param name - Name of the tool to unregister
|
|
104
|
+
*/
|
|
105
|
+
unregisterTool: (name: string) => void;
|
|
106
|
+
/**
|
|
107
|
+
* Clear all registered tools
|
|
108
|
+
*/
|
|
109
|
+
clearTools: () => void;
|
|
110
|
+
/**
|
|
111
|
+
* Check if a tool with the given name exists
|
|
112
|
+
* @param name - Tool name to check
|
|
113
|
+
* @returns true if tool exists, false otherwise
|
|
114
|
+
*/
|
|
115
|
+
hasTool: (name: string) => boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Hook for managing tools dynamically in React components
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```tsx
|
|
122
|
+
* function MyComponent() {
|
|
123
|
+
* const { tools, registerTool, unregisterTool } = useTools();
|
|
124
|
+
* const [todos, setTodos] = useState([]);
|
|
125
|
+
*
|
|
126
|
+
* useEffect(() => {
|
|
127
|
+
* registerTool({
|
|
128
|
+
* name: 'addTodo',
|
|
129
|
+
* description: 'Add a new todo',
|
|
130
|
+
* parameters: {
|
|
131
|
+
* type: 'object',
|
|
132
|
+
* properties: {
|
|
133
|
+
* task: { type: 'string' }
|
|
134
|
+
* }
|
|
135
|
+
* },
|
|
136
|
+
* handler: async ({ task }) => {
|
|
137
|
+
* setTodos(prev => [...prev, { id: Date.now(), text: task }]);
|
|
138
|
+
* return { success: true };
|
|
139
|
+
* }
|
|
140
|
+
* });
|
|
141
|
+
*
|
|
142
|
+
* return () => unregisterTool('addTodo');
|
|
143
|
+
* }, [registerTool, unregisterTool, setTodos]);
|
|
144
|
+
*
|
|
145
|
+
* return <InAppAI endpoint="..." tools={tools} />;
|
|
146
|
+
* }
|
|
147
|
+
* ```
|
|
148
|
+
*
|
|
149
|
+
* @param options - Configuration options
|
|
150
|
+
* @returns Tool management functions and current tools array
|
|
151
|
+
*/
|
|
152
|
+
declare function useTools(options?: UseToolsOptions): UseToolsReturn;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Tool registry interface
|
|
156
|
+
*/
|
|
157
|
+
interface ToolRegistry {
|
|
158
|
+
/**
|
|
159
|
+
* Register tools under a namespace
|
|
160
|
+
* @param namespace - Unique namespace identifier
|
|
161
|
+
* @param tools - Array of tools to register
|
|
162
|
+
*/
|
|
163
|
+
register(namespace: string, tools: Tool[]): void;
|
|
164
|
+
/**
|
|
165
|
+
* Unregister all tools for a namespace
|
|
166
|
+
* @param namespace - Namespace to unregister
|
|
167
|
+
*/
|
|
168
|
+
unregister(namespace: string): void;
|
|
169
|
+
/**
|
|
170
|
+
* Get tools for a specific namespace
|
|
171
|
+
* @param namespace - Namespace to query
|
|
172
|
+
* @returns Array of tools for the namespace, or empty array if not found
|
|
173
|
+
*/
|
|
174
|
+
getTools(namespace: string): Tool[];
|
|
175
|
+
/**
|
|
176
|
+
* Get all registered tools from all namespaces
|
|
177
|
+
* @returns Combined array of all tools
|
|
178
|
+
*/
|
|
179
|
+
getAllTools(): Tool[];
|
|
180
|
+
/**
|
|
181
|
+
* Clear all registered tools from all namespaces
|
|
182
|
+
*/
|
|
183
|
+
clear(): void;
|
|
184
|
+
/**
|
|
185
|
+
* Get all registered namespace names
|
|
186
|
+
* @returns Array of namespace names
|
|
187
|
+
*/
|
|
188
|
+
getNamespaces(): string[];
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Props for ToolRegistryProvider
|
|
192
|
+
*/
|
|
193
|
+
interface ToolRegistryProviderProps {
|
|
194
|
+
/**
|
|
195
|
+
* Child components
|
|
196
|
+
*/
|
|
197
|
+
children: React.ReactNode;
|
|
198
|
+
/**
|
|
199
|
+
* Initial tools organized by namespace
|
|
200
|
+
*/
|
|
201
|
+
initialTools?: Record<string, Tool[]>;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Provider component for global tool registry
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```tsx
|
|
208
|
+
* function App() {
|
|
209
|
+
* return (
|
|
210
|
+
* <ToolRegistryProvider>
|
|
211
|
+
* <MyApp />
|
|
212
|
+
* </ToolRegistryProvider>
|
|
213
|
+
* );
|
|
214
|
+
* }
|
|
215
|
+
* ```
|
|
216
|
+
*/
|
|
217
|
+
declare function ToolRegistryProvider({ children, initialTools, }: ToolRegistryProviderProps): React.ReactElement;
|
|
218
|
+
/**
|
|
219
|
+
* Hook to access the tool registry
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```tsx
|
|
223
|
+
* function TodoPage() {
|
|
224
|
+
* const registry = useToolRegistry();
|
|
225
|
+
* const [todos, setTodos] = useState([]);
|
|
226
|
+
*
|
|
227
|
+
* useEffect(() => {
|
|
228
|
+
* registry.register('todos', [
|
|
229
|
+
* {
|
|
230
|
+
* name: 'addTodo',
|
|
231
|
+
* description: 'Add a todo',
|
|
232
|
+
* parameters: { type: 'object', properties: { task: { type: 'string' } } },
|
|
233
|
+
* handler: async ({ task }) => {
|
|
234
|
+
* setTodos(prev => [...prev, { id: Date.now(), text: task }]);
|
|
235
|
+
* return { success: true };
|
|
236
|
+
* }
|
|
237
|
+
* }
|
|
238
|
+
* ]);
|
|
239
|
+
*
|
|
240
|
+
* return () => registry.unregister('todos');
|
|
241
|
+
* }, [registry, todos, setTodos]);
|
|
242
|
+
*
|
|
243
|
+
* return <TodoList />;
|
|
244
|
+
* }
|
|
245
|
+
*
|
|
246
|
+
* function ChatWidget() {
|
|
247
|
+
* const registry = useToolRegistry();
|
|
248
|
+
* const allTools = registry.getAllTools();
|
|
249
|
+
*
|
|
250
|
+
* return <InAppAI endpoint="..." tools={allTools} />;
|
|
251
|
+
* }
|
|
252
|
+
* ```
|
|
253
|
+
*
|
|
254
|
+
* @throws {Error} If used outside of ToolRegistryProvider
|
|
255
|
+
* @returns Tool registry instance
|
|
256
|
+
*/
|
|
257
|
+
declare function useToolRegistry(): ToolRegistry;
|
|
55
258
|
|
|
56
|
-
export { type CustomStyles, InAppAI, type InAppAIProps, type Tool };
|
|
259
|
+
export { type CustomStyles, InAppAI, type InAppAIProps, type Message, type Tool, type ToolRegistry, ToolRegistryProvider, type ToolRegistryProviderProps, type UseToolsOptions, type UseToolsReturn, useToolRegistry, useTools };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Sa=Object.create;var _=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Fa=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty;var ja=(t,o)=>{for(var p in o)_(t,p,{get:o[p],enumerable:!0})},ya=(t,o,p,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let s of Fa(o))!Ha.call(t,s)&&s!==p&&_(t,s,{get:()=>o[s],enumerable:!(n=Ua(o,s))||n.enumerable});return t};var Ya=(t,o,p)=>(p=t!=null?Sa(Wa(t)):{},ya(o||!t||!t.__esModule?_(p,"default",{value:t,enumerable:!0}):p,t)),Ka=t=>ya(_({},"__esModule",{value:!0}),t);var Va={};ja(Va,{InAppAI:()=>Ra,ToolRegistryProvider:()=>pa,useToolRegistry:()=>sa,useTools:()=>oa});module.exports=Ka(Va);var l=require("react"),ta=Ya(require("react-markdown")),Na=require("react-syntax-highlighter"),Ea=require("react-syntax-highlighter/dist/esm/styles/prism");var a=require("react/jsx-runtime"),Ca={};function wa(){return(0,a.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",background:"var(--inapp-ai-assistant-bg)",borderRadius:"var(--inapp-ai-border-radius)"},children:[(0,a.jsx)("div",{style:{height:"14px",background:"linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%)",backgroundSize:"200% 100%",animation:"shimmer 1.5s infinite",borderRadius:"4px"}}),(0,a.jsx)("div",{style:{height:"14px",width:"90%",background:"linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%)",backgroundSize:"200% 100%",animation:"shimmer 1.5s infinite",animationDelay:"0.1s",borderRadius:"4px"}}),(0,a.jsx)("div",{style:{height:"14px",width:"75%",background:"linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%)",backgroundSize:"200% 100%",animation:"shimmer 1.5s infinite",animationDelay:"0.2s",borderRadius:"4px"}}),(0,a.jsx)("style",{children:`
|
|
2
2
|
@keyframes shimmer {
|
|
3
3
|
0% { background-position: 200% 0; }
|
|
4
4
|
100% { background-position: -200% 0; }
|
|
5
5
|
}
|
|
6
|
-
`})]})}function
|
|
7
|
-
`),C=await fetch(`${n}/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:x,conversationId:W.current,context:l(),disableCache:!1})});if(!C.ok)throw new Error("Failed to get AI response for tool results");let H=await C.json(),U={id:`${Date.now()}-assistant`,role:"assistant",content:H.message||"I executed the tools successfully.",timestamp:new Date,usage:H.usage};R(b=>[...b,U])}else{let w={id:`${Date.now()}-assistant`,role:"assistant",content:g.message,timestamp:new Date,usage:g.usage};R(x=>[...x,w])}}catch(l){console.error("\u274C Error:",l),y(l instanceof Error?l.message:"Unknown error")}finally{Y(!1)}},ga=e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Z())},fa=()=>{R([]),W.current=`react-demo-${Date.now()}`},_=()=>{sa(!u)},aa=`inapp-ai-${o}`,ia=p&&p!=="light"?`inapp-ai-theme-${p}`:"",ba=s?`inapp-ai-sidebar inapp-ai-${r}`:d?`inapp-ai-panel inapp-ai-${r}`:"inapp-ai-popup",ua=u?"inapp-ai-folded":"",xa={...i.buttonBackgroundColor&&{background:i.buttonBackgroundColor},...i.buttonTextColor&&{color:i.buttonTextColor},...i.buttonSize&&{width:i.buttonSize,height:i.buttonSize,fontSize:`calc(${i.buttonSize} * 0.5)`},...i.buttonBorderRadius&&{borderRadius:i.buttonBorderRadius},...i.boxShadow&&{boxShadow:i.boxShadow}},ma={...i.windowWidth&&!s&&!d&&{width:i.windowWidth},...i.windowHeight&&!s&&!d&&{height:i.windowHeight},...i.windowBorderRadius&&{borderRadius:i.windowBorderRadius},...i.fontFamily&&{fontFamily:i.fontFamily},...i.fontSize&&{fontSize:i.fontSize},...i.sidebarWidth&&s&&!u&&{width:i.sidebarWidth},...i.sidebarFoldedWidth&&s&&u&&{width:i.sidebarFoldedWidth},...d&&{width:da}};return(0,a.jsxs)(a.Fragment,{children:[!s&&!d&&(0,a.jsxs)("button",{className:`inapp-ai-button ${aa} ${ia}`,style:xa,onClick:()=>L(!I),"aria-label":I?"Close AI Assistant":"Open AI Assistant","aria-expanded":I,"aria-haspopup":"dialog",tabIndex:0,children:[I?"\u2715":i.buttonIcon||"\u{1F916}",!v&&(0,a.jsx)("span",{className:"inapp-ai-offline-indicator",role:"status","aria-label":"Backend disconnected"})]}),I&&(0,a.jsxs)("div",{ref:G,role:"dialog","aria-label":"AI Assistant Chat","aria-modal":!s&&!d?"true":void 0,className:`inapp-ai-window ${ba} ${s||d?"":aa} ${ia} ${ua}`,style:ma,children:[d&&(0,a.jsx)("div",{className:`inapp-ai-resize-handle ${B?"inapp-ai-resize-handle-right":"inapp-ai-resize-handle-left"}`,onMouseDown:()=>J(!0),title:"Drag to resize"}),(s||d)&&u?(0,a.jsxs)("div",{className:"inapp-ai-folded-content",onClick:_,style:{cursor:"pointer"},title:"Click to unfold",children:[(0,a.jsx)("div",{className:"inapp-ai-folded-icon",children:i.buttonIcon||"\u{1F916}"}),(0,a.jsx)("div",{className:"inapp-ai-folded-text",children:"AI"}),h.length>0&&(0,a.jsx)("div",{className:"inapp-ai-message-count",children:h.length})]}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)("div",{className:"inapp-ai-header",style:{...i.headerBackground&&{background:i.headerBackground},...i.headerTextColor&&{color:i.headerTextColor}},children:[(0,a.jsxs)("div",{className:"inapp-ai-header-title",children:[(0,a.jsx)("span",{className:"inapp-ai-header-icon",children:i.buttonIcon||"\u{1F916}"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{children:i.headerTitle||"AI Assistant"}),(0,a.jsx)("p",{children:v?(0,a.jsxs)("span",{className:"inapp-ai-status-connected",children:[(0,a.jsx)("span",{className:"inapp-ai-status-dot"}),"Connected"]}):(0,a.jsxs)("span",{className:"inapp-ai-status-disconnected",children:[(0,a.jsx)("span",{className:"inapp-ai-status-dot"}),"Disconnected"]})})]})]}),(s||d)&&(0,a.jsx)("button",{className:"inapp-ai-header-fold-btn",onClick:_,"aria-label":u?`Unfold ${s?"sidebar":"panel"}`:`Fold ${s?"sidebar":"panel"}`,title:u?`Unfold ${s?"sidebar":"panel"}`:`Fold ${s?"sidebar":"panel"}`,children:ca||B?"\u25C0":"\u25B6"}),!s&&!d&&(0,a.jsx)("button",{className:"inapp-ai-close-btn",onClick:()=>L(!1),"aria-label":"Close",children:"\u2715"})]}),V&&(0,a.jsx)(Na,{error:V,onDismiss:()=>y(null)}),(0,a.jsxs)("div",{className:"inapp-ai-messages",role:"log","aria-live":"polite","aria-label":"Chat messages",children:[h.length===0?(0,a.jsxs)("div",{className:"inapp-ai-empty-state",role:"status",children:[(0,a.jsx)("div",{className:"inapp-ai-empty-icon","aria-hidden":"true",children:"\u{1F4AC}"}),(0,a.jsx)("h4",{children:"Start a conversation"}),(0,a.jsx)("p",{children:"Ask me anything! I'm powered by OpenAI."})]}):h.map(e=>(0,a.jsxs)("div",{className:`inapp-ai-message inapp-ai-message-${e.role}`,role:"article","aria-label":`${e.role==="user"?"User":"Assistant"} message`,children:[(0,a.jsx)("div",{className:"inapp-ai-message-icon","aria-hidden":"true",children:e.role==="user"?"\u{1F464}":"\u{1F916}"}),(0,a.jsxs)("div",{className:"inapp-ai-message-content",children:[(0,a.jsx)("div",{className:"inapp-ai-message-text",style:{...e.role==="user"&&i.userMessageBackground&&{background:i.userMessageBackground},...e.role==="user"&&i.userMessageColor&&{color:i.userMessageColor},...e.role==="assistant"&&i.assistantMessageBackground&&{background:i.assistantMessageBackground},...e.role==="assistant"&&i.assistantMessageColor&&{color:i.assistantMessageColor},...i.borderRadius&&{borderRadius:i.borderRadius}},children:e.role==="assistant"?(0,a.jsx)(na.default,{components:{code:Ta},children:e.content}):e.content}),(0,a.jsxs)("div",{className:"inapp-ai-message-time",children:[e.timestamp.toLocaleTimeString(),e.usage&&(0,a.jsxs)("span",{className:"inapp-ai-message-tokens",children:[" \u2022 ",e.usage.totalTokens," tokens"]})]})]})]},e.id)),f&&(0,a.jsxs)("div",{className:"inapp-ai-message inapp-ai-message-assistant",children:[(0,a.jsx)("div",{className:"inapp-ai-message-icon",children:(0,a.jsx)("div",{style:{animation:"pulse 2s infinite"},children:"\u{1F916}"})}),(0,a.jsx)("div",{className:"inapp-ai-message-content",children:(0,a.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(0,a.jsxs)("div",{className:"inapp-ai-typing-indicator",children:[(0,a.jsx)("span",{}),(0,a.jsx)("span",{}),(0,a.jsx)("span",{})]}),(0,a.jsx)(za,{})]})})]}),(0,a.jsx)("div",{ref:q})]}),(0,a.jsxs)("div",{className:"inapp-ai-input-area",role:"form","aria-label":"Message input",children:[h.length>0&&(0,a.jsxs)("button",{className:"inapp-ai-clear-btn",onClick:fa,disabled:f,"aria-label":"Clear conversation history",tabIndex:0,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:"\u{1F5D1}\uFE0F"})," Clear"]}),(0,a.jsxs)("div",{className:"inapp-ai-input-wrapper",children:[(0,a.jsx)("input",{ref:Q,type:"text",className:"inapp-ai-input",placeholder:i.inputPlaceholder||"Type your message...",value:F,onChange:e=>j(e.target.value),onKeyPress:ga,disabled:f||!v,"aria-label":"Message input","aria-describedby":"send-hint",tabIndex:0,style:{...i.inputBackground&&{background:i.inputBackground},...i.inputBorderColor&&{borderColor:i.inputBorderColor},...i.inputTextColor&&{color:i.inputTextColor}}}),(0,a.jsxs)("button",{className:"inapp-ai-send-btn",onClick:Z,disabled:f||!v||!F.trim(),"aria-label":"Send message",tabIndex:0,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:f?"\u23F3":"\u2B06"}),(0,a.jsx)("span",{className:"sr-only",children:f?"Sending...":"Send message"})]}),(0,a.jsx)("span",{id:"send-hint",className:"sr-only",children:"Press Enter to send"})]})]})]})]})]})}0&&(module.exports={InAppAI});
|
|
6
|
+
`})]})}function ka({error:t,onDismiss:o}){let n=(s=>s.includes("not responding")||s.includes("connection")||s.includes("network")?{type:"connection",icon:"\u{1F50C}",title:"Connection Error"}:s.includes("timeout")?{type:"timeout",icon:"\u23F1\uFE0F",title:"Request Timeout"}:s.includes("rate limit")?{type:"rateLimit",icon:"\u{1F6A6}",title:"Rate Limit"}:s.includes("authentication")||s.includes("unauthorized")?{type:"auth",icon:"\u{1F512}",title:"Authentication Error"}:{type:"generic",icon:"\u26A0\uFE0F",title:"Error"})(t);return(0,a.jsxs)("div",{className:"inapp-ai-error-banner",role:"alert","aria-live":"assertive",style:{display:"flex",alignItems:"flex-start",gap:"12px",padding:"14px 16px",background:"linear-gradient(135deg, #fff3cd 0%, #ffe9a6 100%)",borderLeft:"4px solid #ff9800",borderRadius:"0"},children:[(0,a.jsx)("span",{style:{fontSize:"20px"},children:n.icon}),(0,a.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,a.jsx)("div",{style:{fontWeight:600,marginBottom:"4px",color:"#856404"},children:n.title}),(0,a.jsx)("div",{style:{fontSize:"13px",color:"#856404",wordBreak:"break-word"},children:t}),n.type==="connection"&&(0,a.jsx)("div",{style:{fontSize:"12px",marginTop:"6px",color:"#997404"},children:"\u{1F4A1} Make sure the backend server is running on the correct port"})]}),(0,a.jsx)("button",{onClick:o,style:{background:"none",border:"none",color:"#856404",cursor:"pointer",padding:"4px 8px",fontSize:"16px",lineHeight:1},"aria-label":"Dismiss error",children:"\u2715"})]})}function Ta({inline:t,className:o,children:p,...n}){let[s,x]=(0,l.useState)(!1),v=/language-(\w+)/.exec(o||""),e=v?v[1]:"",k=String(p).replace(/\n$/,""),C=()=>{navigator.clipboard.writeText(k),x(!0),setTimeout(()=>x(!1),2e3)};return t?(0,a.jsx)("code",{className:o,...n,children:p}):(0,a.jsxs)("div",{style:{position:"relative",marginTop:"8px",marginBottom:"8px"},children:[(0,a.jsx)("button",{onClick:C,style:{position:"absolute",top:"8px",right:"8px",padding:"4px 8px",background:s?"#28a745":"rgba(255, 255, 255, 0.1)",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"12px",zIndex:1,transition:"background 0.2s"},"aria-label":"Copy code",children:s?"\u2713 Copied!":"\u{1F4CB} Copy"}),(0,a.jsx)(Na.Prism,{language:e||"text",style:Ea.vscDarkPlus,customStyle:{borderRadius:"8px",padding:"16px",fontSize:"13px",marginTop:0,marginBottom:0},...n,children:k})]})}function Ra({endpoint:t,agentId:o,position:p="bottom-right",displayMode:n="popup",defaultFolded:s=!1,theme:x="light",context:v,customStyles:e={},tools:k=[],panelMinWidth:C="20%",panelMaxWidth:r="33.33%",panelDefaultWidth:d="25%",onPanelResize:c,conversationId:M,messages:h,onMessagesChange:T,showHeader:da=!0}){if(h===void 0||T===void 0)throw new Error("InAppAI requires controlled mode. Please provide both `messages` and `onMessagesChange` props. See documentation for usage examples.");let W=t||typeof process<"u"&&process.env?.REACT_APP_INAPPAI_ENDPOINT||typeof Ca.env<"u"&&Ca.env?.VITE_INAPPAI_ENDPOINT||"https://api.inappai.com/api",J=(0,l.useRef)(h);(0,l.useEffect)(()=>{J.current=h},[h]);let N=h,H=i=>{let P=J.current,f=typeof i=="function"?i(P):i;J.current=f,T(f)},[D,q]=(0,l.useState)(n.startsWith("sidebar")||n.startsWith("panel")||n==="embedded"),[A,Pa]=(0,l.useState)(s&&(n.startsWith("sidebar")||n.startsWith("panel"))),[L,G]=(0,l.useState)(""),[u,la]=(0,l.useState)(!1),[E,ca]=(0,l.useState)(!1),[j,z]=(0,l.useState)(null),[Aa,za]=(0,l.useState)(d),[ga,fa]=(0,l.useState)(!1),Z=(0,l.useRef)(null),Ba=(0,l.useRef)(`react-demo-${Date.now()}`),ua=M||Ba.current,Q=(0,l.useRef)(null),aa=(0,l.useRef)(null),R=n==="embedded",g=n.startsWith("sidebar"),b=n.startsWith("panel"),Da=n==="sidebar-left",Y=n==="panel-left";(0,l.useEffect)(()=>{(g||b||R)&&q(!0)},[g,b,R]),(0,l.useEffect)(()=>{if(!b||!ga)return;let i=f=>{let S=Q.current?.parentElement;if(!S)return;let U=S.getBoundingClientRect(),y;Y?y=f.clientX:y=U.width-f.clientX;let $=y/U.width*100,B=parseFloat(C),O=parseFloat(r),ra=`${Math.max(B,Math.min(O,$))}%`;za(ra),c&&c(y)},P=()=>{fa(!1)};return document.addEventListener("mousemove",i),document.addEventListener("mouseup",P),()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",P)}},[ga,b,Y,C,r,c]),(0,l.useEffect)(()=>{let i=async()=>{try{(await fetch(`${W}/${o}/health`)).ok?(ca(!0),z(null)):z("Backend not responding")}catch{z("Failed to connect to backend"),ca(!1)}};i();let P=setInterval(i,3e4);return()=>clearInterval(P)},[W,o]),(0,l.useEffect)(()=>{Z.current?.scrollIntoView({behavior:"smooth"})},[N]),(0,l.useEffect)(()=>{!u&&E&&setTimeout(()=>{aa.current?.focus()},100)},[u,E]);let ea=async()=>{let i=L.trim();if(!i||u)return;let P={id:`${Date.now()}-user`,role:"user",content:i,timestamp:new Date};H(f=>[...f,P]),G(""),la(!0),z(null);try{let f=()=>typeof v=="function"?v():v,S=k.map(({name:$,description:B,parameters:O})=>({type:"function",function:{name:$,description:B,parameters:O}})),U=await fetch(`${W}/${o}/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i,conversationId:ua,context:f(),tools:S.length>0?S:void 0,disableCache:!1})});if(!U.ok)throw new Error("Failed to get response");let y=await U.json();if(y.toolCalls&&y.toolCalls.length>0){let B=(await Promise.all(y.toolCalls.map(async I=>{let K=I.function?.name||I.name,V=I.function?.arguments?JSON.parse(I.function.arguments):I.parameters,X=k.find(F=>F.name===K);if(!X)return{success:!1,error:`Tool '${K}' not found`};try{return await Promise.resolve(X.handler(V))}catch(F){return console.error(`Tool '${X.name}' failed:`,F),{success:!1,error:F.message}}}))).map((I,K)=>{let V=y.toolCalls[K];return`Tool "${V.function?.name||V.name}" result: ${JSON.stringify(I)}`}).join(`
|
|
7
|
+
`),O=await fetch(`${W}/${o}/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:B,conversationId:ua,context:f(),disableCache:!1})});if(!O.ok)throw new Error("Failed to get AI response for tool results");let na=await O.json(),ra={id:`${Date.now()}-assistant`,role:"assistant",content:na.message||"I executed the tools successfully.",timestamp:new Date,usage:na.usage};H(I=>[...I,ra])}else{let $={id:`${Date.now()}-assistant`,role:"assistant",content:y.message,timestamp:new Date,usage:y.usage};H(B=>[...B,$])}}catch(f){console.error("\u274C Error:",f),z(f instanceof Error?f.message:"Unknown error")}finally{la(!1)}},ba=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),ea())},ma=()=>{H([])},xa=()=>{Pa(!A)},ha=`inapp-ai-${p}`,ia=x&&x!=="light"?`inapp-ai-theme-${x}`:"",$a=R?"inapp-ai-embedded":g?`inapp-ai-sidebar inapp-ai-${n}`:b?`inapp-ai-panel inapp-ai-${n}`:"inapp-ai-popup",Oa=A?"inapp-ai-folded":"",La={...e.buttonBackgroundColor&&{background:e.buttonBackgroundColor},...e.buttonTextColor&&{color:e.buttonTextColor},...e.buttonSize&&{width:e.buttonSize,height:e.buttonSize,fontSize:`calc(${e.buttonSize} * 0.5)`},...e.buttonBorderRadius&&{borderRadius:e.buttonBorderRadius},...e.boxShadow&&{boxShadow:e.boxShadow}},va={...e.windowWidth&&!g&&!b&&{width:e.windowWidth},...e.windowHeight&&!g&&!b&&{height:e.windowHeight},...e.windowBorderRadius&&{borderRadius:e.windowBorderRadius},...e.fontFamily&&{fontFamily:e.fontFamily},...e.fontSize&&{fontSize:e.fontSize},...e.sidebarWidth&&g&&!A&&{width:e.sidebarWidth},...e.sidebarFoldedWidth&&g&&A&&{width:e.sidebarFoldedWidth},...b&&{width:Aa}};return R&&D?(0,a.jsxs)("div",{ref:Q,role:"region","aria-label":"AI Assistant Chat",className:`inapp-ai-window inapp-ai-embedded ${ia}`,style:va,children:[da&&(0,a.jsx)("div",{className:"inapp-ai-header",style:{...e.headerBackground&&{background:e.headerBackground},...e.headerTextColor&&{color:e.headerTextColor}},children:(0,a.jsxs)("div",{className:"inapp-ai-header-title",children:[(0,a.jsx)("span",{className:"inapp-ai-header-icon",children:e.buttonIcon||"\u{1F916}"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{children:e.headerTitle||"AI Assistant"}),(0,a.jsx)("p",{children:E?(0,a.jsxs)("span",{className:"inapp-ai-status-connected",children:[(0,a.jsx)("span",{className:"inapp-ai-status-dot"}),"Connected"]}):(0,a.jsxs)("span",{className:"inapp-ai-status-disconnected",children:[(0,a.jsx)("span",{className:"inapp-ai-status-dot"}),"Disconnected"]})})]})]})}),j&&(0,a.jsx)(ka,{error:j,onDismiss:()=>z(null)}),(0,a.jsxs)("div",{className:"inapp-ai-messages",role:"log","aria-live":"polite","aria-label":"Chat messages",children:[N.length===0?(0,a.jsxs)("div",{className:"inapp-ai-empty-state",role:"status",children:[(0,a.jsx)("div",{className:"inapp-ai-empty-icon","aria-hidden":"true",children:"\u{1F4AC}"}),(0,a.jsx)("h4",{children:"Start a conversation"}),(0,a.jsx)("p",{children:"How can I help you today?"})]}):N.map(i=>(0,a.jsxs)("div",{className:`inapp-ai-message inapp-ai-message-${i.role}`,role:"article","aria-label":`${i.role==="user"?"User":"Assistant"} message`,children:[(0,a.jsx)("div",{className:"inapp-ai-message-icon","aria-hidden":"true",children:i.role==="user"?"\u{1F464}":"\u{1F916}"}),(0,a.jsxs)("div",{className:"inapp-ai-message-content",children:[(0,a.jsx)("div",{className:"inapp-ai-message-text",style:{...i.role==="user"&&e.userMessageBackground&&{background:e.userMessageBackground},...i.role==="user"&&e.userMessageColor&&{color:e.userMessageColor},...i.role==="assistant"&&e.assistantMessageBackground&&{background:e.assistantMessageBackground},...i.role==="assistant"&&e.assistantMessageColor&&{color:e.assistantMessageColor},...e.borderRadius&&{borderRadius:e.borderRadius}},children:i.role==="assistant"?(0,a.jsx)(ta.default,{components:{code:Ta},children:i.content}):i.content}),(0,a.jsxs)("div",{className:"inapp-ai-message-time",children:[i.timestamp?new Date(i.timestamp).toLocaleTimeString():"",i.usage&&(0,a.jsxs)("span",{className:"inapp-ai-message-tokens",children:[" \u2022 ",i.usage.totalTokens," tokens"]})]})]})]},i.id)),u&&(0,a.jsxs)("div",{className:"inapp-ai-message inapp-ai-message-assistant",children:[(0,a.jsx)("div",{className:"inapp-ai-message-icon",children:(0,a.jsx)("div",{style:{animation:"pulse 2s infinite"},children:"\u{1F916}"})}),(0,a.jsx)("div",{className:"inapp-ai-message-content",children:(0,a.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(0,a.jsxs)("div",{className:"inapp-ai-typing-indicator",children:[(0,a.jsx)("span",{}),(0,a.jsx)("span",{}),(0,a.jsx)("span",{})]}),(0,a.jsx)(wa,{})]})})]}),(0,a.jsx)("div",{ref:Z})]}),(0,a.jsxs)("div",{className:"inapp-ai-input-area",role:"form","aria-label":"Message input",children:[N.length>0&&(0,a.jsxs)("button",{className:"inapp-ai-clear-btn",onClick:ma,disabled:u,"aria-label":"Clear conversation history",tabIndex:0,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:"\u{1F5D1}\uFE0F"})," Clear"]}),(0,a.jsxs)("div",{className:"inapp-ai-input-wrapper",children:[(0,a.jsx)("input",{ref:aa,type:"text",className:"inapp-ai-input",placeholder:e.inputPlaceholder||"Type your message...",value:L,onChange:i=>G(i.target.value),onKeyPress:ba,disabled:u||!E,"aria-label":"Message input","aria-describedby":"send-hint",tabIndex:0,style:{...e.inputBackground&&{background:e.inputBackground},...e.inputBorderColor&&{borderColor:e.inputBorderColor},...e.inputTextColor&&{color:e.inputTextColor}}}),(0,a.jsxs)("button",{className:"inapp-ai-send-btn",onClick:ea,disabled:u||!E||!L.trim(),"aria-label":"Send message",tabIndex:0,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:u?"\u23F3":"\u2B06"}),(0,a.jsx)("span",{className:"sr-only",children:u?"Sending...":"Send message"})]}),(0,a.jsx)("span",{id:"send-hint",className:"sr-only",children:"Press Enter to send"})]})]})]}):(0,a.jsxs)(a.Fragment,{children:[!g&&!b&&!R&&(0,a.jsxs)("button",{className:`inapp-ai-button ${ha} ${ia}`,style:La,onClick:()=>q(!D),"aria-label":D?"Close AI Assistant":"Open AI Assistant","aria-expanded":D,"aria-haspopup":"dialog",tabIndex:0,children:[D?"\u2715":e.buttonIcon||"\u{1F916}",!E&&(0,a.jsx)("span",{className:"inapp-ai-offline-indicator",role:"status","aria-label":"Backend disconnected"})]}),D&&(0,a.jsxs)("div",{ref:Q,role:R?"region":"dialog","aria-label":"AI Assistant Chat","aria-modal":!g&&!b&&!R?"true":void 0,className:`inapp-ai-window ${$a} ${g||b||R?"":ha} ${ia} ${Oa}`,style:va,children:[b&&(0,a.jsx)("div",{className:`inapp-ai-resize-handle ${Y?"inapp-ai-resize-handle-right":"inapp-ai-resize-handle-left"}`,onMouseDown:()=>fa(!0),title:"Drag to resize"}),(g||b)&&A?(0,a.jsxs)("div",{className:"inapp-ai-folded-content",onClick:xa,style:{cursor:"pointer"},title:"Click to unfold",children:[(0,a.jsx)("div",{className:"inapp-ai-folded-icon",children:e.buttonIcon||"\u{1F916}"}),(0,a.jsx)("div",{className:"inapp-ai-folded-text",children:"AI"}),N.length>0&&(0,a.jsx)("div",{className:"inapp-ai-message-count",children:N.length})]}):(0,a.jsxs)(a.Fragment,{children:[da&&(0,a.jsxs)("div",{className:"inapp-ai-header",style:{...e.headerBackground&&{background:e.headerBackground},...e.headerTextColor&&{color:e.headerTextColor}},children:[(0,a.jsxs)("div",{className:"inapp-ai-header-title",children:[(0,a.jsx)("span",{className:"inapp-ai-header-icon",children:e.buttonIcon||"\u{1F916}"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("h3",{children:e.headerTitle||"AI Assistant"}),(0,a.jsx)("p",{children:E?(0,a.jsxs)("span",{className:"inapp-ai-status-connected",children:[(0,a.jsx)("span",{className:"inapp-ai-status-dot"}),"Connected"]}):(0,a.jsxs)("span",{className:"inapp-ai-status-disconnected",children:[(0,a.jsx)("span",{className:"inapp-ai-status-dot"}),"Disconnected"]})})]})]}),(g||b)&&(0,a.jsx)("button",{className:"inapp-ai-header-fold-btn",onClick:xa,"aria-label":A?`Unfold ${g?"sidebar":"panel"}`:`Fold ${g?"sidebar":"panel"}`,title:A?`Unfold ${g?"sidebar":"panel"}`:`Fold ${g?"sidebar":"panel"}`,children:Da||Y?"\u25C0":"\u25B6"}),!g&&!b&&!R&&(0,a.jsx)("button",{className:"inapp-ai-close-btn",onClick:()=>q(!1),"aria-label":"Close",children:"\u2715"})]}),j&&(0,a.jsx)(ka,{error:j,onDismiss:()=>z(null)}),(0,a.jsxs)("div",{className:"inapp-ai-messages",role:"log","aria-live":"polite","aria-label":"Chat messages",children:[N.length===0?(0,a.jsxs)("div",{className:"inapp-ai-empty-state",role:"status",children:[(0,a.jsx)("div",{className:"inapp-ai-empty-icon","aria-hidden":"true",children:"\u{1F4AC}"}),(0,a.jsx)("h4",{children:"Start a conversation"}),(0,a.jsx)("p",{children:"How can I help you today?"})]}):N.map(i=>(0,a.jsxs)("div",{className:`inapp-ai-message inapp-ai-message-${i.role}`,role:"article","aria-label":`${i.role==="user"?"User":"Assistant"} message`,children:[(0,a.jsx)("div",{className:"inapp-ai-message-icon","aria-hidden":"true",children:i.role==="user"?"\u{1F464}":"\u{1F916}"}),(0,a.jsxs)("div",{className:"inapp-ai-message-content",children:[(0,a.jsx)("div",{className:"inapp-ai-message-text",style:{...i.role==="user"&&e.userMessageBackground&&{background:e.userMessageBackground},...i.role==="user"&&e.userMessageColor&&{color:e.userMessageColor},...i.role==="assistant"&&e.assistantMessageBackground&&{background:e.assistantMessageBackground},...i.role==="assistant"&&e.assistantMessageColor&&{color:e.assistantMessageColor},...e.borderRadius&&{borderRadius:e.borderRadius}},children:i.role==="assistant"?(0,a.jsx)(ta.default,{components:{code:Ta},children:i.content}):i.content}),(0,a.jsxs)("div",{className:"inapp-ai-message-time",children:[i.timestamp?.toLocaleTimeString()||"",i.usage&&(0,a.jsxs)("span",{className:"inapp-ai-message-tokens",children:[" \u2022 ",i.usage.totalTokens," tokens"]})]})]})]},i.id)),u&&(0,a.jsxs)("div",{className:"inapp-ai-message inapp-ai-message-assistant",children:[(0,a.jsx)("div",{className:"inapp-ai-message-icon",children:(0,a.jsx)("div",{style:{animation:"pulse 2s infinite"},children:"\u{1F916}"})}),(0,a.jsx)("div",{className:"inapp-ai-message-content",children:(0,a.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[(0,a.jsxs)("div",{className:"inapp-ai-typing-indicator",children:[(0,a.jsx)("span",{}),(0,a.jsx)("span",{}),(0,a.jsx)("span",{})]}),(0,a.jsx)(wa,{})]})})]}),(0,a.jsx)("div",{ref:Z})]}),(0,a.jsxs)("div",{className:"inapp-ai-input-area",role:"form","aria-label":"Message input",children:[N.length>0&&(0,a.jsxs)("button",{className:"inapp-ai-clear-btn",onClick:ma,disabled:u,"aria-label":"Clear conversation history",tabIndex:0,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:"\u{1F5D1}\uFE0F"})," Clear"]}),(0,a.jsxs)("div",{className:"inapp-ai-input-wrapper",children:[(0,a.jsx)("input",{ref:aa,type:"text",className:"inapp-ai-input",placeholder:e.inputPlaceholder||"Type your message...",value:L,onChange:i=>G(i.target.value),onKeyPress:ba,disabled:u||!E,"aria-label":"Message input","aria-describedby":"send-hint",tabIndex:0,style:{...e.inputBackground&&{background:e.inputBackground},...e.inputBorderColor&&{borderColor:e.inputBorderColor},...e.inputTextColor&&{color:e.inputTextColor}}}),(0,a.jsxs)("button",{className:"inapp-ai-send-btn",onClick:ea,disabled:u||!E||!L.trim(),"aria-label":"Send message",tabIndex:0,children:[(0,a.jsx)("span",{"aria-hidden":"true",children:u?"\u23F3":"\u2B06"}),(0,a.jsx)("span",{className:"sr-only",children:u?"Sending...":"Send message"})]}),(0,a.jsx)("span",{id:"send-hint",className:"sr-only",children:"Press Enter to send"})]})]})]})]})]})}var w=require("react");function oa(t={}){let{initialTools:o=[],autoCleanup:p=!0}=t,n=(0,w.useRef)(new Set),[s,x]=(0,w.useState)(()=>(o.forEach(r=>{n.current.has(r.name)?console.warn(`[useTools] Duplicate tool name in initialTools: "${r.name}". Only the first occurrence will be used.`):n.current.add(r.name)}),o.filter((r,d)=>o.findIndex(c=>c.name===r.name)===d))),v=(0,w.useCallback)(r=>{if(!r.name)throw new Error("[useTools] Tool must have a name");if(n.current.has(r.name)){console.warn(`[useTools] Tool "${r.name}" is already registered. Use unregisterTool() first if you want to replace it.`);return}if(r.description||console.warn(`[useTools] Tool "${r.name}" is missing description`),r.parameters||console.warn(`[useTools] Tool "${r.name}" is missing parameters schema`),typeof r.handler!="function")throw new Error(`[useTools] Tool "${r.name}" must have a handler function`);n.current.add(r.name),x(d=>[...d,r])},[]),e=(0,w.useCallback)(r=>{if(!n.current.has(r)){console.warn(`[useTools] Tool "${r}" is not registered`);return}n.current.delete(r),x(d=>d.filter(c=>c.name!==r))},[]),k=(0,w.useCallback)(()=>{n.current.clear(),x([])},[]),C=(0,w.useCallback)(r=>n.current.has(r),[]);return(0,w.useEffect)(()=>{if(p)return()=>{n.current.clear()}},[p]),{tools:s,registerTool:v,unregisterTool:e,clearTools:k,hasTool:C}}var m=require("react"),Ma=require("react/jsx-runtime"),Ia=(0,m.createContext)(null);function pa({children:t,initialTools:o={}}){let[p,n]=(0,m.useState)(()=>new Map(Object.entries(o))),s=(0,m.useCallback)((d,c)=>{if(!d||typeof d!="string")throw new Error("[ToolRegistry] Namespace must be a non-empty string");if(!/^[a-zA-Z0-9_-]+$/.test(d))throw new Error(`[ToolRegistry] Invalid namespace "${d}". Use only alphanumeric characters, hyphens, and underscores.`);if(!Array.isArray(c))throw new Error("[ToolRegistry] Tools must be an array");let M=new Set;c.forEach(h=>{M.has(h.name)&&console.warn(`[ToolRegistry] Duplicate tool name in namespace "${d}": "${h.name}"`),M.add(h.name)}),n(h=>{let T=new Map(h);return T.set(d,c),T})},[]),x=(0,m.useCallback)(d=>{n(c=>{if(!c.has(d))return console.warn(`[ToolRegistry] Namespace "${d}" is not registered`),c;let M=new Map(c);return M.delete(d),M})},[]),v=(0,m.useCallback)(d=>p.get(d)||[],[p]),e=(0,m.useCallback)(()=>{let d=[],c=new Set;for(let[M,h]of p.entries())for(let T of h){if(c.has(T.name)){console.warn(`[ToolRegistry] Tool name conflict: "${T.name}" exists in multiple namespaces. Only the first occurrence will be used.`);continue}c.add(T.name),d.push(T)}return d},[p]),k=(0,m.useCallback)(()=>{n(new Map)},[]),C=(0,m.useCallback)(()=>Array.from(p.keys()),[p]),r=(0,m.useMemo)(()=>({register:s,unregister:x,getTools:v,getAllTools:e,clear:k,getNamespaces:C}),[s,x,v,e,k,C]);return(0,Ma.jsx)(Ia.Provider,{value:r,children:t})}function sa(){let t=(0,m.useContext)(Ia);if(!t)throw new Error("[useToolRegistry] must be used within a ToolRegistryProvider. Wrap your component tree with <ToolRegistryProvider>.");return t}0&&(module.exports={InAppAI,ToolRegistryProvider,useToolRegistry,useTools});
|
|
8
8
|
//# sourceMappingURL=index.js.map
|