humanbehavior-js 0.4.6 → 0.4.8

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.
Files changed (58) hide show
  1. package/dist/cjs/angular/index.cjs +52 -7
  2. package/dist/cjs/angular/index.cjs.map +1 -1
  3. package/dist/cjs/index.cjs +52 -7
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/install-wizard.cjs +4 -2
  6. package/dist/cjs/install-wizard.cjs.map +1 -1
  7. package/dist/cjs/react/index.cjs +52 -7
  8. package/dist/cjs/react/index.cjs.map +1 -1
  9. package/dist/cjs/remix/index.cjs +52 -7
  10. package/dist/cjs/remix/index.cjs.map +1 -1
  11. package/dist/cjs/svelte/index.cjs +52 -7
  12. package/dist/cjs/svelte/index.cjs.map +1 -1
  13. package/dist/cjs/vue/index.cjs +52 -7
  14. package/dist/cjs/vue/index.cjs.map +1 -1
  15. package/dist/cjs/wizard/index.cjs +3208 -0
  16. package/dist/cjs/wizard/index.cjs.map +1 -0
  17. package/dist/cli/ai-auto-install.js +2024 -0
  18. package/dist/cli/ai-auto-install.js.map +1 -0
  19. package/dist/cli/auto-install.js +4 -2
  20. package/dist/cli/auto-install.js.map +1 -1
  21. package/dist/esm/angular/index.js +52 -7
  22. package/dist/esm/angular/index.js.map +1 -1
  23. package/dist/esm/index.js +52 -7
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/install-wizard.js +4 -2
  26. package/dist/esm/install-wizard.js.map +1 -1
  27. package/dist/esm/react/index.js +52 -7
  28. package/dist/esm/react/index.js.map +1 -1
  29. package/dist/esm/remix/index.js +52 -7
  30. package/dist/esm/remix/index.js.map +1 -1
  31. package/dist/esm/svelte/index.js +52 -7
  32. package/dist/esm/svelte/index.js.map +1 -1
  33. package/dist/esm/vue/index.js +52 -7
  34. package/dist/esm/vue/index.js.map +1 -1
  35. package/dist/esm/wizard/index.js +3178 -0
  36. package/dist/esm/wizard/index.js.map +1 -0
  37. package/dist/index.min.js +1 -1
  38. package/dist/index.min.js.map +1 -1
  39. package/dist/types/angular/index.d.ts +7 -0
  40. package/dist/types/index.d.ts +7 -0
  41. package/dist/types/install-wizard.d.ts +8 -8
  42. package/dist/types/react/index.d.ts +7 -0
  43. package/dist/types/remix/index.d.ts +7 -0
  44. package/dist/types/svelte/index.d.ts +7 -0
  45. package/dist/types/wizard/index.d.ts +489 -0
  46. package/package.json +14 -8
  47. package/rollup.config.js +65 -3
  48. package/src/react/AutoInstallWizard.tsx +1 -1
  49. package/src/tracker.ts +59 -8
  50. package/src/wizard/README.md +114 -0
  51. package/src/wizard/ai/ai-install-wizard.ts +894 -0
  52. package/src/wizard/ai/manual-framework-wizard.ts +236 -0
  53. package/src/wizard/cli/ai-auto-install.ts +369 -0
  54. package/src/{cli → wizard/cli}/auto-install.ts +1 -1
  55. package/src/{install-wizard.ts → wizard/core/install-wizard.ts} +12 -10
  56. package/src/wizard/index.ts +23 -0
  57. package/src/wizard/services/centralized-ai-service.ts +668 -0
  58. package/src/wizard/services/remote-ai-service.ts +224 -0
