floating-copilot-widget 1.4.3 → 1.5.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.
@@ -0,0 +1,281 @@
1
+ /**
2
+ * API Integration Examples
3
+ *
4
+ * This file provides examples of how to create and configure API integrations
5
+ * for use with the Copilot chat widget.
6
+ */
7
+ /**
8
+ * Example: Customer Creation API with Required Parameters
9
+ *
10
+ * This example shows how to integrate an API that creates a customer
11
+ * with interactive parameter collection
12
+ */
13
+ export const createCustomerAPIIntegration = (baseUrl) => {
14
+ const requiredParams = [
15
+ {
16
+ name: 'name',
17
+ description: 'Customer full name',
18
+ type: 'string',
19
+ required: true,
20
+ example: 'John Doe'
21
+ },
22
+ {
23
+ name: 'email',
24
+ description: 'Customer email address',
25
+ type: 'email',
26
+ required: true,
27
+ validation: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$',
28
+ example: 'john@example.com'
29
+ },
30
+ {
31
+ name: 'phone',
32
+ description: 'Customer phone number',
33
+ type: 'phone',
34
+ required: true,
35
+ example: '+1-555-123-4567'
36
+ },
37
+ {
38
+ name: 'company',
39
+ description: 'Company name (optional)',
40
+ type: 'string',
41
+ required: false,
42
+ example: 'Acme Corp'
43
+ }
44
+ ];
45
+ return {
46
+ id: 'create_customer',
47
+ name: 'Create Customer',
48
+ endpoint: `${baseUrl}/api/customers`,
49
+ method: 'POST',
50
+ intents: ['create_customer', 'add_customer', 'new_customer'],
51
+ requiredParameters: requiredParams,
52
+ buildRequest: (params) => ({
53
+ name: params.name,
54
+ email: params.email,
55
+ phone: params.phone,
56
+ company: params.company || null,
57
+ createdAt: new Date().toISOString()
58
+ }),
59
+ formatResponse: (data) => {
60
+ return `✅ **Customer Created Successfully**\n\n` +
61
+ `**ID**: ${data.id}\n` +
62
+ `**Name**: ${data.name}\n` +
63
+ `**Email**: ${data.email}\n` +
64
+ `**Phone**: ${data.phone}\n` +
65
+ (data.company ? `**Company**: ${data.company}\n` : '') +
66
+ `**Created**: ${new Date(data.createdAt).toLocaleDateString()}`;
67
+ },
68
+ shouldCall: (intent, params) => {
69
+ // Call when all required params are present
70
+ return !!(params.name && params.email && params.phone);
71
+ }
72
+ };
73
+ };
74
+ /**
75
+ * Example: REST API Integration
76
+ *
77
+ * This example shows how to integrate a generic REST API that returns user data
78
+ */
79
+ export const createUserAPIIntegration = (baseUrl) => ({
80
+ id: 'user_api',
81
+ name: 'User Service API',
82
+ endpoint: `${baseUrl}/api/users`,
83
+ method: 'GET',
84
+ intents: ['get_user', 'find_user', 'lookup_user'],
85
+ buildRequest: (params) => {
86
+ // Transform intent parameters into API query string
87
+ const queryParams = new URLSearchParams();
88
+ if (params.userId)
89
+ queryParams.append('id', params.userId);
90
+ if (params.username)
91
+ queryParams.append('username', params.username);
92
+ if (params.email)
93
+ queryParams.append('email', params.email);
94
+ return queryParams.toString();
95
+ },
96
+ formatResponse: (data) => {
97
+ if (Array.isArray(data)) {
98
+ return data.map(user => `**${user.name}** (${user.email})\nID: ${user.id}\nRole: ${user.role}`).join('\n\n');
99
+ }
100
+ return `**${data.name}** (${data.email})\nID: ${data.id}\nRole: ${data.role}`;
101
+ },
102
+ shouldCall: (intent, params) => {
103
+ // Only call if we have identifying parameters
104
+ return !!(params.userId || params.username || params.email);
105
+ }
106
+ });
107
+ /**
108
+ * Example: Data Analysis API Integration
109
+ *
110
+ * This shows how to integrate an API that performs data analysis
111
+ */
112
+ export const createAnalysisAPIIntegration = (baseUrl) => ({
113
+ id: 'analysis_api',
114
+ name: 'Data Analysis Service',
115
+ endpoint: `${baseUrl}/api/analysis`,
116
+ method: 'POST',
117
+ intents: ['analyze_data', 'generate_report', 'data_insights'],
118
+ buildRequest: (params) => ({
119
+ dataSource: params.dataSource,
120
+ analysisType: params.analysisType || 'summary',
121
+ timeRange: params.timeRange,
122
+ filters: params.filters || {}
123
+ }),
124
+ formatResponse: (data) => {
125
+ let response = `## Analysis Results\n\n`;
126
+ if (data.summary) {
127
+ response += `### Summary\n${data.summary}\n\n`;
128
+ }
129
+ if (data.metrics) {
130
+ response += `### Key Metrics\n`;
131
+ Object.entries(data.metrics).forEach(([key, value]) => {
132
+ response += `- **${key}**: ${value}\n`;
133
+ });
134
+ response += '\n';
135
+ }
136
+ if (data.recommendations) {
137
+ response += `### Recommendations\n`;
138
+ data.recommendations.forEach((rec) => {
139
+ response += `- ${rec}\n`;
140
+ });
141
+ }
142
+ return response;
143
+ },
144
+ shouldCall: (intent, params) => {
145
+ return !!(params.dataSource && params.analysisType);
146
+ }
147
+ });
148
+ /**
149
+ * Example: Search API Integration
150
+ *
151
+ * Shows how to integrate a search/query API
152
+ */
153
+ export const createSearchAPIIntegration = (baseUrl) => ({
154
+ id: 'search_api',
155
+ name: 'Search Service',
156
+ endpoint: `${baseUrl}/api/search`,
157
+ method: 'POST',
158
+ intents: ['search', 'find', 'query'],
159
+ buildRequest: (params) => ({
160
+ query: params.query,
161
+ filters: {
162
+ type: params.type,
163
+ category: params.category,
164
+ dateRange: params.dateRange
165
+ },
166
+ limit: params.limit || 10,
167
+ offset: params.offset || 0
168
+ }),
169
+ formatResponse: (data) => {
170
+ if (!data.results || data.results.length === 0) {
171
+ return 'No results found matching your search criteria.';
172
+ }
173
+ let response = `Found **${data.results.length}** results:\n\n`;
174
+ response += data.results.map((result, index) => `${index + 1}. **${result.title}**\n ${result.description}\n URL: ${result.url}`).join('\n\n');
175
+ return response;
176
+ }
177
+ });
178
+ /**
179
+ * Example: Webhook/Action API Integration
180
+ *
181
+ * Shows how to integrate APIs that perform actions (create, update, delete)
182
+ */
183
+ export const createActionAPIIntegration = (baseUrl) => ({
184
+ id: 'action_api',
185
+ name: 'Action Service',
186
+ endpoint: `${baseUrl}/api/actions`,
187
+ method: 'POST',
188
+ intents: ['create', 'update', 'delete', 'perform_action'],
189
+ buildRequest: (params) => ({
190
+ action: params.action,
191
+ targetId: params.targetId,
192
+ targetType: params.targetType,
193
+ payload: params.payload || {},
194
+ metadata: params.metadata || {}
195
+ }),
196
+ formatResponse: (data) => {
197
+ if (data.success) {
198
+ return `✅ **Action Completed Successfully**\n\n${data.message || 'The requested action has been performed.'}\n\nDetails: ${JSON.stringify(data.result, null, 2)}`;
199
+ }
200
+ return `❌ **Action Failed**\n\n${data.message || 'The requested action could not be completed.'}`;
201
+ }
202
+ });
203
+ /**
204
+ * Example: Database Query Integration
205
+ *
206
+ * Shows how to integrate a database query service
207
+ */
208
+ export const createDatabaseAPIIntegration = (baseUrl) => ({
209
+ id: 'database_api',
210
+ name: 'Database Query Service',
211
+ endpoint: `${baseUrl}/api/query`,
212
+ method: 'POST',
213
+ intents: ['query_database', 'get_data', 'fetch_records'],
214
+ buildRequest: (params) => ({
215
+ table: params.table,
216
+ columns: params.columns || ['*'],
217
+ where: params.where || {},
218
+ orderBy: params.orderBy,
219
+ limit: params.limit || 50
220
+ }),
221
+ formatResponse: (data) => {
222
+ if (!data.rows || data.rows.length === 0) {
223
+ return 'No records found matching your query.';
224
+ }
225
+ let response = `Retrieved **${data.rows.length}** records:\n\n`;
226
+ // Format as table if we have column information
227
+ if (data.columns && data.columns.length > 0) {
228
+ response += `| ${data.columns.join(' | ')} |\n`;
229
+ response += `|${data.columns.map(() => '-').join('|')}|\n`;
230
+ data.rows.forEach((row) => {
231
+ response += `| ${data.columns.map((col) => row[col] || '-').join(' | ')} |\n`;
232
+ });
233
+ }
234
+ else {
235
+ // Fallback: display as JSON
236
+ response += '```json\n' + JSON.stringify(data.rows, null, 2) + '\n```';
237
+ }
238
+ return response;
239
+ }
240
+ });
241
+ /**
242
+ * Example: External Service Integration (Weather, News, etc.)
243
+ */
244
+ export const createWeatherAPIIntegration = (apiKey) => ({
245
+ id: 'weather_api',
246
+ name: 'Weather Service',
247
+ endpoint: 'https://api.openweathermap.org/data/2.5/weather',
248
+ method: 'GET',
249
+ headers: {
250
+ 'User-Agent': 'FloatingCopilot/1.0'
251
+ },
252
+ intents: ['get_weather', 'weather', 'check_weather'],
253
+ buildRequest: (params) => {
254
+ // Note: For actual use, pass apiKey securely
255
+ return {
256
+ q: params.city,
257
+ appid: apiKey,
258
+ units: params.units || 'metric'
259
+ };
260
+ },
261
+ formatResponse: (data) => {
262
+ var _a, _b, _c;
263
+ const weather = (_a = data.weather) === null || _a === void 0 ? void 0 : _a[0];
264
+ const main = data.main;
265
+ return `**Weather for ${data.name}, ${(_b = data.sys) === null || _b === void 0 ? void 0 : _b.country}**
266
+
267
+ Current: ${weather === null || weather === void 0 ? void 0 : weather.main} (${weather === null || weather === void 0 ? void 0 : weather.description})
268
+ Temperature: ${main === null || main === void 0 ? void 0 : main.temp}°C
269
+ Feels like: ${main === null || main === void 0 ? void 0 : main.feels_like}°C
270
+ Humidity: ${main === null || main === void 0 ? void 0 : main.humidity}%
271
+ Wind Speed: ${(_c = data.wind) === null || _c === void 0 ? void 0 : _c.speed} m/s
272
+
273
+ Updated: ${new Date(data.dt * 1000).toLocaleString()}`;
274
+ }
275
+ });
276
+ /**
277
+ * Helper function to create a custom API integration
278
+ */
279
+ export function createCustomAPIIntegration(config) {
280
+ return config;
281
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Copilot Integration Types
3
+ *
4
+ * Defines interfaces and types for GitHub Copilot integration
5
+ * with the floating chat widget.
6
+ */
7
+ export interface CopilotConfig {
8
+ /**
9
+ * GitHub Personal Access Token for Copilot API access
10
+ * Required scopes: copilot, read:user
11
+ *
12
+ * Can be provided explicitly or read from environment variables:
13
+ * - GITHUB_TOKEN
14
+ * - VITE_GITHUB_TOKEN (for Vite projects)
15
+ * - REACT_APP_GITHUB_TOKEN (for Create React App)
16
+ *
17
+ * If not provided, the service will automatically check environment variables.
18
+ */
19
+ githubToken?: string;
20
+ /**
21
+ * AI model to use (default: gpt-4o)
22
+ */
23
+ model?: string;
24
+ /**
25
+ * Maximum tokens for API responses (default: 2000)
26
+ */
27
+ maxTokens?: number;
28
+ /**
29
+ * Temperature for response generation (0-1, default: 0.3)
30
+ */
31
+ temperature?: number;
32
+ }
33
+ export interface CopilotIntentRequest {
34
+ /**
35
+ * User message or query
36
+ */
37
+ userMessage: string;
38
+ /**
39
+ * Context data from the application
40
+ */
41
+ context?: Record<string, any>;
42
+ /**
43
+ * Custom instructions for intent analysis
44
+ */
45
+ customInstructions?: string;
46
+ }
47
+ export interface ParameterDefinition {
48
+ /**
49
+ * Parameter name/key
50
+ */
51
+ name: string;
52
+ /**
53
+ * User-friendly description for prompting
54
+ */
55
+ description: string;
56
+ /**
57
+ * Data type: string, number, email, phone, date, etc.
58
+ */
59
+ type?: string;
60
+ /**
61
+ * Is this parameter required?
62
+ */
63
+ required?: boolean;
64
+ /**
65
+ * Validation regex pattern
66
+ */
67
+ validation?: string;
68
+ /**
69
+ * Example value to show user
70
+ */
71
+ example?: string;
72
+ }
73
+ export interface CopilotIntentResponse {
74
+ /**
75
+ * Identified intent of the user message
76
+ */
77
+ intent: string;
78
+ /**
79
+ * Confidence score (0-1)
80
+ */
81
+ confidence: number;
82
+ /**
83
+ * Extracted parameters from the user message
84
+ */
85
+ parameters: Record<string, any>;
86
+ /**
87
+ * Suggested API endpoints to call
88
+ */
89
+ suggestedApis: string[];
90
+ /**
91
+ * Raw response from Copilot
92
+ */
93
+ rawResponse: string;
94
+ /**
95
+ * Required parameters for the API (if parameter collection is needed)
96
+ */
97
+ requiredParameters?: ParameterDefinition[];
98
+ /**
99
+ * Parameters that are still missing
100
+ */
101
+ missingParameters?: string[];
102
+ }
103
+ export interface APIIntegration {
104
+ /**
105
+ * Unique identifier for this API
106
+ */
107
+ id: string;
108
+ /**
109
+ * API name/description
110
+ */
111
+ name: string;
112
+ /**
113
+ * API endpoint URL
114
+ */
115
+ endpoint: string;
116
+ /**
117
+ * HTTP method (GET, POST, PUT, DELETE, etc.)
118
+ */
119
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
120
+ /**
121
+ * Headers to include in the request
122
+ */
123
+ headers?: Record<string, string>;
124
+ /**
125
+ * Intents that should trigger this API
126
+ */
127
+ intents?: string[];
128
+ /**
129
+ * Required parameters for this API
130
+ * If provided, system will interactively collect missing parameters
131
+ */
132
+ requiredParameters?: ParameterDefinition[];
133
+ /**
134
+ * Function to transform user message into API request
135
+ */
136
+ buildRequest: (params: Record<string, any>, context?: Record<string, any>) => any;
137
+ /**
138
+ * Function to format API response for display
139
+ */
140
+ formatResponse: (data: any) => string;
141
+ /**
142
+ * Optional: Function to check if this API should be called for a given intent
143
+ */
144
+ shouldCall?: (intent: string, parameters: Record<string, any>) => boolean;
145
+ }
146
+ export interface APICallRequest {
147
+ /**
148
+ * API integration ID
149
+ */
150
+ apiId: string;
151
+ /**
152
+ * Parameters extracted from user intent
153
+ */
154
+ parameters: Record<string, any>;
155
+ /**
156
+ * Application context
157
+ */
158
+ context?: Record<string, any>;
159
+ }
160
+ export interface APICallResponse {
161
+ /**
162
+ * Success status
163
+ */
164
+ success: boolean;
165
+ /**
166
+ * Formatted response data
167
+ */
168
+ data?: string;
169
+ /**
170
+ * Raw API response (for debugging)
171
+ */
172
+ rawData?: any;
173
+ /**
174
+ * Error message if failed
175
+ */
176
+ error?: string;
177
+ /**
178
+ * API that was called
179
+ */
180
+ apiName?: string;
181
+ }
182
+ export interface CopilotChatMessage {
183
+ /**
184
+ * Role of the message sender
185
+ */
186
+ role: 'user' | 'assistant' | 'system';
187
+ /**
188
+ * Message content
189
+ */
190
+ content: string;
191
+ /**
192
+ * Associated API call if this was generated from API
193
+ */
194
+ apiCall?: {
195
+ apiId: string;
196
+ apiName: string;
197
+ rawData: any;
198
+ };
199
+ /**
200
+ * Intent information if this was intent analysis
201
+ */
202
+ intent?: {
203
+ intent: string;
204
+ confidence: number;
205
+ parameters: Record<string, any>;
206
+ };
207
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copilot Integration Types
3
+ *
4
+ * Defines interfaces and types for GitHub Copilot integration
5
+ * with the floating chat widget.
6
+ */
7
+ export {};
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { CopilotConfig, APIIntegration } from './types/copilot';
1
2
  export interface FloatingCopilotConfig {
2
3
  position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
3
4
  width?: number;
@@ -24,5 +25,11 @@ export interface FloatingCopilotConfig {
24
25
  showMaximizeBtn?: boolean;
25
26
  showCloseBtn?: boolean;
26
27
  headerContent?: string;
28
+ copilot?: {
29
+ config: CopilotConfig;
30
+ apiIntegrations?: APIIntegration[];
31
+ enabled?: boolean;
32
+ showIntentAnalysis?: boolean;
33
+ };
27
34
  }
28
35
  export declare const defaultConfig: FloatingCopilotConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "floating-copilot-widget",
3
- "version": "1.4.3",
3
+ "version": "1.5.1",
4
4
  "description": "A highly configurable floating chat widget plugin for React websites. Draggable, resizable, themeable, and production-ready.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",