humanbehavior-js 0.4.13 → 0.4.14

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.
@@ -13,7 +13,7 @@ import { AIEnhancedInstallationWizard, AIBrowserInstallationWizard } from '../ai
13
13
  import { ManualFrameworkInstallationWizard } from '../ai/manual-framework-wizard';
14
14
  import { AutoInstallationWizard } from '../core/install-wizard';
15
15
  import { RemoteAIService } from '../services/remote-ai-service';
16
- import * as readline from 'readline';
16
+ import * as clack from '@clack/prompts';
17
17
  import * as fs from 'fs';
18
18
  import * as path from 'path';
19
19
 
@@ -22,81 +22,61 @@ interface AICLIOptions {
22
22
  projectPath?: string;
23
23
  yes?: boolean;
24
24
  dryRun?: boolean;
25
- useAI?: boolean;
26
- browser?: boolean;
27
25
  framework?: string;
28
- manual?: boolean;
29
26
  }
30
27
 
31
28
  class AIAutoInstallCLI {
32
- private rl: readline.Interface;
33
29
  private options: AICLIOptions;
34
30
 
35
31
  constructor(options: AICLIOptions) {
36
32
  this.options = options;
37
- this.rl = readline.createInterface({
38
- input: process.stdin,
39
- output: process.stdout
40
- });
41
33
  }
42
34
 
43
35
  async run() {
44
- console.log('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');
45
- console.log('================================================\n');
36
+ clack.intro('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');
46
37
 
47
38
  try {
48
39
  // Get API key
49
40
  const apiKey = await this.getApiKey();
50
41
  if (!apiKey) {
51
- console.error('API key is required');
42
+ clack.cancel('API key is required');
52
43
  process.exit(1);
53
44
  }
54
45
 
55
46
  // Get project path
56
47
  const projectPath = this.options.projectPath || process.cwd();
57
48
 
58
- // Choose installation mode
59
- const installationMode = await this.chooseInstallationMode();
49
+ // Choose framework
50
+ const framework = await this.chooseFramework();
51
+ if (!framework) {
52
+ clack.cancel('Installation cancelled.');
53
+ process.exit(0);
54
+ }
60
55
 
61
56
  // Confirm installation
62
57
  if (!this.options.yes) {
63
- const confirmed = await this.confirmInstallation(projectPath, installationMode);
58
+ const confirmed = await this.confirmInstallation(projectPath, framework);
64
59
  if (!confirmed) {
65
- console.log('Installation cancelled.');
60
+ clack.cancel('Installation cancelled.');
66
61
  process.exit(0);
67
62
  }
68
63
  }
69
64
 
70
65
  // Run installation
71
- console.log('🔍 Analyzing your project with AI...');
66
+ const spinner = clack.spinner();
67
+ spinner.start('🔍 Analyzing your project with AI...');
72
68
 
73
- let result;
74
- if (this.options.browser) {
75
- const wizard = new AIBrowserInstallationWizard(apiKey);
76
- result = await wizard.install();
77
- } else if (installationMode === 'manual') {
78
- // Manual AI-Enhanced framework selection
79
- const framework = await this.chooseFramework();
80
- const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
81
- result = await wizard.install();
82
- } else if (installationMode.startsWith('manual:')) {
83
- // Manual framework selection with pre-selected framework
84
- const framework = installationMode.split(':')[1];
85
- const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
86
- result = await wizard.install();
87
- } else {
88
- const wizard = new AutoInstallationWizard(apiKey, projectPath);
89
- result = await wizard.install();
90
- }
69
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
70
+ const result = await wizard.install();
71
+
72
+ spinner.stop('Analysis complete!');
91
73
 
92
74
  // Display results
93
- this.displayResults(result, installationMode);
75
+ this.displayResults(result, framework);
94
76
 
95
77
  } catch (error) {
96
- console.error('❌ Error:', error instanceof Error ? error.message : error);
78
+ clack.cancel(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
97
79
  process.exit(1);
98
- } finally {
99
- this.rl.close();
100
80
  }
101
81
  }
102
82
 
@@ -105,154 +85,89 @@ class AIAutoInstallCLI {
105
85
  return this.options.apiKey;
106
86
  }
107
87
 
108
- return new Promise((resolve) => {
109
- this.rl.question('Enter your HumanBehavior API key: ', (answer) => {
110
- resolve(answer.trim());
111
- });
88
+ const apiKey = await clack.text({
89
+ message: 'Enter your HumanBehavior API key:',
90
+ placeholder: 'hb_...',
91
+ validate: (value) => {
92
+ if (!value) return 'API key is required';
93
+ if (!value.startsWith('hb_')) return 'API key should start with "hb_"';
94
+ return undefined;
95
+ }
112
96
  });
97
+
98
+ return apiKey;
113
99
  }
114
100
 
115
- private async chooseInstallationMode(): Promise<string> {
116
- if (this.options.manual && this.options.framework) {
117
- return `manual:${this.options.framework}`;
118
- }
119
- if (this.options.useAI !== undefined) {
120
- return this.options.useAI ? 'ai' : 'traditional';
121
- }
122
101
 
123
- console.log('🤖 Choose installation mode:');
124
- console.log('1. Manual AI-Enhanced (recommended) - Choose your framework and use AI for optimization');
125
- console.log('2. Traditional - Standard framework detection and installation');
126
- console.log('3. Browser - Browser-based AI detection and code generation\n');
127
-
128
- return new Promise((resolve) => {
129
- this.rl.question('Select mode (1-3, default: 1): ', (answer) => {
130
- const choice = answer.trim() || '1';
131
- if (choice === '1') resolve('manual');
132
- else if (choice === '2') resolve('traditional');
133
- else if (choice === '3') resolve('browser');
134
- else resolve('manual');
135
- });
136
- });
137
- }
138
102
 
139
- private async confirmInstallation(projectPath: string, installationMode: string): Promise<boolean> {
140
- console.log(`📁 Project path: ${projectPath}`);
141
- console.log(`🤖 Installation mode: ${this.getInstallationModeDisplay(installationMode)}`);
142
- console.log('⚠️ This will modify your codebase to integrate HumanBehavior SDK.');
143
- console.log(' The following changes will be made:');
144
- console.log(' - Install humanbehavior-js package');
145
- console.log(' - Analyze code patterns with AI (if enabled)');
146
- console.log(' - Modify your main app file');
147
- console.log(' - Create environment files');
148
- console.log(' - Add AI-optimized SDK initialization code\n');
149
-
150
- return new Promise((resolve) => {
151
- this.rl.question('Continue with installation? (y/n): ', (answer) => {
152
- resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
153
- });
103
+
104
+
105
+ private async confirmInstallation(projectPath: string, framework: string): Promise<boolean> {
106
+ const confirmed = await clack.confirm({
107
+ message: `Ready to install HumanBehavior SDK in ${projectPath} for ${framework}?`
154
108
  });
155
- }
156
109
 
157
- private getInstallationModeDisplay(mode: string): string {
158
- if (mode === 'manual') return 'Manual AI-Enhanced';
159
- if (mode === 'traditional') return 'Traditional';
160
- if (mode.startsWith('manual:')) {
161
- const framework = mode.split(':')[1];
162
- return `Manual AI-Enhanced (${framework})`;
163
- }
164
- if (mode === 'browser') return 'Browser';
165
- return 'Unknown';
110
+ return confirmed;
166
111
  }
167
112
 
168
113
  private async chooseFramework(): Promise<string> {
169
- console.log('\n🎯 Choose your framework:');
170
- console.log('1. Vanilla JS (HTML)');
171
- console.log('2. React');
172
- console.log('3. Next.js');
173
- console.log('4. Vue');
174
- console.log('5. Nuxt');
175
- console.log('6. Angular');
176
- console.log('7. Svelte');
177
- console.log('8. Remix');
178
- console.log('9. Node.js');
179
- console.log('10. Other (Auto-detect)\n');
180
-
181
- return new Promise((resolve) => {
182
- this.rl.question('Select framework (1-10, default: 1): ', (answer) => {
183
- const choice = answer.trim() || '1';
184
- const frameworks = ['vanilla', 'react', 'nextjs', 'vue', 'nuxt', 'angular', 'svelte', 'remix', 'node', 'auto'];
185
- const index = parseInt(choice) - 1;
186
- resolve(frameworks[index] || 'vanilla');
187
- });
114
+ const framework = await clack.select({
115
+ message: 'Select your framework:',
116
+ options: [
117
+ { label: 'React', value: 'react' },
118
+ { label: 'Next.js', value: 'nextjs' },
119
+ { label: 'Vue', value: 'vue' },
120
+ { label: 'Angular', value: 'angular' },
121
+ { label: 'Svelte', value: 'svelte' },
122
+ { label: 'Nuxt.js', value: 'nuxt' },
123
+ { label: 'Remix', value: 'remix' },
124
+ { label: 'Astro', value: 'astro' },
125
+ { label: 'Gatsby', value: 'gatsby' },
126
+ { label: 'Vanilla JS/TS', value: 'vanilla' }
127
+ ]
188
128
  });
129
+
130
+ return framework;
189
131
  }
190
132
 
191
- private displayResults(result: any, installationMode: string) {
133
+ private displayResults(result: any, framework: string) {
192
134
  if (result.success) {
193
- console.log('\n✅ Installation completed successfully!');
194
-
195
- if (installationMode === 'ai' && result.aiAnalysis) {
196
- console.log(`🎯 AI Analysis Results:`);
197
- console.log(` Framework: ${result.aiAnalysis.framework.name} (confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%)`);
198
- console.log(` Integration Strategy: ${result.aiAnalysis.integrationStrategy}`);
199
- console.log(` Compatibility Mode: ${result.aiAnalysis.compatibilityMode}`);
200
-
201
- if (result.aiAnalysis.patterns.length > 0) {
202
- console.log(` Detected Patterns: ${result.aiAnalysis.patterns.length} patterns`);
203
- }
204
-
205
- if (result.aiAnalysis.recommendations.length > 0) {
206
- console.log(` AI Recommendations:`);
207
- result.aiAnalysis.recommendations.forEach((rec: string) => {
208
- console.log(` • ${rec}`);
209
- });
210
- }
211
- } else {
212
- console.log(`📦 Framework detected: ${result.framework.name}`);
213
- }
214
-
215
- if (result.framework.bundler) {
216
- console.log(`🔧 Bundler: ${result.framework.bundler}`);
135
+ clack.outro('🎉 Installation completed successfully!');
136
+
137
+ // Display framework info
138
+ clack.note(`Framework detected: ${result.framework.name} (${result.framework.type})`, 'Framework Info');
139
+
140
+ // Display modifications
141
+ if (result.modifications && result.modifications.length > 0) {
142
+ const modifications = result.modifications.map((mod: any) =>
143
+ `${mod.action}: ${mod.filePath} - ${mod.description}`
144
+ );
145
+ clack.note(modifications.join('\n'), 'Files Modified');
217
146
  }
218
-
219
- if (result.framework.packageManager) {
220
- console.log(`📋 Package Manager: ${result.framework.packageManager}`);
147
+
148
+ // Display next steps
149
+ if (result.nextSteps && result.nextSteps.length > 0) {
150
+ clack.note(result.nextSteps.join('\n'), 'Next Steps');
221
151
  }
222
152
 
223
- console.log('\n📝 Changes made:');
224
- result.modifications.forEach((mod: any) => {
225
- console.log(` ${mod.action === 'create' ? '➕' : '✏️'} ${mod.description}`);
226
- console.log(` ${mod.filePath}`);
227
- });
228
-
229
- console.log('\n🎯 Next steps:');
230
- result.nextSteps.forEach((step: string) => {
231
- console.log(` ${step}`);
232
- });
233
-
234
- if (installationMode === 'ai' && result.learningData) {
235
- console.log('\n🧠 Learning Data:');
236
- console.log(` Framework: ${result.learningData.framework}`);
237
- console.log(` Patterns: ${result.learningData.patterns.length} detected`);
238
- console.log(` Success: ${result.learningData.success ? 'Yes' : 'No'}`);
153
+ // Display AI insights if available
154
+ if (result.aiAnalysis) {
155
+ clack.note(`Confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%`, 'AI Analysis');
156
+ if (result.aiAnalysis.recommendations && result.aiAnalysis.recommendations.length > 0) {
157
+ clack.note(result.aiAnalysis.recommendations.join('\n'), 'AI Recommendations');
158
+ }
239
159
  }
240
160
 
241
- console.log('\n🚀 Your app is now ready to track user behavior!');
242
- console.log('📊 View sessions in your HumanBehavior dashboard');
243
-
244
161
  } else {
245
- console.log('\n❌ Installation failed:');
246
- result.errors.forEach((error: string) => {
247
- console.log(` ${error}`);
248
- });
162
+ clack.cancel('Installation failed');
249
163
 
250
- console.log('\n💡 Try running with --help for more options');
164
+ if (result.errors && result.errors.length > 0) {
165
+ clack.note(result.errors.join('\n'), 'Errors');
166
+ }
251
167
  }
252
168
  }
253
169
  }
254
170
 
255
- // CLI argument parsing
256
171
  function parseArgs(): AICLIOptions {
257
172
  const args = process.argv.slice(2);
258
173
  const options: AICLIOptions = {};
@@ -260,27 +175,33 @@ function parseArgs(): AICLIOptions {
260
175
  for (let i = 0; i < args.length; i++) {
261
176
  const arg = args[i];
262
177
 
263
- if (arg === '--yes' || arg === '-y') {
264
- options.yes = true;
265
- } else if (arg === '--dry-run' || arg === '-d') {
266
- options.dryRun = true;
267
- } else if (arg === '--project' || arg === '-p') {
268
- options.projectPath = args[i + 1];
269
- i++;
270
- } else if (arg === '--traditional' || arg === '-t') {
271
- options.useAI = false;
272
- } else if (arg === '--browser' || arg === '-b') {
273
- options.browser = true;
274
- } else if (arg === '--manual' || arg === '-m') {
275
- options.manual = true;
276
- } else if (arg === '--framework' || arg === '-f') {
277
- options.framework = args[i + 1];
278
- i++;
279
- } else if (arg === '--help' || arg === '-h') {
280
- showHelp();
281
- process.exit(0);
282
- } else if (!options.apiKey) {
283
- options.apiKey = arg;
178
+ switch (arg) {
179
+ case '--help':
180
+ case '-h':
181
+ showHelp();
182
+ process.exit(0);
183
+ break;
184
+ case '--yes':
185
+ case '-y':
186
+ options.yes = true;
187
+ break;
188
+ case '--dry-run':
189
+ options.dryRun = true;
190
+ break;
191
+
192
+ case '--project':
193
+ case '-p':
194
+ options.projectPath = args[++i];
195
+ break;
196
+ case '--framework':
197
+ case '-f':
198
+ options.framework = args[++i];
199
+ break;
200
+ default:
201
+ if (!options.apiKey && !arg.startsWith('-')) {
202
+ options.apiKey = arg;
203
+ }
204
+ break;
284
205
  }
285
206
  }
286
207
 
@@ -289,81 +210,34 @@ function parseArgs(): AICLIOptions {
289
210
 
290
211
  function showHelp() {
291
212
  console.log(`
292
- AI-Enhanced HumanBehavior SDK Auto-Installation CLI
213
+ 🤖 HumanBehavior SDK AI Auto-Installation
293
214
 
294
215
  Usage: npx humanbehavior-js ai-auto-install [api-key] [options]
295
216
 
296
- This tool uses AI to intelligently detect frameworks, analyze code patterns,
297
- and generate optimal integration code that's both future-proof and backward-compatible.
298
-
299
- Arguments:
300
- api-key Your HumanBehavior API key
301
-
302
217
  Options:
303
- -y, --yes Skip all prompts and use defaults
304
- -d, --dry-run Show what would be changed without making changes
305
- -p, --project <path> Project directory (default: current directory)
306
- -t, --traditional Force traditional installation mode
307
- -b, --browser Browser-based AI installation
308
- -m, --manual Manual framework selection
309
- -f, --framework <f> Specify framework for manual mode
310
- -h, --help Show this help message
311
-
312
- Installation Modes:
313
- 1. Manual AI-Enhanced (default): Choose your framework and use AI for optimization
314
- 2. Traditional: Standard framework detection and installation
315
- 3. Browser: Browser-based AI detection and code generation
218
+ -h, --help Show this help message
219
+ -y, --yes Skip all prompts and use defaults
220
+ --dry-run Show what would be changed without making changes
221
+
222
+ -p, --project <path> Specify project directory
223
+ -f, --framework <name> Specify framework manually
316
224
 
317
225
  Examples:
318
- npx humanbehavior-js ai-auto-install your-api-key
319
- npx humanbehavior-js ai-auto-install your-api-key --manual --framework react
320
- npx humanbehavior-js ai-auto-install your-api-key --traditional
321
- npx humanbehavior-js ai-auto-install your-api-key --browser
322
-
323
- Supported Frameworks:
324
- ✅ React (CRA, Vite, Webpack)
325
- ✅ Next.js (App Router, Pages Router)
326
- ✅ Vue (Vue CLI, Vite)
327
- ✅ Angular
328
- ✅ Svelte (SvelteKit, Vite)
329
- ✅ Remix
330
- ✅ Vanilla JS/TS
331
- ✅ Node.js (CommonJS & ESM)
332
-
333
- AI Features:
334
- 🔍 Intelligent framework detection beyond package.json
335
- 📊 Code pattern analysis and optimization
336
- 🔄 Future-proof integration strategies
337
- 🔙 Backward compatibility with legacy frameworks
338
- 🧠 Learning from installation patterns
339
- ⚡ Adaptive code generation for new frameworks
340
- 🔧 Smart conflict resolution
341
- 📈 Performance optimization recommendations
342
-
343
- The AI-enhanced tool will:
344
- 1. 🔍 Analyze your codebase with AI to detect patterns
345
- 2. 🎯 Determine optimal integration strategy
346
- 3. 📦 Install the humanbehavior-js package
347
- 4. ✏️ Generate AI-optimized integration code
348
- 5. 🔧 Apply modifications with conflict resolution
349
- 6. 🧠 Learn from the installation for future improvements
350
- 7. 🚀 Make your app ready to track user behavior
226
+ npx humanbehavior-js ai-auto-install
227
+ npx humanbehavior-js ai-auto-install hb_your_api_key_here
228
+ npx humanbehavior-js ai-auto-install --project ./my-app --ai
229
+ npx humanbehavior-js ai-auto-install --framework react --yes
351
230
  `);
352
231
  }
353
232
 
354
233
  // Main execution
355
- const options = parseArgs();
356
-
357
- // Check if we have enough arguments (api-key is required)
358
- if (process.argv.length < 3 || process.argv.includes('--help') || process.argv.includes('-h')) {
359
- showHelp();
360
- process.exit(0);
234
+ if (import.meta.url === `file://${process.argv[1]}`) {
235
+ const options = parseArgs();
236
+ const cli = new AIAutoInstallCLI(options);
237
+ cli.run().catch((error) => {
238
+ clack.cancel(`Unexpected error: ${error.message}`);
239
+ process.exit(1);
240
+ });
361
241
  }
362
242
 
363
- const cli = new AIAutoInstallCLI(options);
364
- cli.run().catch((error) => {
365
- console.error('❌ Fatal error:', error);
366
- process.exit(1);
367
- });
368
-
369
243
  export { AIAutoInstallCLI };