@@ -0,0 +1,894 @@
1
+ /**
2
+ * AI-Enhanced HumanBehavior SDK Auto-Installation Wizard
3
+ *
4
+ * This wizard uses AI to intelligently detect frameworks, analyze code patterns,
5
+ * and generate optimal integration code that's both future-proof and backward-compatible.
6
+ *
7
+ * 🚀 KEY FEATURES:
8
+ * - AI-powered framework detection beyond package.json
9
+ * - Intelligent code pattern analysis
10
+ * - Future-proof integration strategies
11
+ * - Backward compatibility with legacy frameworks
12
+ * - Adaptive code generation for new frameworks
13
+ * - Smart conflict resolution
14
+ * - Learning from user feedback
15
+ * - Centralized AI service (no user API keys required)
16
+ */
17
+
18
+ import * as fs from 'fs';
19
+ import * as path from 'path';
20
+ import { AutoInstallationWizard, FrameworkInfo, CodeModification, InstallationResult } from '../core/install-wizard';
21
+
22
+ export interface AICodeAnalysis {
23
+ framework: FrameworkInfo;
24
+ confidence: number;
25
+ patterns: string[];
26
+ conflicts: string[];
27
+ recommendations: string[];
28
+ integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone';
29
+ compatibilityMode: 'modern' | 'legacy' | 'hybrid';
30
+ }
31
+
32
+ export interface AIInstallationResult extends InstallationResult {
33
+ aiAnalysis: AICodeAnalysis;
34
+ learningData: {
35
+ patterns: string[];
36
+ framework: string;
37
+ success: boolean;
38
+ userFeedback?: string;
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Centralized AI Service Interface
44
+ * This runs on your backend infrastructure, not in the user's environment
45
+ */
46
+ interface CentralizedAIService {
47
+ analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis>;
48
+ resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]>;
49
+ generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]>;
50
+ }
51
+
52
+ /**
53
+ * Default AI Service Implementation
54
+ * Uses heuristic analysis when centralized service is not available
55
+ */
56
+ class DefaultAIService implements CentralizedAIService {
57
+ async analyzeCodePatterns(codeSamples: string[]): Promise<AICodeAnalysis> {
58
+ return this.analyzeWithHeuristics(codeSamples);
59
+ }
60
+
61
+ async resolveConflicts(conflicts: string[], framework: FrameworkInfo): Promise<string[]> {
62
+ // Default conflict resolution strategies
63
+ const resolutions: string[] = [];
64
+
65
+ for (const conflict of conflicts) {
66
+ switch (conflict) {
67
+ case 'existing_humanbehavior_code':
68
+ resolutions.push('update_existing_integration');
69
+ break;
70
+ case 'existing_provider':
71
+ resolutions.push('merge_providers');
72
+ break;
73
+ case 'module_system_conflict':
74
+ resolutions.push('hybrid_module_support');
75
+ break;
76
+ default:
77
+ resolutions.push('skip_conflict');
78
+ }
79
+ }
80
+
81
+ return resolutions;
82
+ }
83
+
84
+ async generateOptimizations(framework: FrameworkInfo, patterns: string[]): Promise<string[]> {
85
+ const optimizations: string[] = [];
86
+
87
+ // Framework-specific optimizations
88
+ switch (framework.type) {
89
+ case 'react':
90
+ optimizations.push('Use React.memo for performance optimization');
91
+ optimizations.push('Implement error boundaries for better error tracking');
92
+ optimizations.push('Consider using React.lazy for code splitting');
93
+ break;
94
+ case 'vue':
95
+ optimizations.push('Use Vue 3 Composition API for better performance');
96
+ optimizations.push('Implement proper error handling in components');
97
+ optimizations.push('Consider using Vue Router for navigation tracking');
98
+ break;
99
+ case 'angular':
100
+ optimizations.push('Use Angular standalone components for better tree-shaking');
101
+ optimizations.push('Implement proper error handling with ErrorHandler');
102
+ optimizations.push('Consider using Angular signals for state management');
103
+ break;
104
+ default:
105
+ optimizations.push('Enable performance tracking');
106
+ optimizations.push('Implement error tracking');
107
+ optimizations.push('Consider progressive enhancement');
108
+ }
109
+
110
+ return optimizations;
111
+ }
112
+
113
+ private analyzeWithHeuristics(codeSamples: string[]): AICodeAnalysis {
114
+ const patterns = codeSamples.join(' ').toLowerCase();
115
+
116
+ // Framework detection
117
+ let framework: FrameworkInfo = { name: 'vanilla', type: 'vanilla' };
118
+ let confidence = 0.5;
119
+
120
+ if (patterns.includes('nuxt') || patterns.includes('nuxtjs') || patterns.includes('defineNuxtConfig') || patterns.includes('nuxt.config') || patterns.includes('@nuxt/') || patterns.includes('useNuxtApp') || patterns.includes('useRuntimeConfig') || patterns.includes('useSeoMeta') || patterns.includes('useHead') || patterns.includes('useLazyFetch') || patterns.includes('useFetch') || patterns.includes('useAsyncData') || patterns.includes('#app')) {
121
+ framework = { name: 'nuxt', type: 'nuxt' };
122
+ confidence = 0.95;
123
+ } else if (patterns.includes('next') || patterns.includes('nextjs') || patterns.includes('next/link') || patterns.includes('next/image') || patterns.includes('next/navigation') || patterns.includes('next/router') || patterns.includes('getserverSideProps') || patterns.includes('getstaticProps') || patterns.includes('getstaticPaths') || patterns.includes('app/layout') || patterns.includes('app/page') || patterns.includes('pages/')) {
124
+ framework = { name: 'nextjs', type: 'nextjs' };
125
+ confidence = 0.95;
126
+ } else if (patterns.includes('react')) {
127
+ framework = { name: 'react', type: 'react' };
128
+ confidence = 0.9;
129
+ } else if (patterns.includes('vue')) {
130
+ framework = { name: 'vue', type: 'vue' };
131
+ confidence = 0.9;
132
+ } else if (patterns.includes('angular')) {
133
+ framework = { name: 'angular', type: 'angular' };
134
+ confidence = 0.9;
135
+ } else if (patterns.includes('svelte')) {
136
+ framework = { name: 'svelte', type: 'svelte' };
137
+ confidence = 0.9;
138
+ }
139
+
140
+ // Integration strategy
141
+ let integrationStrategy: 'provider' | 'plugin' | 'module' | 'script' | 'standalone' = 'script';
142
+ if (framework.type === 'react' || framework.type === 'nextjs') {
143
+ integrationStrategy = 'provider';
144
+ } else if (framework.type === 'vue') {
145
+ integrationStrategy = 'plugin';
146
+ } else if (framework.type === 'angular') {
147
+ integrationStrategy = 'module';
148
+ }
149
+
150
+ // Compatibility mode
151
+ let compatibilityMode: 'modern' | 'legacy' | 'hybrid' = 'modern';
152
+ if (patterns.includes('require(') || patterns.includes('var ')) {
153
+ compatibilityMode = 'legacy';
154
+ }
155
+
156
+ return {
157
+ framework,
158
+ confidence,
159
+ patterns: codeSamples,
160
+ conflicts: [],
161
+ recommendations: [],
162
+ integrationStrategy,
163
+ compatibilityMode
164
+ };
165
+ }
166
+ }
167
+
168
+ export class AIEnhancedInstallationWizard extends AutoInstallationWizard {
169
+ private aiService: CentralizedAIService;
170
+ private learningCache: Map<string, any> = new Map();
171
+ private patternDatabase: Map<string, any[]> = new Map();
172
+
173
+ constructor(apiKey: string, projectRoot: string = process.cwd(), aiService?: CentralizedAIService) {
174
+ super(apiKey, projectRoot);
175
+ this.aiService = aiService || new DefaultAIService();
176
+ this.loadLearningData();
177
+ }
178
+
179
+ /**
180
+ * AI-enhanced installation with intelligent analysis
181
+ */
182
+ async install(): Promise<AIInstallationResult> {
183
+ try {
184
+ // Step 1: AI-powered framework detection
185
+ const aiAnalysis = await this.performAICodeAnalysis();
186
+
187
+ // Step 2: Smart framework detection with AI validation
188
+ this.framework = await this.detectFrameworkWithAI(aiAnalysis);
189
+
190
+ // Step 3: Generate AI-optimized modifications
191
+ const modifications = await this.generateAIOptimizedModifications(aiAnalysis);
192
+
193
+ // Step 4: Apply modifications with conflict resolution
194
+ await this.applyModificationsWithAI(modifications, aiAnalysis);
195
+
196
+ // Step 5: Generate intelligent next steps
197
+ const nextSteps = this.generateAINextSteps(aiAnalysis);
198
+
199
+ // Step 6: Learn from this installation
200
+ await this.learnFromInstallation(aiAnalysis, modifications);
201
+
202
+ return {
203
+ success: true,
204
+ framework: this.framework,
205
+ modifications,
206
+ errors: [],
207
+ nextSteps,
208
+ aiAnalysis,
209
+ learningData: {
210
+ patterns: aiAnalysis.patterns,
211
+ framework: this.framework.name,
212
+ success: true
213
+ }
214
+ };
215
+ } catch (error) {
216
+ return {
217
+ success: false,
218
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
219
+ modifications: [],
220
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
221
+ nextSteps: [],
222
+ aiAnalysis: {
223
+ framework: { name: 'unknown', type: 'vanilla' },
224
+ confidence: 0,
225
+ patterns: [],
226
+ conflicts: [],
227
+ recommendations: [],
228
+ integrationStrategy: 'script',
229
+ compatibilityMode: 'legacy'
230
+ },
231
+ learningData: {
232
+ patterns: [],
233
+ framework: 'unknown',
234
+ success: false
235
+ }
236
+ };
237
+ }
238
+ }
239
+
240
+ /**
241
+ * AI-powered code analysis using centralized service
242
+ */
243
+ public async performAICodeAnalysis(): Promise<AICodeAnalysis> {
244
+ const projectFiles = await this.scanProjectFiles();
245
+ const codeSamples = await this.extractCodeSamples(projectFiles);
246
+
247
+ // Use centralized AI service (no user API key required)
248
+ return await this.aiService.analyzeCodePatterns(codeSamples);
249
+ }
250
+
251
+ /**
252
+ * Scan project files for analysis
253
+ */
254
+ private async scanProjectFiles(): Promise<string[]> {
255
+ const files: string[] = [];
256
+ const scanDir = (dir: string, depth: number = 0) => {
257
+ if (depth > 3) return; // Limit depth
258
+
259
+ try {
260
+ const items = fs.readdirSync(dir);
261
+ for (const item of items) {
262
+ const fullPath = path.join(dir, item);
263
+ const stat = fs.statSync(fullPath);
264
+
265
+ if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
266
+ scanDir(fullPath, depth + 1);
267
+ } else if (stat.isFile() && this.isRelevantFile(item)) {
268
+ files.push(fullPath);
269
+ }
270
+ }
271
+ } catch (error) {
272
+ // Skip inaccessible directories
273
+ }
274
+ };
275
+
276
+ scanDir(this.projectRoot);
277
+ return files;
278
+ }
279
+
280
+ /**
281
+ * Check if file is relevant for analysis
282
+ */
283
+ private isRelevantFile(filename: string): boolean {
284
+ const relevantExtensions = [
285
+ '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',
286
+ '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'
287
+ ];
288
+
289
+ const relevantNames = [
290
+ 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',
291
+ 'next.config', 'nuxt.config', 'angular.json', 'svelte.config',
292
+ 'app/layout', 'app/page', 'pages/index', 'pages/_app', 'pages/_document'
293
+ ];
294
+
295
+ return relevantExtensions.some(ext => filename.endsWith(ext)) ||
296
+ relevantNames.some(name => filename.includes(name));
297
+ }
298
+
299
+ /**
300
+ * Extract code samples for AI analysis
301
+ */
302
+ private async extractCodeSamples(files: string[]): Promise<string[]> {
303
+ const samples: string[] = [];
304
+
305
+ for (const file of files.slice(0, 20)) { // Limit to 20 files
306
+ try {
307
+ const content = fs.readFileSync(file, 'utf8');
308
+ const relativePath = path.relative(this.projectRoot, file);
309
+
310
+ // Extract relevant code patterns
311
+ const patterns = this.extractCodePatterns(content);
312
+ if (patterns.length > 0) {
313
+ samples.push(`File: ${relativePath}\n${patterns.join('\n')}`);
314
+ }
315
+ } catch (error) {
316
+ // Skip unreadable files
317
+ }
318
+ }
319
+
320
+ return samples;
321
+ }
322
+
323
+ /**
324
+ * Extract relevant code patterns
325
+ */
326
+ private extractCodePatterns(content: string): string[] {
327
+ const patterns: string[] = [];
328
+
329
+ // Framework-specific patterns
330
+ const frameworkPatterns = {
331
+ react: [
332
+ /import\s+React\s+from\s+['"]react['"]/gi,
333
+ /from\s+['"]react['"]/gi,
334
+ /function\s+\w+\s*\(\s*\)\s*{/gi,
335
+ /const\s+\w+\s*=\s*\(\s*\)\s*=>\s*{/gi
336
+ ],
337
+ vue: [
338
+ /import\s+{\s*createApp\s*}\s+from\s+['"]vue['"]/gi,
339
+ /from\s+['"]vue['"]/gi,
340
+ /<template>/gi,
341
+ /<script\s+setup>/gi
342
+ ],
343
+ angular: [
344
+ /import\s+{\s*Component\s*}\s+from\s+['"]@angular\/core['"]/gi,
345
+ /@Component\s*\(\s*{/gi,
346
+ /from\s+['"]@angular/gi
347
+ ],
348
+ svelte: [
349
+ /<script>/gi,
350
+ /import\s+.*\s+from\s+['"]svelte/gi,
351
+ /from\s+['"]svelte/gi
352
+ ],
353
+ nextjs: [
354
+ /import\s+.*\s+from\s+['"]next/gi,
355
+ /from\s+['"]next/gi,
356
+ /export\s+default\s+function\s+Page/gi,
357
+ /export\s+default\s+function\s+Layout/gi,
358
+ /export\s+default\s+function\s+Loading/gi,
359
+ /export\s+default\s+function\s+Error/gi,
360
+ /export\s+default\s+function\s+Not-found/gi,
361
+ /useRouter\s+from\s+['"]next\/navigation['"]/gi,
362
+ /useRouter\s+from\s+['"]next\/router['"]/gi,
363
+ /Link\s+from\s+['"]next\/link['"]/gi,
364
+ /Image\s+from\s+['"]next\/image['"]/gi,
365
+ /getServerSideProps/gi,
366
+ /getStaticProps/gi,
367
+ /getStaticPaths/gi,
368
+ /next\.config/gi,
369
+ /app\/layout\.tsx/gi,
370
+ /app\/page\.tsx/gi,
371
+ /pages\/.*\.tsx/gi,
372
+ /pages\/.*\.jsx/gi,
373
+ /pages\/.*\.ts/gi,
374
+ /pages\/.*\.js/gi
375
+ ],
376
+ nuxt: [
377
+ /import\s+.*\s+from\s+['"]nuxt/gi,
378
+ /from\s+['"]nuxt/gi,
379
+ /export\s+default\s+defineNuxtConfig/gi,
380
+ /defineNuxtConfig/gi,
381
+ /nuxt\.config\.ts/gi,
382
+ /nuxt\.config\.js/gi,
383
+ /@nuxt\//gi,
384
+ /#app/gi,
385
+ /useNuxtApp/gi,
386
+ /useRuntimeConfig/gi,
387
+ /useSeoMeta/gi,
388
+ /useHead/gi,
389
+ /useLazyFetch/gi,
390
+ /useFetch/gi,
391
+ /useAsyncData/gi,
392
+ /<NuxtLayout/gi,
393
+ /<NuxtPage/gi,
394
+ /NuxtLayout/gi,
395
+ /NuxtPage/gi,
396
+ /pages\/.*\.vue/gi,
397
+ /layouts\/.*\.vue/gi,
398
+ /components\/.*\.vue/gi,
399
+ /composables\/.*\.ts/gi,
400
+ /middleware\/.*\.ts/gi,
401
+ /server\/.*\.ts/gi,
402
+ /plugins\/.*\.ts/gi,
403
+ /public\//gi,
404
+ /assets\//gi,
405
+ /content\//gi
406
+ ]
407
+ };
408
+
409
+ // Extract patterns for each framework
410
+ for (const [framework, regexes] of Object.entries(frameworkPatterns)) {
411
+ for (const regex of regexes) {
412
+ const matches = content.match(regex);
413
+ if (matches) {
414
+ // Add raw patterns for heuristic analysis
415
+ patterns.push(...matches.slice(0, 3));
416
+ // Also add formatted patterns for debugging
417
+ patterns.push(`${framework.toUpperCase()}: ${matches.slice(0, 3).join(', ')}`);
418
+ }
419
+ }
420
+ }
421
+
422
+ // Extract import patterns
423
+ const importMatches = content.match(/import\s+.*\s+from\s+['"][^'"]+['"]/gi);
424
+ if (importMatches) {
425
+ patterns.push(`IMPORTS: ${importMatches.slice(0, 5).join(', ')}`);
426
+ }
427
+
428
+ // Extract export patterns
429
+ const exportMatches = content.match(/export\s+.*/gi);
430
+ if (exportMatches) {
431
+ patterns.push(`EXPORTS: ${exportMatches.slice(0, 3).join(', ')}`);
432
+ }
433
+
434
+ return patterns;
435
+ }
436
+
437
+ /**
438
+ * AI-enhanced framework detection
439
+ */
440
+ private async detectFrameworkWithAI(aiAnalysis: AICodeAnalysis): Promise<FrameworkInfo> {
441
+ // Combine AI analysis with traditional detection
442
+ const traditionalFramework = await super.detectFramework();
443
+
444
+ // Use AI analysis if confidence is high, but preserve bundler info
445
+ if (aiAnalysis.confidence > 0.8) {
446
+ return {
447
+ ...aiAnalysis.framework,
448
+ bundler: traditionalFramework.bundler, // Preserve bundler detection
449
+ packageManager: traditionalFramework.packageManager, // Preserve package manager
450
+ hasTypeScript: traditionalFramework.hasTypeScript, // Preserve TypeScript detection
451
+ hasRouter: traditionalFramework.hasRouter, // Preserve router detection
452
+ projectRoot: this.projectRoot
453
+ };
454
+ }
455
+
456
+ // Merge AI insights with traditional detection
457
+ return {
458
+ ...traditionalFramework,
459
+ // Override with AI insights if available
460
+ ...(aiAnalysis.framework.type !== 'vanilla' && {
461
+ type: aiAnalysis.framework.type,
462
+ name: aiAnalysis.framework.name
463
+ })
464
+ };
465
+ }
466
+
467
+ /**
468
+ * Generate AI-optimized modifications
469
+ */
470
+ private async generateAIOptimizedModifications(aiAnalysis: AICodeAnalysis): Promise<CodeModification[]> {
471
+ const baseModifications = await super.generateModifications();
472
+
473
+ // Enhance with AI recommendations
474
+ const enhancedModifications = baseModifications.map(mod => {
475
+ return this.enhanceModificationWithAI(mod, aiAnalysis);
476
+ });
477
+
478
+ // Add AI-specific optimizations
479
+ const aiOptimizations = this.generateAIOptimizations(aiAnalysis);
480
+ enhancedModifications.push(...aiOptimizations);
481
+
482
+ return enhancedModifications;
483
+ }
484
+
485
+ /**
486
+ * Enhance modification with AI insights
487
+ */
488
+ private enhanceModificationWithAI(mod: CodeModification, aiAnalysis: AICodeAnalysis): CodeModification {
489
+ let enhancedContent = mod.content;
490
+
491
+ // Add compatibility comments
492
+ if (aiAnalysis.compatibilityMode === 'legacy') {
493
+ enhancedContent = `// HumanBehavior SDK - Legacy Compatibility Mode\n${enhancedContent}`;
494
+ }
495
+
496
+ // Add future-proofing comments
497
+ if (aiAnalysis.integrationStrategy === 'provider') {
498
+ enhancedContent = `// HumanBehavior SDK - Provider Pattern (Future-proof)\n${enhancedContent}`;
499
+ }
500
+
501
+ // Add conflict resolution
502
+ if (aiAnalysis.conflicts.length > 0) {
503
+ enhancedContent = `// Conflict Resolution: ${aiAnalysis.conflicts.join(', ')}\n${enhancedContent}`;
504
+ }
505
+
506
+ return {
507
+ ...mod,
508
+ content: enhancedContent,
509
+ description: `${mod.description} (AI-optimized)`
510
+ };
511
+ }
512
+
513
+ /**
514
+ * Generate AI-specific optimizations
515
+ */
516
+ private generateAIOptimizations(aiAnalysis: AICodeAnalysis): CodeModification[] {
517
+ const optimizations: CodeModification[] = [];
518
+
519
+ // AI optimizations are now handled through environment variables and code injection
520
+ // No separate config file needed - everything is integrated into the existing codebase
521
+
522
+ return optimizations;
523
+ }
524
+
525
+ /**
526
+ * Apply modifications with AI conflict resolution
527
+ */
528
+ private async applyModificationsWithAI(modifications: CodeModification[], aiAnalysis: AICodeAnalysis): Promise<void> {
529
+ for (const modification of modifications) {
530
+ try {
531
+ // Check for conflicts
532
+ const conflicts = await this.detectConflicts(modification);
533
+
534
+ if (conflicts.length > 0) {
535
+ // Resolve conflicts using centralized AI service
536
+ const resolutions = await this.aiService.resolveConflicts(conflicts, aiAnalysis.framework);
537
+ const resolvedModification = await this.resolveConflicts(modification, conflicts, resolutions, aiAnalysis);
538
+ await this.applyModification(resolvedModification);
539
+ } else {
540
+ await this.applyModification(modification);
541
+ }
542
+ } catch (error) {
543
+ throw new Error(`Failed to apply AI-optimized modification to ${modification.filePath}: ${error}`);
544
+ }
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Detect potential conflicts
550
+ */
551
+ private async detectConflicts(modification: CodeModification): Promise<string[]> {
552
+ const conflicts: string[] = [];
553
+
554
+ if (fs.existsSync(modification.filePath)) {
555
+ const existingContent = fs.readFileSync(modification.filePath, 'utf8');
556
+
557
+ // Check for existing HumanBehavior code
558
+ if (existingContent.includes('HumanBehavior') || existingContent.includes('humanbehavior')) {
559
+ conflicts.push('existing_humanbehavior_code');
560
+ }
561
+
562
+ // Check for conflicting providers/plugins
563
+ if (modification.content.includes('Provider') && existingContent.includes('Provider')) {
564
+ conflicts.push('existing_provider');
565
+ }
566
+
567
+ // Check for TypeScript conflicts
568
+ if (modification.content.includes('import') && existingContent.includes('require(')) {
569
+ conflicts.push('module_system_conflict');
570
+ }
571
+ }
572
+
573
+ return conflicts;
574
+ }
575
+
576
+ /**
577
+ * Resolve conflicts with AI
578
+ */
579
+ private async resolveConflicts(modification: CodeModification, conflicts: string[], resolutions: string[], aiAnalysis: AICodeAnalysis): Promise<CodeModification> {
580
+ let resolvedContent = modification.content;
581
+
582
+ for (let i = 0; i < conflicts.length; i++) {
583
+ const conflict = conflicts[i];
584
+ const resolution = resolutions[i];
585
+
586
+ switch (resolution) {
587
+ case 'update_existing_integration':
588
+ resolvedContent = `// Updated HumanBehavior Integration\n${resolvedContent}`;
589
+ break;
590
+ case 'merge_providers':
591
+ resolvedContent = resolvedContent.replace(/<HumanBehaviorProvider/g, '<HumanBehaviorProvider key="updated"');
592
+ break;
593
+ case 'hybrid_module_support':
594
+ resolvedContent = `// Hybrid module system support\n${resolvedContent}`;
595
+ break;
596
+ case 'skip_conflict':
597
+ // Skip this modification
598
+ return { ...modification, content: '', description: `${modification.description} (skipped due to conflict)` };
599
+ default:
600
+ // Default resolution
601
+ resolvedContent = `// Conflict resolved: ${conflict}\n${resolvedContent}`;
602
+ }
603
+ }
604
+
605
+ return {
606
+ ...modification,
607
+ content: resolvedContent,
608
+ description: `${modification.description} (conflict-resolved)`
609
+ };
610
+ }
611
+
612
+ /**
613
+ * Apply single modification
614
+ */
615
+ private async applyModification(modification: CodeModification): Promise<void> {
616
+ if (!modification.content) return; // Skip empty modifications
617
+
618
+ const dir = path.dirname(modification.filePath);
619
+ if (!fs.existsSync(dir)) {
620
+ fs.mkdirSync(dir, { recursive: true });
621
+ }
622
+
623
+ switch (modification.action) {
624
+ case 'create':
625
+ fs.writeFileSync(modification.filePath, modification.content);
626
+ break;
627
+ case 'modify':
628
+ fs.writeFileSync(modification.filePath, modification.content);
629
+ break;
630
+ case 'append':
631
+ fs.appendFileSync(modification.filePath, '\n' + modification.content);
632
+ break;
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Generate AI-enhanced next steps
638
+ */
639
+ private generateAINextSteps(aiAnalysis: AICodeAnalysis): string[] {
640
+ const steps = [
641
+ '✅ AI-optimized SDK installation completed!',
642
+ `🎯 Framework detected: ${aiAnalysis.framework.name} (confidence: ${Math.round(aiAnalysis.confidence * 100)}%)`,
643
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
644
+ `🔄 Compatibility mode: ${aiAnalysis.compatibilityMode}`,
645
+ '🚀 Your app is now tracking user behavior with AI-optimized configuration'
646
+ ];
647
+
648
+ if (aiAnalysis.recommendations.length > 0) {
649
+ steps.push('💡 AI Recommendations:');
650
+ aiAnalysis.recommendations.forEach(rec => steps.push(` • ${rec}`));
651
+ }
652
+
653
+ return steps;
654
+ }
655
+
656
+ /**
657
+ * Learn from installation for future improvements
658
+ */
659
+ private async learnFromInstallation(aiAnalysis: AICodeAnalysis, modifications: CodeModification[]): Promise<void> {
660
+ const learningData = {
661
+ timestamp: new Date().toISOString(),
662
+ framework: aiAnalysis.framework.name,
663
+ patterns: aiAnalysis.patterns,
664
+ integrationStrategy: aiAnalysis.integrationStrategy,
665
+ compatibilityMode: aiAnalysis.compatibilityMode,
666
+ modifications: modifications.length,
667
+ success: true
668
+ };
669
+
670
+ // Store learning data
671
+ this.learningCache.set(`${aiAnalysis.framework.name}_${Date.now()}`, learningData);
672
+
673
+ // Update pattern database
674
+ if (!this.patternDatabase.has(aiAnalysis.framework.name)) {
675
+ this.patternDatabase.set(aiAnalysis.framework.name, []);
676
+ }
677
+ this.patternDatabase.get(aiAnalysis.framework.name)!.push(learningData);
678
+
679
+ // Save to disk
680
+ await this.saveLearningData();
681
+ }
682
+
683
+ /**
684
+ * Load learning data from disk
685
+ */
686
+ private loadLearningData(): void {
687
+ // Don't load learning data from user's project - keep it in memory only
688
+ // This prevents cluttering the user's project with internal files
689
+ }
690
+
691
+ /**
692
+ * Save learning data to disk
693
+ */
694
+ private async saveLearningData(): Promise<void> {
695
+ // Don't save learning data to user's project - keep it in memory only
696
+ // This prevents cluttering the user's project with internal files
697
+ }
698
+
699
+ /**
700
+ * Get AI insights for a specific framework
701
+ */
702
+ public getAIInsights(frameworkName: string): any[] {
703
+ return this.patternDatabase.get(frameworkName) || [];
704
+ }
705
+
706
+ /**
707
+ * Get learning statistics
708
+ */
709
+ public getLearningStats(): any {
710
+ const stats = {
711
+ totalInstallations: this.learningCache.size,
712
+ frameworks: {} as any,
713
+ patterns: {} as any
714
+ };
715
+
716
+ for (const [framework, data] of this.patternDatabase.entries()) {
717
+ stats.frameworks[framework] = data.length;
718
+ }
719
+
720
+ return stats;
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Browser-based AI installation wizard
726
+ */
727
+ export class AIBrowserInstallationWizard {
728
+ private apiKey: string;
729
+ private aiService: CentralizedAIService;
730
+
731
+ constructor(apiKey: string, aiService?: CentralizedAIService) {
732
+ this.apiKey = apiKey;
733
+ this.aiService = aiService || new DefaultAIService();
734
+ }
735
+
736
+ async install(): Promise<AIInstallationResult> {
737
+ try {
738
+ // AI-powered browser detection
739
+ const aiAnalysis = await this.performBrowserAIAnalysis();
740
+
741
+ // Generate AI-optimized browser modifications
742
+ const modifications = this.generateAIBrowserModifications(aiAnalysis);
743
+
744
+ return {
745
+ success: true,
746
+ framework: aiAnalysis.framework,
747
+ modifications,
748
+ errors: [],
749
+ nextSteps: [
750
+ '✅ AI-optimized browser integration ready!',
751
+ `🎯 Framework detected: ${aiAnalysis.framework.name}`,
752
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
753
+ '📋 Copy the generated code to your project',
754
+ '🚀 Your app will be ready to track user behavior'
755
+ ],
756
+ aiAnalysis,
757
+ learningData: {
758
+ patterns: aiAnalysis.patterns,
759
+ framework: aiAnalysis.framework.name,
760
+ success: true
761
+ }
762
+ };
763
+ } catch (error) {
764
+ return {
765
+ success: false,
766
+ framework: { name: 'unknown', type: 'vanilla' },
767
+ modifications: [],
768
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
769
+ nextSteps: [],
770
+ aiAnalysis: {
771
+ framework: { name: 'unknown', type: 'vanilla' },
772
+ confidence: 0,
773
+ patterns: [],
774
+ conflicts: [],
775
+ recommendations: [],
776
+ integrationStrategy: 'script',
777
+ compatibilityMode: 'legacy'
778
+ },
779
+ learningData: {
780
+ patterns: [],
781
+ framework: 'unknown',
782
+ success: false
783
+ }
784
+ };
785
+ }
786
+ }
787
+
788
+ private async performBrowserAIAnalysis(): Promise<AICodeAnalysis> {
789
+ // Browser-based framework detection
790
+ const framework = this.detectBrowserFramework();
791
+
792
+ // Analyze browser environment
793
+ const patterns = this.analyzeBrowserPatterns();
794
+
795
+ // Use centralized AI service for analysis
796
+ const codeSamples = [`Browser Environment: ${patterns.join(', ')}`];
797
+ return await this.aiService.analyzeCodePatterns(codeSamples);
798
+ }
799
+
800
+ private detectBrowserFramework(): FrameworkInfo {
801
+ if (typeof window !== 'undefined') {
802
+ if ((window as any).React) {
803
+ return { name: 'react', type: 'react' };
804
+ }
805
+ if ((window as any).Vue) {
806
+ return { name: 'vue', type: 'vue' };
807
+ }
808
+ if ((window as any).angular) {
809
+ return { name: 'angular', type: 'angular' };
810
+ }
811
+ }
812
+
813
+ return { name: 'vanilla', type: 'vanilla' };
814
+ }
815
+
816
+ private analyzeBrowserPatterns(): string[] {
817
+ const patterns: string[] = [];
818
+
819
+ if (typeof window !== 'undefined') {
820
+ // Analyze global objects
821
+ if ((window as any).React) patterns.push('React global detected');
822
+ if ((window as any).Vue) patterns.push('Vue global detected');
823
+ if ((window as any).angular) patterns.push('Angular global detected');
824
+
825
+ // Analyze DOM patterns
826
+ if (document.querySelector('[data-reactroot]')) patterns.push('React DOM detected');
827
+ if (document.querySelector('[data-vue]')) patterns.push('Vue DOM detected');
828
+
829
+ // Analyze script patterns
830
+ const scripts = document.querySelectorAll('script');
831
+ scripts.forEach(script => {
832
+ if (script.src.includes('react')) patterns.push('React script detected');
833
+ if (script.src.includes('vue')) patterns.push('Vue script detected');
834
+ });
835
+ }
836
+
837
+ return patterns;
838
+ }
839
+
840
+ private generateAIBrowserModifications(aiAnalysis: AICodeAnalysis): CodeModification[] {
841
+ const modifications: CodeModification[] = [];
842
+
843
+ switch (aiAnalysis.framework.type) {
844
+ case 'react':
845
+ modifications.push({
846
+ filePath: 'App.jsx',
847
+ action: 'create',
848
+ content: `// AI-Optimized React Integration
849
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
850
+
851
+ function App() {
852
+ return (
853
+ <HumanBehaviorProvider
854
+ apiKey="${this.apiKey}"
855
+ config={{
856
+ // AI-generated optimizations
857
+ enablePerformanceTracking: true,
858
+ enableErrorTracking: true,
859
+ framework: '${aiAnalysis.framework.name}',
860
+ integrationStrategy: '${aiAnalysis.integrationStrategy}'
861
+ }}
862
+ >
863
+ {/* Your app components */}
864
+ </HumanBehaviorProvider>
865
+ );
866
+ }
867
+
868
+ export default App;`,
869
+ description: 'AI-optimized React component with HumanBehaviorProvider'
870
+ });
871
+ break;
872
+
873
+ default:
874
+ modifications.push({
875
+ filePath: 'humanbehavior-init.js',
876
+ action: 'create',
877
+ content: `// AI-Optimized Vanilla JS Integration
878
+ import { HumanBehaviorTracker } from 'humanbehavior-js';
879
+
880
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}', {
881
+ // AI-generated configuration
882
+ framework: '${aiAnalysis.framework.name}',
883
+ integrationStrategy: '${aiAnalysis.integrationStrategy}',
884
+ compatibilityMode: '${aiAnalysis.compatibilityMode}',
885
+ enablePerformanceTracking: true,
886
+ enableErrorTracking: true
887
+ });`,
888
+ description: 'AI-optimized vanilla JS initialization'
889
+ });
890
+ }
891
+
892
+ return modifications;
893
+ }
894
+ }