humanbehavior-js 0.4.7 → 0.4.9
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/dist/cjs/angular/index.cjs +13 -14
- package/dist/cjs/angular/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +14 -15
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/install-wizard.cjs +4 -2
- package/dist/cjs/install-wizard.cjs.map +1 -1
- package/dist/cjs/react/index.cjs +13 -14
- package/dist/cjs/react/index.cjs.map +1 -1
- package/dist/cjs/remix/index.cjs +13 -14
- package/dist/cjs/remix/index.cjs.map +1 -1
- package/dist/cjs/svelte/index.cjs +13 -14
- package/dist/cjs/svelte/index.cjs.map +1 -1
- package/dist/cjs/vue/index.cjs +13 -14
- package/dist/cjs/vue/index.cjs.map +1 -1
- package/dist/cjs/wizard/index.cjs +3208 -0
- package/dist/cjs/wizard/index.cjs.map +1 -0
- package/dist/cli/ai-auto-install.js +2024 -0
- package/dist/cli/ai-auto-install.js.map +1 -0
- package/dist/cli/auto-install.js +4 -2
- package/dist/cli/auto-install.js.map +1 -1
- package/dist/esm/angular/index.js +13 -14
- package/dist/esm/angular/index.js.map +1 -1
- package/dist/esm/index.js +14 -15
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/install-wizard.js +4 -2
- package/dist/esm/install-wizard.js.map +1 -1
- package/dist/esm/react/index.js +13 -14
- package/dist/esm/react/index.js.map +1 -1
- package/dist/esm/remix/index.js +13 -14
- package/dist/esm/remix/index.js.map +1 -1
- package/dist/esm/svelte/index.js +13 -14
- package/dist/esm/svelte/index.js.map +1 -1
- package/dist/esm/vue/index.js +13 -14
- package/dist/esm/vue/index.js.map +1 -1
- package/dist/esm/wizard/index.js +3178 -0
- package/dist/esm/wizard/index.js.map +1 -0
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +1 -1
- package/dist/types/install-wizard.d.ts +8 -8
- package/dist/types/wizard/index.d.ts +489 -0
- package/package.json +14 -8
- package/rollup.config.js +65 -3
- package/src/api.ts +9 -9
- package/src/react/AutoInstallWizard.tsx +1 -1
- package/src/tracker.ts +6 -7
- package/src/wizard/README.md +114 -0
- package/src/wizard/ai/ai-install-wizard.ts +894 -0
- package/src/wizard/ai/manual-framework-wizard.ts +236 -0
- package/src/wizard/cli/ai-auto-install.ts +369 -0
- package/src/{cli → wizard/cli}/auto-install.ts +1 -1
- package/src/{install-wizard.ts → wizard/core/install-wizard.ts} +12 -10
- package/src/wizard/index.ts +23 -0
- package/src/wizard/services/centralized-ai-service.ts +668 -0
- package/src/wizard/services/remote-ai-service.ts +224 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HumanBehavior SDK Wizard Module
|
|
3
|
+
*
|
|
4
|
+
* This module provides AI-enhanced auto-installation capabilities for the HumanBehavior SDK.
|
|
5
|
+
* It includes traditional installation, AI-powered analysis, and centralized AI services.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// Core wizard components
|
|
9
|
+
export { AutoInstallationWizard, FrameworkInfo, CodeModification, InstallationResult } from './core/install-wizard';
|
|
10
|
+
|
|
11
|
+
// AI-enhanced wizard components
|
|
12
|
+
export { AIEnhancedInstallationWizard, AIBrowserInstallationWizard, AICodeAnalysis, AIInstallationResult } from './ai/ai-install-wizard';
|
|
13
|
+
|
|
14
|
+
// CLI components
|
|
15
|
+
export { AIAutoInstallCLI } from './cli/ai-auto-install';
|
|
16
|
+
export { AutoInstallCLI } from './cli/auto-install';
|
|
17
|
+
|
|
18
|
+
// AI services
|
|
19
|
+
export { RemoteAIService, RemoteAIServiceConfig } from './services/remote-ai-service';
|
|
20
|
+
export { CentralizedAIService, CentralizedAIServiceConfig } from './services/centralized-ai-service';
|
|
21
|
+
|
|
22
|
+
// Re-export main wizard for backward compatibility
|
|
23
|
+
export { AutoInstallationWizard as InstallWizard } from './core/install-wizard';
|
|
@@ -0,0 +1,668 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized AI Service Implementation
|
|
3
|
+
*
|
|
4
|
+
* This service runs on your backend infrastructure and provides AI-powered
|
|
5
|
+
* code analysis without requiring users to provide their own API keys.
|
|
6
|
+
*
|
|
7
|
+
* The service can be deployed as:
|
|
8
|
+
* - AWS Lambda function
|
|
9
|
+
* - Docker container
|
|
10
|
+
* - Express.js server
|
|
11
|
+
* - Cloud function
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { AICodeAnalysis } from '../ai/ai-install-wizard';
|
|
15
|
+
|
|
16
|
+
export interface FrameworkInfo {
|
|
17
|
+
name: string;
|
|
18
|
+
type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'node';
|
|
19
|
+
bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';
|
|
20
|
+
packageManager?: 'npm' | 'yarn' | 'pnpm';
|
|
21
|
+
hasTypeScript?: boolean;
|
|
22
|
+
hasRouter?: boolean;
|
|
23
|
+
projectRoot?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface CentralizedAIServiceConfig {
|
|
27
|
+
openaiApiKey: string;
|
|
28
|
+
openaiModel?: string;
|
|
29
|
+
maxTokens?: number;
|
|
30
|
+
temperature?: number;
|
|
31
|
+
enableCaching?: boolean;
|
|
32
|
+
cacheTTL?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface AIAnalysisRequest {
|
|
36
|
+
codeSamples: string[];
|
|
37
|
+
projectType?: string;
|
|
38
|
+
userAgent?: string;
|
|
39
|
+
timestamp: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface AIAnalysisResponse {
|
|
43
|
+
analysis: AICodeAnalysis;
|
|
44
|
+
processingTime: number;
|
|
45
|
+
cacheHit?: boolean;
|
|
46
|
+
modelUsed: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ConflictResolutionRequest {
|
|
50
|
+
conflicts: string[];
|
|
51
|
+
framework: FrameworkInfo;
|
|
52
|
+
codeContext?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface OptimizationRequest {
|
|
56
|
+
framework: FrameworkInfo;
|
|
57
|
+
patterns: string[];
|
|
58
|
+
projectContext?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Centralized AI Service Implementation
|
|
63
|
+
* This runs on your backend infrastructure
|
|
64
|
+
*/
|
|
65
|
+
export class CentralizedAIService {
|
|
66
|
+
private config: CentralizedAIServiceConfig;
|
|
67
|
+
private cache: Map<string, any> = new Map();
|
|
68
|
+
private openai: any; // OpenAI client
|
|
69
|
+
|
|
70
|
+
constructor(config: CentralizedAIServiceConfig) {
|
|
71
|
+
this.config = {
|
|
72
|
+
openaiModel: 'gpt-4',
|
|
73
|
+
maxTokens: 2000,
|
|
74
|
+
temperature: 0.3,
|
|
75
|
+
enableCaching: true,
|
|
76
|
+
cacheTTL: 3600, // 1 hour
|
|
77
|
+
...config
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
this.initializeOpenAI();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Initialize OpenAI client
|
|
85
|
+
*/
|
|
86
|
+
private initializeOpenAI() {
|
|
87
|
+
try {
|
|
88
|
+
// Import OpenAI dynamically to avoid bundling issues
|
|
89
|
+
const { OpenAI } = require('openai');
|
|
90
|
+
this.openai = new OpenAI({
|
|
91
|
+
apiKey: this.config.openaiApiKey
|
|
92
|
+
});
|
|
93
|
+
} catch (error) {
|
|
94
|
+
console.warn('OpenAI not available, falling back to heuristic analysis');
|
|
95
|
+
this.openai = null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Analyze code patterns using AI
|
|
101
|
+
*/
|
|
102
|
+
async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {
|
|
103
|
+
const request: AIAnalysisRequest = {
|
|
104
|
+
codeSamples,
|
|
105
|
+
timestamp: new Date().toISOString()
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// Check cache first
|
|
109
|
+
const cacheKey = this.generateCacheKey(request);
|
|
110
|
+
if (this.config.enableCaching) {
|
|
111
|
+
const cached = this.cache.get(cacheKey);
|
|
112
|
+
if (cached && this.isCacheValid(cached.timestamp)) {
|
|
113
|
+
return cached.analysis;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Perform AI analysis
|
|
118
|
+
const startTime = Date.now();
|
|
119
|
+
const analysis = await this.performAIAnalysis(request);
|
|
120
|
+
const processingTime = Date.now() - startTime;
|
|
121
|
+
|
|
122
|
+
// Cache the result
|
|
123
|
+
if (this.config.enableCaching) {
|
|
124
|
+
this.cache.set(cacheKey, {
|
|
125
|
+
analysis,
|
|
126
|
+
timestamp: Date.now()
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return analysis;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Resolve conflicts using AI
|
|
135
|
+
*/
|
|
136
|
+
async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {
|
|
137
|
+
const request: ConflictResolutionRequest = {
|
|
138
|
+
conflicts,
|
|
139
|
+
framework,
|
|
140
|
+
codeContext: 'HumanBehavior SDK integration'
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
if (!this.openai) {
|
|
144
|
+
return this.resolveConflictsHeuristic(conflicts, framework);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
const prompt = this.buildConflictResolutionPrompt(request);
|
|
149
|
+
const response = await this.openai.chat.completions.create({
|
|
150
|
+
model: this.config.openaiModel,
|
|
151
|
+
messages: [
|
|
152
|
+
{
|
|
153
|
+
role: 'system',
|
|
154
|
+
content: 'You are an expert at resolving code integration conflicts. Provide specific resolution strategies.'
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
role: 'user',
|
|
158
|
+
content: prompt
|
|
159
|
+
}
|
|
160
|
+
],
|
|
161
|
+
max_tokens: this.config.maxTokens,
|
|
162
|
+
temperature: this.config.temperature
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const content = response.choices[0]?.message?.content;
|
|
166
|
+
if (content && typeof content === 'string') {
|
|
167
|
+
return this.parseConflictResolutions(content);
|
|
168
|
+
}
|
|
169
|
+
return [];
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.warn('AI conflict resolution failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return this.resolveConflictsHeuristic(conflicts, framework);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Generate optimizations using AI
|
|
179
|
+
*/
|
|
180
|
+
async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {
|
|
181
|
+
const request: OptimizationRequest = {
|
|
182
|
+
framework,
|
|
183
|
+
patterns,
|
|
184
|
+
projectContext: 'HumanBehavior SDK integration'
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
if (!this.openai) {
|
|
188
|
+
return this.generateOptimizationsHeuristic(framework, patterns);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
const prompt = this.buildOptimizationPrompt(request);
|
|
193
|
+
const response = await this.openai.chat.completions.create({
|
|
194
|
+
model: this.config.openaiModel,
|
|
195
|
+
messages: [
|
|
196
|
+
{
|
|
197
|
+
role: 'system',
|
|
198
|
+
content: 'You are an expert at optimizing code integration. Provide specific, actionable recommendations.'
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
role: 'user',
|
|
202
|
+
content: prompt
|
|
203
|
+
}
|
|
204
|
+
],
|
|
205
|
+
max_tokens: this.config.maxTokens,
|
|
206
|
+
temperature: this.config.temperature
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
const content = response.choices[0]?.message?.content;
|
|
210
|
+
if (content) {
|
|
211
|
+
return this.parseOptimizations(content);
|
|
212
|
+
}
|
|
213
|
+
} catch (error) {
|
|
214
|
+
console.warn('AI optimization generation failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return this.generateOptimizationsHeuristic(framework, patterns);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Perform AI analysis
|
|
222
|
+
*/
|
|
223
|
+
private async performAIAnalysis(request: AIAnalysisRequest): Promise<AICodeAnalysis> {
|
|
224
|
+
if (!this.openai) {
|
|
225
|
+
return this.performHeuristicAnalysis(request);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
const prompt = this.buildAnalysisPrompt(request);
|
|
230
|
+
const response = await this.openai.chat.completions.create({
|
|
231
|
+
model: this.config.openaiModel,
|
|
232
|
+
messages: [
|
|
233
|
+
{
|
|
234
|
+
role: 'system',
|
|
235
|
+
content: 'You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format.'
|
|
236
|
+
},
|
|
237
|
+
{
|
|
238
|
+
role: 'user',
|
|
239
|
+
content: prompt
|
|
240
|
+
}
|
|
241
|
+
],
|
|
242
|
+
max_tokens: this.config.maxTokens,
|
|
243
|
+
temperature: this.config.temperature,
|
|
244
|
+
response_format: { type: 'json_object' }
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
const content = response.choices[0]?.message?.content;
|
|
248
|
+
if (content) {
|
|
249
|
+
return this.parseAnalysisResult(content);
|
|
250
|
+
}
|
|
251
|
+
} catch (error) {
|
|
252
|
+
console.warn('AI analysis failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return this.performHeuristicAnalysis(request);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Build analysis prompt
|
|
260
|
+
*/
|
|
261
|
+
private buildAnalysisPrompt(request: AIAnalysisRequest): string {
|
|
262
|
+
return `Analyze these code samples to determine the framework and integration strategy:
|
|
263
|
+
|
|
264
|
+
${request.codeSamples.join('\n\n')}
|
|
265
|
+
|
|
266
|
+
Provide analysis in JSON format with:
|
|
267
|
+
- framework: { name, type, confidence (0-1) }
|
|
268
|
+
- patterns: array of detected patterns
|
|
269
|
+
- conflicts: array of potential conflicts
|
|
270
|
+
- recommendations: array of integration recommendations
|
|
271
|
+
- integrationStrategy: "provider" | "plugin" | "module" | "script" | "standalone"
|
|
272
|
+
- compatibilityMode: "modern" | "legacy" | "hybrid"
|
|
273
|
+
|
|
274
|
+
Focus on:
|
|
275
|
+
1. Framework detection beyond package.json
|
|
276
|
+
2. Code patterns and architecture
|
|
277
|
+
3. Integration compatibility
|
|
278
|
+
4. Future-proof strategies
|
|
279
|
+
5. Backward compatibility needs
|
|
280
|
+
|
|
281
|
+
Respond with valid JSON only.`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Build conflict resolution prompt
|
|
286
|
+
*/
|
|
287
|
+
private buildConflictResolutionPrompt(request: ConflictResolutionRequest): string {
|
|
288
|
+
return `Resolve these integration conflicts for ${request.framework.name}:
|
|
289
|
+
|
|
290
|
+
Conflicts: ${request.conflicts.join(', ')}
|
|
291
|
+
|
|
292
|
+
Framework: ${request.framework.name} (${request.framework.type})
|
|
293
|
+
Context: ${request.codeContext}
|
|
294
|
+
|
|
295
|
+
Provide specific resolution strategies for each conflict. Options:
|
|
296
|
+
- update_existing_integration: Update existing code
|
|
297
|
+
- merge_providers: Merge multiple providers
|
|
298
|
+
- hybrid_module_support: Support both module systems
|
|
299
|
+
- skip_conflict: Skip the modification
|
|
300
|
+
- custom_resolution: Custom resolution strategy
|
|
301
|
+
|
|
302
|
+
Respond with a JSON array of resolution strategies.`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Build optimization prompt
|
|
307
|
+
*/
|
|
308
|
+
private buildOptimizationPrompt(request: OptimizationRequest): string {
|
|
309
|
+
return `Generate optimizations for ${request.framework.name} integration:
|
|
310
|
+
|
|
311
|
+
Framework: ${request.framework.name} (${request.framework.type})
|
|
312
|
+
Patterns: ${request.patterns.join(', ')}
|
|
313
|
+
Context: ${request.projectContext}
|
|
314
|
+
|
|
315
|
+
Provide specific, actionable optimization recommendations for:
|
|
316
|
+
1. Performance improvements
|
|
317
|
+
2. Error handling
|
|
318
|
+
3. Code organization
|
|
319
|
+
4. Future-proofing
|
|
320
|
+
5. Backward compatibility
|
|
321
|
+
|
|
322
|
+
Respond with a JSON array of optimization recommendations.`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Parse analysis result
|
|
327
|
+
*/
|
|
328
|
+
private parseAnalysisResult(content: string): AICodeAnalysis {
|
|
329
|
+
try {
|
|
330
|
+
const result = JSON.parse(content);
|
|
331
|
+
return {
|
|
332
|
+
framework: result.framework || { name: 'vanilla', type: 'vanilla' },
|
|
333
|
+
confidence: result.confidence || 0.5,
|
|
334
|
+
patterns: result.patterns || [],
|
|
335
|
+
conflicts: result.conflicts || [],
|
|
336
|
+
recommendations: result.recommendations || [],
|
|
337
|
+
integrationStrategy: result.integrationStrategy || 'script',
|
|
338
|
+
compatibilityMode: result.compatibilityMode || 'modern'
|
|
339
|
+
};
|
|
340
|
+
} catch (error) {
|
|
341
|
+
console.warn('Failed to parse AI analysis result:', error);
|
|
342
|
+
return this.getDefaultAnalysis();
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Parse conflict resolutions
|
|
348
|
+
*/
|
|
349
|
+
private parseConflictResolutions(content: string): string[] {
|
|
350
|
+
try {
|
|
351
|
+
const result = JSON.parse(content);
|
|
352
|
+
return Array.isArray(result) ? result : [];
|
|
353
|
+
} catch (error) {
|
|
354
|
+
console.warn('Failed to parse conflict resolutions:', error);
|
|
355
|
+
return [];
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Parse optimizations
|
|
361
|
+
*/
|
|
362
|
+
private parseOptimizations(content: string): string[] {
|
|
363
|
+
try {
|
|
364
|
+
const result = JSON.parse(content);
|
|
365
|
+
return Array.isArray(result) ? result : [];
|
|
366
|
+
} catch (error) {
|
|
367
|
+
console.warn('Failed to parse optimizations:', error);
|
|
368
|
+
return [];
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Heuristic analysis fallback
|
|
374
|
+
*/
|
|
375
|
+
private performHeuristicAnalysis(request: AIAnalysisRequest): AICodeAnalysis {
|
|
376
|
+
const patterns = request.codeSamples.join(' ').toLowerCase();
|
|
377
|
+
|
|
378
|
+
// Framework detection
|
|
379
|
+
let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };
|
|
380
|
+
let confidence = 0.5;
|
|
381
|
+
|
|
382
|
+
if (patterns.includes('react')) {
|
|
383
|
+
framework = { name: 'react', type: 'react' };
|
|
384
|
+
confidence = 0.9;
|
|
385
|
+
} else if (patterns.includes('vue')) {
|
|
386
|
+
framework = { name: 'vue', type: 'vue' };
|
|
387
|
+
confidence = 0.9;
|
|
388
|
+
} else if (patterns.includes('angular')) {
|
|
389
|
+
framework = { name: 'angular', type: 'angular' };
|
|
390
|
+
confidence = 0.9;
|
|
391
|
+
} else if (patterns.includes('svelte')) {
|
|
392
|
+
framework = { name: 'svelte', type: 'svelte' };
|
|
393
|
+
confidence = 0.9;
|
|
394
|
+
} else if (patterns.includes('next')) {
|
|
395
|
+
framework = { name: 'nextjs', type: 'nextjs' };
|
|
396
|
+
confidence = 0.9;
|
|
397
|
+
} else if (patterns.includes('nuxt')) {
|
|
398
|
+
framework = { name: 'nuxt', type: 'nuxt' };
|
|
399
|
+
confidence = 0.9;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Integration strategy
|
|
403
|
+
let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';
|
|
404
|
+
if (framework.type === 'react' || framework.type === 'nextjs') {
|
|
405
|
+
integrationStrategy = 'provider';
|
|
406
|
+
} else if (framework.type === 'vue') {
|
|
407
|
+
integrationStrategy = 'plugin';
|
|
408
|
+
} else if (framework.type === 'angular') {
|
|
409
|
+
integrationStrategy = 'module';
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Compatibility mode
|
|
413
|
+
let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';
|
|
414
|
+
if (patterns.includes('require(') || patterns.includes('var ')) {
|
|
415
|
+
compatibilityMode = 'legacy';
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
return {
|
|
419
|
+
framework,
|
|
420
|
+
confidence,
|
|
421
|
+
patterns: request.codeSamples,
|
|
422
|
+
conflicts: [],
|
|
423
|
+
recommendations: [],
|
|
424
|
+
integrationStrategy,
|
|
425
|
+
compatibilityMode
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Heuristic conflict resolution
|
|
431
|
+
*/
|
|
432
|
+
private resolveConflictsHeuristic(conflicts: string[], framework: FrameworkInfo): string[] {
|
|
433
|
+
const resolutions: string[] = [];
|
|
434
|
+
|
|
435
|
+
for (const conflict of conflicts) {
|
|
436
|
+
switch (conflict) {
|
|
437
|
+
case 'existing_humanbehavior_code':
|
|
438
|
+
resolutions.push('update_existing_integration');
|
|
439
|
+
break;
|
|
440
|
+
case 'existing_provider':
|
|
441
|
+
resolutions.push('merge_providers');
|
|
442
|
+
break;
|
|
443
|
+
case 'module_system_conflict':
|
|
444
|
+
resolutions.push('hybrid_module_support');
|
|
445
|
+
break;
|
|
446
|
+
default:
|
|
447
|
+
resolutions.push('skip_conflict');
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
return resolutions;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Heuristic optimization generation
|
|
456
|
+
*/
|
|
457
|
+
private generateOptimizationsHeuristic(framework: FrameworkInfo, patterns: string[]): string[] {
|
|
458
|
+
const optimizations: string[] = [];
|
|
459
|
+
|
|
460
|
+
switch (framework.type) {
|
|
461
|
+
case 'react':
|
|
462
|
+
optimizations.push('Use React.memo for performance optimization');
|
|
463
|
+
optimizations.push('Implement error boundaries for better error tracking');
|
|
464
|
+
optimizations.push('Consider using React.lazy for code splitting');
|
|
465
|
+
break;
|
|
466
|
+
case 'vue':
|
|
467
|
+
optimizations.push('Use Vue 3 Composition API for better performance');
|
|
468
|
+
optimizations.push('Implement proper error handling in components');
|
|
469
|
+
optimizations.push('Consider using Vue Router for navigation tracking');
|
|
470
|
+
break;
|
|
471
|
+
case 'angular':
|
|
472
|
+
optimizations.push('Use Angular standalone components for better tree-shaking');
|
|
473
|
+
optimizations.push('Implement proper error handling with ErrorHandler');
|
|
474
|
+
optimizations.push('Consider using Angular signals for state management');
|
|
475
|
+
break;
|
|
476
|
+
default:
|
|
477
|
+
optimizations.push('Enable performance tracking');
|
|
478
|
+
optimizations.push('Implement error tracking');
|
|
479
|
+
optimizations.push('Consider progressive enhancement');
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return optimizations;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Generate cache key
|
|
487
|
+
*/
|
|
488
|
+
private generateCacheKey(request: AIAnalysisRequest): string {
|
|
489
|
+
const content = JSON.stringify(request);
|
|
490
|
+
return Buffer.from(content).toString('base64').substring(0, 32);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Check if cache is valid
|
|
495
|
+
*/
|
|
496
|
+
private isCacheValid(timestamp: number): boolean {
|
|
497
|
+
const now = Date.now();
|
|
498
|
+
const ttl = (this.config.cacheTTL || 3600) * 1000; // Convert to milliseconds
|
|
499
|
+
return (now - timestamp) < ttl;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Get default analysis
|
|
504
|
+
*/
|
|
505
|
+
private getDefaultAnalysis(): AICodeAnalysis {
|
|
506
|
+
return {
|
|
507
|
+
framework: { name: 'vanilla', type: 'vanilla' },
|
|
508
|
+
confidence: 0.5,
|
|
509
|
+
patterns: [],
|
|
510
|
+
conflicts: [],
|
|
511
|
+
recommendations: [],
|
|
512
|
+
integrationStrategy: 'script',
|
|
513
|
+
compatibilityMode: 'modern'
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Get service statistics
|
|
519
|
+
*/
|
|
520
|
+
getStats() {
|
|
521
|
+
return {
|
|
522
|
+
cacheSize: this.cache.size,
|
|
523
|
+
config: {
|
|
524
|
+
model: this.config.openaiModel,
|
|
525
|
+
maxTokens: this.config.maxTokens,
|
|
526
|
+
temperature: this.config.temperature,
|
|
527
|
+
caching: this.config.enableCaching
|
|
528
|
+
},
|
|
529
|
+
openaiAvailable: !!this.openai
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Clear cache
|
|
535
|
+
*/
|
|
536
|
+
clearCache() {
|
|
537
|
+
this.cache.clear();
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Express.js server implementation
|
|
543
|
+
*/
|
|
544
|
+
export function createAIServiceServer(config: CentralizedAIServiceConfig) {
|
|
545
|
+
const express = require('express');
|
|
546
|
+
const app = express();
|
|
547
|
+
const aiService = new CentralizedAIService(config);
|
|
548
|
+
|
|
549
|
+
app.use(express.json());
|
|
550
|
+
|
|
551
|
+
// Health check endpoint
|
|
552
|
+
app.get('/health', (req: any, res: any) => {
|
|
553
|
+
res.json({ status: 'healthy', stats: aiService.getStats() });
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
// Analysis endpoint
|
|
557
|
+
app.post('/analyze', async (req: any, res: any) => {
|
|
558
|
+
try {
|
|
559
|
+
const { codeSamples, projectType, userAgent } = req.body;
|
|
560
|
+
|
|
561
|
+
if (!codeSamples || !Array.isArray(codeSamples)) {
|
|
562
|
+
return res.status(400).json({ error: 'codeSamples array is required' });
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const startTime = Date.now();
|
|
566
|
+
const analysis = await aiService.analyzeCodePatterns(codeSamples);
|
|
567
|
+
const processingTime = Date.now() - startTime;
|
|
568
|
+
|
|
569
|
+
res.json({
|
|
570
|
+
analysis,
|
|
571
|
+
processingTime,
|
|
572
|
+
modelUsed: config.openaiModel || 'heuristic'
|
|
573
|
+
});
|
|
574
|
+
} catch (error) {
|
|
575
|
+
res.status(500).json({ error: 'Analysis failed', details: error instanceof Error ? error.message : 'Unknown error' });
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
// Conflict resolution endpoint
|
|
580
|
+
app.post('/resolve-conflicts', async (req: any, res: any) => {
|
|
581
|
+
try {
|
|
582
|
+
const { conflicts, framework } = req.body;
|
|
583
|
+
|
|
584
|
+
if (!conflicts || !framework) {
|
|
585
|
+
return res.status(400).json({ error: 'conflicts and framework are required' });
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const resolutions = await aiService.resolveConflicts(conflicts, framework);
|
|
589
|
+
res.json({ resolutions });
|
|
590
|
+
} catch (error) {
|
|
591
|
+
res.status(500).json({ error: 'Conflict resolution failed', details: error instanceof Error ? error.message : 'Unknown error' });
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
// Optimization endpoint
|
|
596
|
+
app.post('/optimize', async (req: any, res: any) => {
|
|
597
|
+
try {
|
|
598
|
+
const { framework, patterns } = req.body;
|
|
599
|
+
|
|
600
|
+
if (!framework || !patterns) {
|
|
601
|
+
return res.status(400).json({ error: 'framework and patterns are required' });
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
const optimizations = await aiService.generateOptimizations(framework, patterns);
|
|
605
|
+
res.json({ optimizations });
|
|
606
|
+
} catch (error) {
|
|
607
|
+
res.status(500).json({ error: 'Optimization failed', details: error instanceof Error ? error.message : 'Unknown error' });
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
return app;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* AWS Lambda handler
|
|
616
|
+
*/
|
|
617
|
+
export async function lambdaHandler(event: any, context: any) {
|
|
618
|
+
const config: CentralizedAIServiceConfig = {
|
|
619
|
+
openaiApiKey: process.env.OPENAI_API_KEY!,
|
|
620
|
+
openaiModel: process.env.OPENAI_MODEL || 'gpt-4',
|
|
621
|
+
maxTokens: parseInt(process.env.MAX_TOKENS || '2000'),
|
|
622
|
+
temperature: parseFloat(process.env.TEMPERATURE || '0.3'),
|
|
623
|
+
enableCaching: process.env.ENABLE_CACHING !== 'false',
|
|
624
|
+
cacheTTL: parseInt(process.env.CACHE_TTL || '3600')
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
const aiService = new CentralizedAIService(config);
|
|
628
|
+
|
|
629
|
+
try {
|
|
630
|
+
const { path, httpMethod, body } = event;
|
|
631
|
+
const parsedBody = body ? JSON.parse(body) : {};
|
|
632
|
+
|
|
633
|
+
switch (path) {
|
|
634
|
+
case '/analyze':
|
|
635
|
+
if (httpMethod !== 'POST') {
|
|
636
|
+
return { statusCode: 405, body: JSON.stringify({ error: 'Method not allowed' }) };
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const analysis = await aiService.analyzeCodePatterns(parsedBody.codeSamples || []);
|
|
640
|
+
return {
|
|
641
|
+
statusCode: 200,
|
|
642
|
+
body: JSON.stringify({ analysis })
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
case '/resolve-conflicts':
|
|
646
|
+
if (httpMethod !== 'POST') {
|
|
647
|
+
return { statusCode: 405, body: JSON.stringify({ error: 'Method not allowed' }) };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const resolutions = await aiService.resolveConflicts(
|
|
651
|
+
parsedBody.conflicts || [],
|
|
652
|
+
parsedBody.framework || { name: 'vanilla', type: 'vanilla' }
|
|
653
|
+
);
|
|
654
|
+
return {
|
|
655
|
+
statusCode: 200,
|
|
656
|
+
body: JSON.stringify({ resolutions })
|
|
657
|
+
};
|
|
658
|
+
|
|
659
|
+
default:
|
|
660
|
+
return { statusCode: 404, body: JSON.stringify({ error: 'Not found' }) };
|
|
661
|
+
}
|
|
662
|
+
} catch (error) {
|
|
663
|
+
return {
|
|
664
|
+
statusCode: 500,
|
|
665
|
+
body: JSON.stringify({ error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' })
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
}
|