humanbehavior-js 0.4.7 → 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 (52) hide show
  1. package/dist/cjs/angular/index.cjs +5 -6
  2. package/dist/cjs/angular/index.cjs.map +1 -1
  3. package/dist/cjs/index.cjs +5 -6
  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 +5 -6
  8. package/dist/cjs/react/index.cjs.map +1 -1
  9. package/dist/cjs/remix/index.cjs +5 -6
  10. package/dist/cjs/remix/index.cjs.map +1 -1
  11. package/dist/cjs/svelte/index.cjs +5 -6
  12. package/dist/cjs/svelte/index.cjs.map +1 -1
  13. package/dist/cjs/vue/index.cjs +5 -6
  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 +5 -6
  22. package/dist/esm/angular/index.js.map +1 -1
  23. package/dist/esm/index.js +5 -6
  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 +5 -6
  28. package/dist/esm/react/index.js.map +1 -1
  29. package/dist/esm/remix/index.js +5 -6
  30. package/dist/esm/remix/index.js.map +1 -1
  31. package/dist/esm/svelte/index.js +5 -6
  32. package/dist/esm/svelte/index.js.map +1 -1
  33. package/dist/esm/vue/index.js +5 -6
  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.map +1 -1
  38. package/dist/types/install-wizard.d.ts +8 -8
  39. package/dist/types/wizard/index.d.ts +489 -0
  40. package/package.json +14 -8
  41. package/rollup.config.js +65 -3
  42. package/src/react/AutoInstallWizard.tsx +1 -1
  43. package/src/tracker.ts +5 -6
  44. package/src/wizard/README.md +114 -0
  45. package/src/wizard/ai/ai-install-wizard.ts +894 -0
  46. package/src/wizard/ai/manual-framework-wizard.ts +236 -0
  47. package/src/wizard/cli/ai-auto-install.ts +369 -0
  48. package/src/{cli → wizard/cli}/auto-install.ts +1 -1
  49. package/src/{install-wizard.ts → wizard/core/install-wizard.ts} +12 -10
  50. package/src/wizard/index.ts +23 -0
  51. package/src/wizard/services/centralized-ai-service.ts +668 -0
  52. package/src/wizard/services/remote-ai-service.ts +224 -0
@@ -0,0 +1,2024 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as readline from 'readline';
5
+
6
+ /******************************************************************************
7
+ Copyright (c) Microsoft Corporation.
8
+
9
+ Permission to use, copy, modify, and/or distribute this software for any
10
+ purpose with or without fee is hereby granted.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
+ PERFORMANCE OF THIS SOFTWARE.
19
+ ***************************************************************************** */
20
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
+
22
+
23
+ function __awaiter(thisArg, _arguments, P, generator) {
24
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
25
+ return new (P || (P = Promise))(function (resolve, reject) {
26
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
27
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
28
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
29
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
30
+ });
31
+ }
32
+
33
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
34
+ var e = new Error(message);
35
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
36
+ };
37
+
38
+ /**
39
+ * HumanBehavior SDK Auto-Installation Wizard
40
+ *
41
+ * This wizard automatically detects the user's framework and modifies their codebase
42
+ * to integrate the SDK with minimal user intervention.
43
+ */
44
+ class AutoInstallationWizard {
45
+ constructor(apiKey, projectRoot = process.cwd()) {
46
+ this.framework = null;
47
+ this.apiKey = apiKey;
48
+ this.projectRoot = projectRoot;
49
+ }
50
+ /**
51
+ * Main installation method - detects framework and auto-installs
52
+ */
53
+ install() {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ try {
56
+ // Step 1: Detect framework
57
+ this.framework = yield this.detectFramework();
58
+ // Step 2: Install package
59
+ yield this.installPackage();
60
+ // Step 3: Generate and apply code modifications
61
+ const modifications = yield this.generateModifications();
62
+ yield this.applyModifications(modifications);
63
+ // Step 4: Generate next steps
64
+ const nextSteps = this.generateNextSteps();
65
+ return {
66
+ success: true,
67
+ framework: this.framework,
68
+ modifications,
69
+ errors: [],
70
+ nextSteps
71
+ };
72
+ }
73
+ catch (error) {
74
+ return {
75
+ success: false,
76
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
77
+ modifications: [],
78
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
79
+ nextSteps: []
80
+ };
81
+ }
82
+ });
83
+ }
84
+ /**
85
+ * Detect the current framework and project setup
86
+ */
87
+ detectFramework() {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ const packageJsonPath = path.join(this.projectRoot, 'package.json');
90
+ if (!fs.existsSync(packageJsonPath)) {
91
+ return {
92
+ name: 'vanilla',
93
+ type: 'vanilla',
94
+ projectRoot: this.projectRoot
95
+ };
96
+ }
97
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
98
+ const dependencies = Object.assign(Object.assign({}, packageJson.dependencies), packageJson.devDependencies);
99
+ // Detect framework
100
+ let framework = {
101
+ name: 'vanilla',
102
+ type: 'vanilla',
103
+ projectRoot: this.projectRoot
104
+ };
105
+ if (dependencies.nuxt) {
106
+ framework = {
107
+ name: 'nuxt',
108
+ type: 'nuxt',
109
+ hasTypeScript: !!dependencies.typescript,
110
+ hasRouter: true,
111
+ projectRoot: this.projectRoot
112
+ };
113
+ }
114
+ else if (dependencies.next) {
115
+ framework = {
116
+ name: 'nextjs',
117
+ type: 'nextjs',
118
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],
119
+ hasRouter: true,
120
+ projectRoot: this.projectRoot
121
+ };
122
+ }
123
+ else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {
124
+ framework = {
125
+ name: 'remix',
126
+ type: 'remix',
127
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
128
+ hasRouter: true,
129
+ projectRoot: this.projectRoot
130
+ };
131
+ }
132
+ else if (dependencies.react) {
133
+ framework = {
134
+ name: 'react',
135
+ type: 'react',
136
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
137
+ hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],
138
+ projectRoot: this.projectRoot
139
+ };
140
+ }
141
+ else if (dependencies.vue) {
142
+ framework = {
143
+ name: 'vue',
144
+ type: 'vue',
145
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],
146
+ hasRouter: !!dependencies['vue-router'],
147
+ projectRoot: this.projectRoot
148
+ };
149
+ }
150
+ else if (dependencies['@angular/core']) {
151
+ framework = {
152
+ name: 'angular',
153
+ type: 'angular',
154
+ hasTypeScript: true,
155
+ hasRouter: true,
156
+ projectRoot: this.projectRoot
157
+ };
158
+ }
159
+ else if (dependencies.svelte) {
160
+ framework = {
161
+ name: 'svelte',
162
+ type: 'svelte',
163
+ hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],
164
+ hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],
165
+ projectRoot: this.projectRoot
166
+ };
167
+ }
168
+ // Detect bundler
169
+ if (dependencies.vite) {
170
+ framework.bundler = 'vite';
171
+ }
172
+ else if (dependencies.webpack) {
173
+ framework.bundler = 'webpack';
174
+ }
175
+ else if (dependencies.esbuild) {
176
+ framework.bundler = 'esbuild';
177
+ }
178
+ else if (dependencies.rollup) {
179
+ framework.bundler = 'rollup';
180
+ }
181
+ // Detect package manager
182
+ if (fs.existsSync(path.join(this.projectRoot, 'yarn.lock'))) {
183
+ framework.packageManager = 'yarn';
184
+ }
185
+ else if (fs.existsSync(path.join(this.projectRoot, 'pnpm-lock.yaml'))) {
186
+ framework.packageManager = 'pnpm';
187
+ }
188
+ else {
189
+ framework.packageManager = 'npm';
190
+ }
191
+ return framework;
192
+ });
193
+ }
194
+ /**
195
+ * Install the SDK package
196
+ */
197
+ installPackage() {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ var _a, _b;
200
+ const { execSync } = yield import('child_process');
201
+ const command = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.packageManager) === 'yarn'
202
+ ? 'yarn add humanbehavior-js'
203
+ : ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.packageManager) === 'pnpm'
204
+ ? 'pnpm add humanbehavior-js'
205
+ : 'npm install humanbehavior-js';
206
+ try {
207
+ execSync(command, { cwd: this.projectRoot, stdio: 'inherit' });
208
+ }
209
+ catch (error) {
210
+ throw new Error(`Failed to install humanbehavior-js: ${error}`);
211
+ }
212
+ });
213
+ }
214
+ /**
215
+ * Generate code modifications based on framework
216
+ */
217
+ generateModifications() {
218
+ return __awaiter(this, void 0, void 0, function* () {
219
+ var _a;
220
+ const modifications = [];
221
+ switch ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type) {
222
+ case 'react':
223
+ modifications.push(...yield this.generateReactModifications());
224
+ break;
225
+ case 'nextjs':
226
+ modifications.push(...yield this.generateNextJSModifications());
227
+ break;
228
+ case 'nuxt':
229
+ modifications.push(...yield this.generateNuxtModifications());
230
+ break;
231
+ case 'remix':
232
+ modifications.push(...yield this.generateRemixModifications());
233
+ break;
234
+ case 'vue':
235
+ modifications.push(...yield this.generateVueModifications());
236
+ break;
237
+ case 'angular':
238
+ modifications.push(...yield this.generateAngularModifications());
239
+ break;
240
+ case 'svelte':
241
+ modifications.push(...yield this.generateSvelteModifications());
242
+ break;
243
+ default:
244
+ modifications.push(...yield this.generateVanillaModifications());
245
+ }
246
+ return modifications;
247
+ });
248
+ }
249
+ /**
250
+ * Generate React-specific modifications
251
+ */
252
+ generateReactModifications() {
253
+ return __awaiter(this, void 0, void 0, function* () {
254
+ const modifications = [];
255
+ // Find main App component or index file
256
+ const appFile = this.findReactAppFile();
257
+ if (appFile) {
258
+ const content = fs.readFileSync(appFile, 'utf8');
259
+ const modifiedContent = this.injectReactProvider(content, appFile);
260
+ modifications.push({
261
+ filePath: appFile,
262
+ action: 'modify',
263
+ content: modifiedContent,
264
+ description: 'Added HumanBehaviorProvider to React app'
265
+ });
266
+ }
267
+ // Create or append to environment file
268
+ modifications.push(this.createEnvironmentModification(this.framework));
269
+ return modifications;
270
+ });
271
+ }
272
+ /**
273
+ * Generate Next.js-specific modifications
274
+ */
275
+ generateNextJSModifications() {
276
+ return __awaiter(this, void 0, void 0, function* () {
277
+ const modifications = [];
278
+ // Check for App Router
279
+ const appLayoutFile = path.join(this.projectRoot, 'src', 'app', 'layout.tsx');
280
+ const pagesLayoutFile = path.join(this.projectRoot, 'src', 'pages', '_app.tsx');
281
+ if (fs.existsSync(appLayoutFile)) {
282
+ // Create providers.tsx file for App Router
283
+ modifications.push({
284
+ filePath: path.join(this.projectRoot, 'src', 'app', 'providers.tsx'),
285
+ action: 'create',
286
+ content: `'use client';
287
+
288
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
289
+
290
+ export function Providers({ children }: { children: React.ReactNode }) {
291
+ return (
292
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
293
+ {children}
294
+ </HumanBehaviorProvider>
295
+ );
296
+ }`,
297
+ description: 'Created providers.tsx file for Next.js App Router'
298
+ });
299
+ // Modify layout.tsx to use the provider
300
+ const content = fs.readFileSync(appLayoutFile, 'utf8');
301
+ const modifiedContent = this.injectNextJSAppRouter(content);
302
+ modifications.push({
303
+ filePath: appLayoutFile,
304
+ action: 'modify',
305
+ content: modifiedContent,
306
+ description: 'Added Providers wrapper to Next.js App Router layout'
307
+ });
308
+ }
309
+ else if (fs.existsSync(pagesLayoutFile)) {
310
+ // Create providers.tsx file for Pages Router
311
+ modifications.push({
312
+ filePath: path.join(this.projectRoot, 'src', 'components', 'providers.tsx'),
313
+ action: 'create',
314
+ content: `'use client';
315
+
316
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
317
+
318
+ export function Providers({ children }: { children: React.ReactNode }) {
319
+ return (
320
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
321
+ {children}
322
+ </HumanBehaviorProvider>
323
+ );
324
+ }`,
325
+ description: 'Created providers.tsx file for Pages Router'
326
+ });
327
+ // Modify _app.tsx to use the provider
328
+ const content = fs.readFileSync(pagesLayoutFile, 'utf8');
329
+ const modifiedContent = this.injectNextJSPagesRouter(content);
330
+ modifications.push({
331
+ filePath: pagesLayoutFile,
332
+ action: 'modify',
333
+ content: modifiedContent,
334
+ description: 'Added Providers wrapper to Next.js Pages Router'
335
+ });
336
+ }
337
+ // Create or append to environment file
338
+ modifications.push(this.createEnvironmentModification(this.framework));
339
+ return modifications;
340
+ });
341
+ }
342
+ /**
343
+ * Generate Nuxt-specific modifications
344
+ */
345
+ generateNuxtModifications() {
346
+ return __awaiter(this, void 0, void 0, function* () {
347
+ const modifications = [];
348
+ // Create plugin file for Nuxt (in app directory)
349
+ const pluginFile = path.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');
350
+ modifications.push({
351
+ filePath: pluginFile,
352
+ action: 'create',
353
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
354
+
355
+ export default defineNuxtPlugin(() => {
356
+ const config = useRuntimeConfig();
357
+
358
+ // Initialize HumanBehavior SDK (client-side only)
359
+ if (typeof window !== 'undefined') {
360
+ const apiKey = config.public.humanBehaviorApiKey;
361
+ console.log('HumanBehavior: API key:', apiKey ? 'present' : 'missing');
362
+
363
+ if (apiKey) {
364
+ try {
365
+ const tracker = HumanBehaviorTracker.init(apiKey);
366
+ console.log('HumanBehavior: Tracker initialized successfully');
367
+ } catch (error) {
368
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
369
+ }
370
+ } else {
371
+ console.error('HumanBehavior: No API key found in runtime config');
372
+ }
373
+ }
374
+ });`,
375
+ description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'
376
+ });
377
+ // Create environment configuration
378
+ const nuxtConfigFile = path.join(this.projectRoot, 'nuxt.config.ts');
379
+ if (fs.existsSync(nuxtConfigFile)) {
380
+ const content = fs.readFileSync(nuxtConfigFile, 'utf8');
381
+ const modifiedContent = this.injectNuxtConfig(content);
382
+ modifications.push({
383
+ filePath: nuxtConfigFile,
384
+ action: 'modify',
385
+ content: modifiedContent,
386
+ description: 'Added HumanBehavior runtime config to Nuxt config'
387
+ });
388
+ }
389
+ // Create or append to environment file
390
+ modifications.push(this.createEnvironmentModification(this.framework));
391
+ return modifications;
392
+ });
393
+ }
394
+ /**
395
+ * Generate Remix-specific modifications
396
+ */
397
+ generateRemixModifications() {
398
+ return __awaiter(this, void 0, void 0, function* () {
399
+ const modifications = [];
400
+ // Find root.tsx file
401
+ const rootFile = path.join(this.projectRoot, 'app', 'root.tsx');
402
+ if (fs.existsSync(rootFile)) {
403
+ const content = fs.readFileSync(rootFile, 'utf8');
404
+ const modifiedContent = this.injectRemixProvider(content);
405
+ modifications.push({
406
+ filePath: rootFile,
407
+ action: 'modify',
408
+ content: modifiedContent,
409
+ description: 'Added HumanBehaviorProvider to Remix root component'
410
+ });
411
+ }
412
+ // Create or append to environment file
413
+ modifications.push(this.createEnvironmentModification(this.framework));
414
+ return modifications;
415
+ });
416
+ }
417
+ /**
418
+ * Generate Vue-specific modifications
419
+ */
420
+ generateVueModifications() {
421
+ return __awaiter(this, void 0, void 0, function* () {
422
+ const modifications = [];
423
+ // Find main.js or main.ts
424
+ const mainFile = this.findVueMainFile();
425
+ if (mainFile) {
426
+ const content = fs.readFileSync(mainFile, 'utf8');
427
+ const modifiedContent = this.injectVuePlugin(content);
428
+ modifications.push({
429
+ filePath: mainFile,
430
+ action: 'modify',
431
+ content: modifiedContent,
432
+ description: 'Added HumanBehaviorPlugin to Vue app'
433
+ });
434
+ }
435
+ // Create or append to environment file
436
+ modifications.push(this.createEnvironmentModification(this.framework));
437
+ return modifications;
438
+ });
439
+ }
440
+ /**
441
+ * Generate Angular-specific modifications
442
+ */
443
+ generateAngularModifications() {
444
+ return __awaiter(this, void 0, void 0, function* () {
445
+ const modifications = [];
446
+ // Check for modern Angular (standalone components) vs legacy (NgModule)
447
+ const appModuleFile = path.join(this.projectRoot, 'src', 'app', 'app.module.ts');
448
+ const appComponentFile = path.join(this.projectRoot, 'src', 'app', 'app.ts');
449
+ const mainFile = path.join(this.projectRoot, 'src', 'main.ts');
450
+ const isModernAngular = fs.existsSync(appComponentFile) && !fs.existsSync(appModuleFile);
451
+ if (isModernAngular) {
452
+ // Modern Angular 17+ with standalone components
453
+ if (fs.existsSync(mainFile)) {
454
+ const content = fs.readFileSync(mainFile, 'utf8');
455
+ const modifiedContent = this.injectAngularStandaloneInit(content);
456
+ modifications.push({
457
+ filePath: mainFile,
458
+ action: 'modify',
459
+ content: modifiedContent,
460
+ description: 'Added HumanBehavior initialization to Angular main.ts'
461
+ });
462
+ }
463
+ }
464
+ else if (fs.existsSync(appModuleFile)) {
465
+ // Legacy Angular with NgModule
466
+ const content = fs.readFileSync(appModuleFile, 'utf8');
467
+ const modifiedContent = this.injectAngularModule(content);
468
+ modifications.push({
469
+ filePath: appModuleFile,
470
+ action: 'modify',
471
+ content: modifiedContent,
472
+ description: 'Added HumanBehaviorModule to Angular app'
473
+ });
474
+ }
475
+ // Handle Angular environment file (legacy structure)
476
+ const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');
477
+ if (fs.existsSync(envFile)) {
478
+ const content = fs.readFileSync(envFile, 'utf8');
479
+ if (!content.includes('humanBehaviorApiKey')) {
480
+ const modifiedContent = content.replace(/export const environment = {([\s\S]*?)};/, `export const environment = {
481
+ $1,
482
+ humanBehaviorApiKey: process.env['HUMANBEHAVIOR_API_KEY'] || ''
483
+ };`);
484
+ modifications.push({
485
+ filePath: envFile,
486
+ action: 'modify',
487
+ content: modifiedContent,
488
+ description: 'Added API key to Angular environment'
489
+ });
490
+ }
491
+ }
492
+ // Create or append to environment file
493
+ modifications.push(this.createEnvironmentModification(this.framework));
494
+ return modifications;
495
+ });
496
+ }
497
+ /**
498
+ * Generate Svelte-specific modifications
499
+ */
500
+ generateSvelteModifications() {
501
+ return __awaiter(this, void 0, void 0, function* () {
502
+ const modifications = [];
503
+ // Check for SvelteKit
504
+ const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');
505
+ const isSvelteKit = fs.existsSync(svelteConfigFile);
506
+ if (isSvelteKit) {
507
+ // SvelteKit - create layout file
508
+ const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');
509
+ if (fs.existsSync(layoutFile)) {
510
+ const content = fs.readFileSync(layoutFile, 'utf8');
511
+ const modifiedContent = this.injectSvelteKitLayout(content);
512
+ modifications.push({
513
+ filePath: layoutFile,
514
+ action: 'modify',
515
+ content: modifiedContent,
516
+ description: 'Added HumanBehavior store to SvelteKit layout'
517
+ });
518
+ }
519
+ }
520
+ else {
521
+ // Regular Svelte - modify main file
522
+ const mainFile = this.findSvelteMainFile();
523
+ if (mainFile) {
524
+ const content = fs.readFileSync(mainFile, 'utf8');
525
+ const modifiedContent = this.injectSvelteStore(content);
526
+ modifications.push({
527
+ filePath: mainFile,
528
+ action: 'modify',
529
+ content: modifiedContent,
530
+ description: 'Added HumanBehavior store to Svelte app'
531
+ });
532
+ }
533
+ }
534
+ // Create or append to environment file
535
+ modifications.push(this.createEnvironmentModification(this.framework));
536
+ return modifications;
537
+ });
538
+ }
539
+ /**
540
+ * Generate vanilla JS/TS modifications
541
+ */
542
+ generateVanillaModifications() {
543
+ return __awaiter(this, void 0, void 0, function* () {
544
+ const modifications = [];
545
+ // Find HTML file to inject script
546
+ const htmlFile = this.findHTMLFile();
547
+ if (htmlFile) {
548
+ const content = fs.readFileSync(htmlFile, 'utf8');
549
+ const modifiedContent = this.injectVanillaScript(content);
550
+ modifications.push({
551
+ filePath: htmlFile,
552
+ action: 'modify',
553
+ content: modifiedContent,
554
+ description: 'Added HumanBehavior CDN script to HTML file'
555
+ });
556
+ }
557
+ // Create or append to environment file
558
+ modifications.push(this.createEnvironmentModification(this.framework));
559
+ return modifications;
560
+ });
561
+ }
562
+ /**
563
+ * Apply modifications to the codebase
564
+ */
565
+ applyModifications(modifications) {
566
+ return __awaiter(this, void 0, void 0, function* () {
567
+ for (const modification of modifications) {
568
+ try {
569
+ const dir = path.dirname(modification.filePath);
570
+ if (!fs.existsSync(dir)) {
571
+ fs.mkdirSync(dir, { recursive: true });
572
+ }
573
+ switch (modification.action) {
574
+ case 'create':
575
+ fs.writeFileSync(modification.filePath, modification.content);
576
+ break;
577
+ case 'modify':
578
+ fs.writeFileSync(modification.filePath, modification.content);
579
+ break;
580
+ case 'append':
581
+ fs.appendFileSync(modification.filePath, '\n' + modification.content);
582
+ break;
583
+ }
584
+ }
585
+ catch (error) {
586
+ throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);
587
+ }
588
+ }
589
+ });
590
+ }
591
+ /**
592
+ * Generate next steps for the user
593
+ */
594
+ generateNextSteps() {
595
+ var _a, _b;
596
+ const steps = [
597
+ '✅ SDK installed and configured automatically!',
598
+ '🚀 Your app is now tracking user behavior',
599
+ '📊 View sessions in your HumanBehavior dashboard',
600
+ '🔧 Customize tracking in your code as needed'
601
+ ];
602
+ if (((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type) === 'react' || ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.type) === 'nextjs') {
603
+ steps.push('💡 Use the useHumanBehavior() hook to track custom events');
604
+ }
605
+ return steps;
606
+ }
607
+ // Helper methods for file detection and content injection
608
+ findReactAppFile() {
609
+ const possibleFiles = [
610
+ 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',
611
+ 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'
612
+ ];
613
+ for (const file of possibleFiles) {
614
+ const fullPath = path.join(this.projectRoot, file);
615
+ if (fs.existsSync(fullPath)) {
616
+ return fullPath;
617
+ }
618
+ }
619
+ return null;
620
+ }
621
+ findVueMainFile() {
622
+ const possibleFiles = [
623
+ 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'
624
+ ];
625
+ for (const file of possibleFiles) {
626
+ const fullPath = path.join(this.projectRoot, file);
627
+ if (fs.existsSync(fullPath)) {
628
+ return fullPath;
629
+ }
630
+ }
631
+ return null;
632
+ }
633
+ findSvelteMainFile() {
634
+ const possibleFiles = [
635
+ 'src/main.js', 'src/main.ts', 'src/main.svelte'
636
+ ];
637
+ for (const file of possibleFiles) {
638
+ const fullPath = path.join(this.projectRoot, file);
639
+ if (fs.existsSync(fullPath)) {
640
+ return fullPath;
641
+ }
642
+ }
643
+ return null;
644
+ }
645
+ findHTMLFile() {
646
+ const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];
647
+ for (const file of possibleFiles) {
648
+ const fullPath = path.join(this.projectRoot, file);
649
+ if (fs.existsSync(fullPath)) {
650
+ return fullPath;
651
+ }
652
+ }
653
+ return null;
654
+ }
655
+ injectReactProvider(content, filePath) {
656
+ var _a;
657
+ filePath.endsWith('.tsx') || filePath.endsWith('.ts');
658
+ // Check if already has HumanBehaviorProvider
659
+ if (content.includes('HumanBehaviorProvider')) {
660
+ return content;
661
+ }
662
+ // Determine the correct environment variable syntax based on bundler
663
+ const isVite = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.bundler) === 'vite';
664
+ const envVar = isVite
665
+ ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!'
666
+ : 'process.env.HUMANBEHAVIOR_API_KEY!';
667
+ const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;
668
+ // Simple injection - in production, you'd want more sophisticated parsing
669
+ if (content.includes('function App()') || content.includes('const App =')) {
670
+ return content.replace(/(function App\(\)|const App =)/, `${importStatement}\n\n$1`).replace(/return \(([\s\S]*?)\);/, `return (
671
+ <HumanBehaviorProvider apiKey={${envVar}}>
672
+ $1
673
+ </HumanBehaviorProvider>
674
+ );`);
675
+ }
676
+ return `${importStatement}\n\n${content}`;
677
+ }
678
+ injectNextJSAppRouter(content) {
679
+ if (content.includes('Providers')) {
680
+ return content;
681
+ }
682
+ const importStatement = `import { Providers } from './providers';`;
683
+ // First, add the import statement
684
+ let modifiedContent = content.replace(/export default function RootLayout/, `${importStatement}\n\nexport default function RootLayout`);
685
+ // Then wrap the body content with Providers
686
+ // Use a more specific approach to handle the body content
687
+ modifiedContent = modifiedContent.replace(/<body([^>]*)>([\s\S]*?)<\/body>/, (match, bodyAttrs, bodyContent) => {
688
+ // Trim whitespace and newlines from bodyContent
689
+ const trimmedContent = bodyContent.trim();
690
+ return `<body${bodyAttrs}>
691
+ <Providers>
692
+ ${trimmedContent}
693
+ </Providers>
694
+ </body>`;
695
+ });
696
+ return modifiedContent;
697
+ }
698
+ injectNextJSPagesRouter(content) {
699
+ if (content.includes('Providers')) {
700
+ return content;
701
+ }
702
+ const importStatement = `import { Providers } from '../components/providers';`;
703
+ return content.replace(/function MyApp/, `${importStatement}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/, `return (
704
+ <Providers>
705
+ $1
706
+ </Providers>
707
+ );`);
708
+ }
709
+ injectRemixProvider(content) {
710
+ if (content.includes('HumanBehaviorProvider')) {
711
+ return content;
712
+ }
713
+ const importStatement = `import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';`;
714
+ const useLoaderDataImport = `import { useLoaderData } from "@remix-run/react";`;
715
+ // Add imports more robustly
716
+ let modifiedContent = content;
717
+ // Add HumanBehaviorProvider import - find the last import and add after it
718
+ if (!content.includes('HumanBehaviorProvider')) {
719
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
720
+ if (lastImportIndex !== -1) {
721
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
722
+ if (nextLineIndex !== -1) {
723
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
724
+ importStatement + '\n' +
725
+ modifiedContent.slice(nextLineIndex + 1);
726
+ }
727
+ else {
728
+ modifiedContent = modifiedContent + '\n' + importStatement;
729
+ }
730
+ }
731
+ else {
732
+ modifiedContent = importStatement + '\n' + modifiedContent;
733
+ }
734
+ }
735
+ // Add useLoaderData import - find the last import and add after it
736
+ if (!content.includes('useLoaderData')) {
737
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
738
+ if (lastImportIndex !== -1) {
739
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
740
+ if (nextLineIndex !== -1) {
741
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
742
+ useLoaderDataImport + '\n' +
743
+ modifiedContent.slice(nextLineIndex + 1);
744
+ }
745
+ else {
746
+ modifiedContent = modifiedContent + '\n' + useLoaderDataImport;
747
+ }
748
+ }
749
+ else {
750
+ modifiedContent = useLoaderDataImport + '\n' + modifiedContent;
751
+ }
752
+ }
753
+ // Add loader function before the App component
754
+ if (!content.includes('export const loader')) {
755
+ modifiedContent = modifiedContent.replace(/export default function App\(\)/, `export const loader = createHumanBehaviorLoader();
756
+
757
+ export default function App()`);
758
+ }
759
+ // Wrap the App component content with HumanBehaviorProvider
760
+ modifiedContent = modifiedContent.replace(/export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/, `export default function App() {
761
+ const data = useLoaderData<typeof loader>();
762
+
763
+ return (
764
+ <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
765
+ $1
766
+ </HumanBehaviorProvider>
767
+ );
768
+ }`);
769
+ return modifiedContent;
770
+ }
771
+ injectVuePlugin(content) {
772
+ if (content.includes('HumanBehaviorPlugin')) {
773
+ return content;
774
+ }
775
+ const importStatement = `import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';`;
776
+ const pluginUsage = `app.use(HumanBehaviorPlugin, {
777
+ apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY
778
+ });`;
779
+ // Handle both Vue 2 and Vue 3 patterns
780
+ if (content.includes('createApp')) {
781
+ // Vue 3
782
+ return content.replace(/import.*from.*['"]vue['"]/, `$&\n${importStatement}`).replace(/app\.mount\(/, `${pluginUsage}\n\napp.mount(`);
783
+ }
784
+ else {
785
+ // Vue 2
786
+ return content.replace(/import.*from.*['"]vue['"]/, `$&\n${importStatement}`).replace(/new Vue\(/, `${pluginUsage}\n\nnew Vue(`);
787
+ }
788
+ }
789
+ injectAngularModule(content) {
790
+ if (content.includes('HumanBehaviorModule')) {
791
+ return content;
792
+ }
793
+ const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;
794
+ const environmentImport = `import { environment } from '../environments/environment';`;
795
+ // Add environment import if not present
796
+ let modifiedContent = content;
797
+ if (!content.includes('environment')) {
798
+ modifiedContent = content.replace(/import.*from.*['"]@angular/, `${environmentImport}\n$&`);
799
+ }
800
+ return modifiedContent.replace(/imports:\s*\[([\s\S]*?)\]/, `imports: [
801
+ $1,
802
+ HumanBehaviorModule.forRoot({
803
+ apiKey: environment.humanBehaviorApiKey
804
+ })
805
+ ]`).replace(/import.*from.*['"]@angular/, `$&\n${importStatement}`);
806
+ }
807
+ injectAngularStandaloneInit(content) {
808
+ if (content.includes('initializeHumanBehavior')) {
809
+ return content;
810
+ }
811
+ const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;
812
+ // Add import at the top
813
+ let modifiedContent = content.replace(/import.*from.*['"]@angular/, `${importStatement}\n$&`);
814
+ // Add initialization after bootstrapApplication
815
+ modifiedContent = modifiedContent.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/, `$1
816
+
817
+ // Initialize HumanBehavior SDK (client-side only)
818
+ if (typeof window !== 'undefined') {
819
+ const tracker = initializeHumanBehavior(
820
+ '${this.apiKey}'
821
+ );
822
+ }`);
823
+ return modifiedContent;
824
+ }
825
+ injectSvelteStore(content) {
826
+ if (content.includes('humanBehaviorStore')) {
827
+ return content;
828
+ }
829
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
830
+ const initCode = `humanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
831
+ return `${importStatement}\n${initCode}\n\n${content}`;
832
+ }
833
+ injectSvelteKitLayout(content) {
834
+ if (content.includes('humanBehaviorStore')) {
835
+ return content;
836
+ }
837
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
838
+ const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;
839
+ const initCode = `humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
840
+ // Add to script section - handle different script tag patterns
841
+ if (content.includes('<script lang="ts">')) {
842
+ return content.replace(/<script lang="ts">/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
843
+ }
844
+ else if (content.includes('<script>')) {
845
+ return content.replace(/<script>/, `<script>\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
846
+ }
847
+ else if (content.includes('<script context="module">')) {
848
+ return content.replace(/<script\s+context="module">/, `<script context="module">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
849
+ }
850
+ else {
851
+ // If no script tag found, add one at the beginning
852
+ return content.replace(/<svelte:head>/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}\n</script>\n\n<svelte:head>`);
853
+ }
854
+ }
855
+ injectVanillaScript(content) {
856
+ if (content.includes('humanbehavior-js')) {
857
+ return content;
858
+ }
859
+ const cdnScript = `<script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"></script>`;
860
+ const initScript = `<script>
861
+ // Initialize HumanBehavior SDK
862
+ // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available
863
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}');
864
+ </script>`;
865
+ return content.replace(/<\/head>/, ` ${cdnScript}\n ${initScript}\n</head>`);
866
+ }
867
+ injectNuxtConfig(content) {
868
+ if (content.includes('humanBehaviorApiKey')) {
869
+ return content;
870
+ }
871
+ // Add runtime config by inserting it after the opening brace
872
+ return content.replace(/export default defineNuxtConfig\(\{/, `export default defineNuxtConfig({
873
+ runtimeConfig: {
874
+ public: {
875
+ humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY
876
+ }
877
+ },`);
878
+ }
879
+ /**
880
+ * Helper method to find the best environment file for a framework
881
+ */
882
+ findBestEnvFile(framework) {
883
+ const possibleEnvFiles = [
884
+ '.env.local',
885
+ '.env.development.local',
886
+ '.env.development',
887
+ '.env.local.development',
888
+ '.env',
889
+ '.env.production',
890
+ '.env.staging'
891
+ ];
892
+ // Framework-specific environment variable names
893
+ const getEnvVarName = (framework) => {
894
+ // Handle React+Vite specifically
895
+ if (framework.type === 'react' && framework.bundler === 'vite') {
896
+ return 'VITE_HUMANBEHAVIOR_API_KEY';
897
+ }
898
+ // Framework-specific mappings
899
+ const envVarNames = {
900
+ react: 'HUMANBEHAVIOR_API_KEY',
901
+ nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
902
+ vue: 'VITE_HUMANBEHAVIOR_API_KEY',
903
+ svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
904
+ angular: 'HUMANBEHAVIOR_API_KEY',
905
+ nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
906
+ remix: 'HUMANBEHAVIOR_API_KEY',
907
+ vanilla: 'HUMANBEHAVIOR_API_KEY',
908
+ node: 'HUMANBEHAVIOR_API_KEY',
909
+ auto: 'HUMANBEHAVIOR_API_KEY'
910
+ };
911
+ return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';
912
+ };
913
+ const envVarName = getEnvVarName(framework);
914
+ // Check for existing files
915
+ for (const envFile of possibleEnvFiles) {
916
+ const fullPath = path.join(this.projectRoot, envFile);
917
+ if (fs.existsSync(fullPath)) {
918
+ return { filePath: fullPath, envVarName };
919
+ }
920
+ }
921
+ // Framework-specific default file creation
922
+ const defaultFiles = {
923
+ react: '.env.local',
924
+ nextjs: '.env.local',
925
+ vue: '.env.local',
926
+ svelte: '.env',
927
+ angular: '.env',
928
+ nuxt: '.env',
929
+ remix: '.env.local',
930
+ vanilla: '.env',
931
+ node: '.env',
932
+ auto: '.env'
933
+ };
934
+ const defaultFile = defaultFiles[framework.type] || '.env';
935
+ return {
936
+ filePath: path.join(this.projectRoot, defaultFile),
937
+ envVarName
938
+ };
939
+ }
940
+ /**
941
+ * Helper method to create or append to environment files
942
+ */
943
+ createEnvironmentModification(framework) {
944
+ const { filePath, envVarName } = this.findBestEnvFile(framework);
945
+ if (fs.existsSync(filePath)) {
946
+ // Check if the variable already exists
947
+ const content = fs.readFileSync(filePath, 'utf8');
948
+ if (content.includes(envVarName)) {
949
+ // Variable exists, don't modify
950
+ return {
951
+ filePath,
952
+ action: 'modify',
953
+ content: content, // No change
954
+ description: `API key already exists in ${path.basename(filePath)}`
955
+ };
956
+ }
957
+ else {
958
+ // Append to existing file
959
+ return {
960
+ filePath,
961
+ action: 'append',
962
+ content: `\n${envVarName}=${this.apiKey}`,
963
+ description: `Added API key to existing ${path.basename(filePath)}`
964
+ };
965
+ }
966
+ }
967
+ else {
968
+ // Create new file
969
+ return {
970
+ filePath,
971
+ action: 'create',
972
+ content: `${envVarName}=${this.apiKey}`,
973
+ description: `Created ${path.basename(filePath)} with API key`
974
+ };
975
+ }
976
+ }
977
+ }
978
+
979
+ /**
980
+ * AI-Enhanced HumanBehavior SDK Auto-Installation Wizard
981
+ *
982
+ * This wizard uses AI to intelligently detect frameworks, analyze code patterns,
983
+ * and generate optimal integration code that's both future-proof and backward-compatible.
984
+ *
985
+ * 🚀 KEY FEATURES:
986
+ * - AI-powered framework detection beyond package.json
987
+ * - Intelligent code pattern analysis
988
+ * - Future-proof integration strategies
989
+ * - Backward compatibility with legacy frameworks
990
+ * - Adaptive code generation for new frameworks
991
+ * - Smart conflict resolution
992
+ * - Learning from user feedback
993
+ * - Centralized AI service (no user API keys required)
994
+ */
995
+ /**
996
+ * Default AI Service Implementation
997
+ * Uses heuristic analysis when centralized service is not available
998
+ */
999
+ class DefaultAIService {
1000
+ analyzeCodePatterns(codeSamples) {
1001
+ return __awaiter(this, void 0, void 0, function* () {
1002
+ return this.analyzeWithHeuristics(codeSamples);
1003
+ });
1004
+ }
1005
+ resolveConflicts(conflicts, framework) {
1006
+ return __awaiter(this, void 0, void 0, function* () {
1007
+ // Default conflict resolution strategies
1008
+ const resolutions = [];
1009
+ for (const conflict of conflicts) {
1010
+ switch (conflict) {
1011
+ case 'existing_humanbehavior_code':
1012
+ resolutions.push('update_existing_integration');
1013
+ break;
1014
+ case 'existing_provider':
1015
+ resolutions.push('merge_providers');
1016
+ break;
1017
+ case 'module_system_conflict':
1018
+ resolutions.push('hybrid_module_support');
1019
+ break;
1020
+ default:
1021
+ resolutions.push('skip_conflict');
1022
+ }
1023
+ }
1024
+ return resolutions;
1025
+ });
1026
+ }
1027
+ generateOptimizations(framework, patterns) {
1028
+ return __awaiter(this, void 0, void 0, function* () {
1029
+ const optimizations = [];
1030
+ // Framework-specific optimizations
1031
+ switch (framework.type) {
1032
+ case 'react':
1033
+ optimizations.push('Use React.memo for performance optimization');
1034
+ optimizations.push('Implement error boundaries for better error tracking');
1035
+ optimizations.push('Consider using React.lazy for code splitting');
1036
+ break;
1037
+ case 'vue':
1038
+ optimizations.push('Use Vue 3 Composition API for better performance');
1039
+ optimizations.push('Implement proper error handling in components');
1040
+ optimizations.push('Consider using Vue Router for navigation tracking');
1041
+ break;
1042
+ case 'angular':
1043
+ optimizations.push('Use Angular standalone components for better tree-shaking');
1044
+ optimizations.push('Implement proper error handling with ErrorHandler');
1045
+ optimizations.push('Consider using Angular signals for state management');
1046
+ break;
1047
+ default:
1048
+ optimizations.push('Enable performance tracking');
1049
+ optimizations.push('Implement error tracking');
1050
+ optimizations.push('Consider progressive enhancement');
1051
+ }
1052
+ return optimizations;
1053
+ });
1054
+ }
1055
+ analyzeWithHeuristics(codeSamples) {
1056
+ const patterns = codeSamples.join(' ').toLowerCase();
1057
+ // Framework detection
1058
+ let framework = { name: 'vanilla', type: 'vanilla' };
1059
+ let confidence = 0.5;
1060
+ 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')) {
1061
+ framework = { name: 'nuxt', type: 'nuxt' };
1062
+ confidence = 0.95;
1063
+ }
1064
+ 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/')) {
1065
+ framework = { name: 'nextjs', type: 'nextjs' };
1066
+ confidence = 0.95;
1067
+ }
1068
+ else if (patterns.includes('react')) {
1069
+ framework = { name: 'react', type: 'react' };
1070
+ confidence = 0.9;
1071
+ }
1072
+ else if (patterns.includes('vue')) {
1073
+ framework = { name: 'vue', type: 'vue' };
1074
+ confidence = 0.9;
1075
+ }
1076
+ else if (patterns.includes('angular')) {
1077
+ framework = { name: 'angular', type: 'angular' };
1078
+ confidence = 0.9;
1079
+ }
1080
+ else if (patterns.includes('svelte')) {
1081
+ framework = { name: 'svelte', type: 'svelte' };
1082
+ confidence = 0.9;
1083
+ }
1084
+ // Integration strategy
1085
+ let integrationStrategy = 'script';
1086
+ if (framework.type === 'react' || framework.type === 'nextjs') {
1087
+ integrationStrategy = 'provider';
1088
+ }
1089
+ else if (framework.type === 'vue') {
1090
+ integrationStrategy = 'plugin';
1091
+ }
1092
+ else if (framework.type === 'angular') {
1093
+ integrationStrategy = 'module';
1094
+ }
1095
+ // Compatibility mode
1096
+ let compatibilityMode = 'modern';
1097
+ if (patterns.includes('require(') || patterns.includes('var ')) {
1098
+ compatibilityMode = 'legacy';
1099
+ }
1100
+ return {
1101
+ framework,
1102
+ confidence,
1103
+ patterns: codeSamples,
1104
+ conflicts: [],
1105
+ recommendations: [],
1106
+ integrationStrategy,
1107
+ compatibilityMode
1108
+ };
1109
+ }
1110
+ }
1111
+ /**
1112
+ * Browser-based AI installation wizard
1113
+ */
1114
+ class AIBrowserInstallationWizard {
1115
+ constructor(apiKey, aiService) {
1116
+ this.apiKey = apiKey;
1117
+ this.aiService = aiService || new DefaultAIService();
1118
+ }
1119
+ install() {
1120
+ return __awaiter(this, void 0, void 0, function* () {
1121
+ try {
1122
+ // AI-powered browser detection
1123
+ const aiAnalysis = yield this.performBrowserAIAnalysis();
1124
+ // Generate AI-optimized browser modifications
1125
+ const modifications = this.generateAIBrowserModifications(aiAnalysis);
1126
+ return {
1127
+ success: true,
1128
+ framework: aiAnalysis.framework,
1129
+ modifications,
1130
+ errors: [],
1131
+ nextSteps: [
1132
+ '✅ AI-optimized browser integration ready!',
1133
+ `🎯 Framework detected: ${aiAnalysis.framework.name}`,
1134
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
1135
+ '📋 Copy the generated code to your project',
1136
+ '🚀 Your app will be ready to track user behavior'
1137
+ ],
1138
+ aiAnalysis,
1139
+ learningData: {
1140
+ patterns: aiAnalysis.patterns,
1141
+ framework: aiAnalysis.framework.name,
1142
+ success: true
1143
+ }
1144
+ };
1145
+ }
1146
+ catch (error) {
1147
+ return {
1148
+ success: false,
1149
+ framework: { name: 'unknown', type: 'vanilla' },
1150
+ modifications: [],
1151
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
1152
+ nextSteps: [],
1153
+ aiAnalysis: {
1154
+ framework: { name: 'unknown', type: 'vanilla' },
1155
+ confidence: 0,
1156
+ patterns: [],
1157
+ conflicts: [],
1158
+ recommendations: [],
1159
+ integrationStrategy: 'script',
1160
+ compatibilityMode: 'legacy'
1161
+ },
1162
+ learningData: {
1163
+ patterns: [],
1164
+ framework: 'unknown',
1165
+ success: false
1166
+ }
1167
+ };
1168
+ }
1169
+ });
1170
+ }
1171
+ performBrowserAIAnalysis() {
1172
+ return __awaiter(this, void 0, void 0, function* () {
1173
+ // Browser-based framework detection
1174
+ this.detectBrowserFramework();
1175
+ // Analyze browser environment
1176
+ const patterns = this.analyzeBrowserPatterns();
1177
+ // Use centralized AI service for analysis
1178
+ const codeSamples = [`Browser Environment: ${patterns.join(', ')}`];
1179
+ return yield this.aiService.analyzeCodePatterns(codeSamples);
1180
+ });
1181
+ }
1182
+ detectBrowserFramework() {
1183
+ if (typeof window !== 'undefined') {
1184
+ if (window.React) {
1185
+ return { name: 'react', type: 'react' };
1186
+ }
1187
+ if (window.Vue) {
1188
+ return { name: 'vue', type: 'vue' };
1189
+ }
1190
+ if (window.angular) {
1191
+ return { name: 'angular', type: 'angular' };
1192
+ }
1193
+ }
1194
+ return { name: 'vanilla', type: 'vanilla' };
1195
+ }
1196
+ analyzeBrowserPatterns() {
1197
+ const patterns = [];
1198
+ if (typeof window !== 'undefined') {
1199
+ // Analyze global objects
1200
+ if (window.React)
1201
+ patterns.push('React global detected');
1202
+ if (window.Vue)
1203
+ patterns.push('Vue global detected');
1204
+ if (window.angular)
1205
+ patterns.push('Angular global detected');
1206
+ // Analyze DOM patterns
1207
+ if (document.querySelector('[data-reactroot]'))
1208
+ patterns.push('React DOM detected');
1209
+ if (document.querySelector('[data-vue]'))
1210
+ patterns.push('Vue DOM detected');
1211
+ // Analyze script patterns
1212
+ const scripts = document.querySelectorAll('script');
1213
+ scripts.forEach(script => {
1214
+ if (script.src.includes('react'))
1215
+ patterns.push('React script detected');
1216
+ if (script.src.includes('vue'))
1217
+ patterns.push('Vue script detected');
1218
+ });
1219
+ }
1220
+ return patterns;
1221
+ }
1222
+ generateAIBrowserModifications(aiAnalysis) {
1223
+ const modifications = [];
1224
+ switch (aiAnalysis.framework.type) {
1225
+ case 'react':
1226
+ modifications.push({
1227
+ filePath: 'App.jsx',
1228
+ action: 'create',
1229
+ content: `// AI-Optimized React Integration
1230
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
1231
+
1232
+ function App() {
1233
+ return (
1234
+ <HumanBehaviorProvider
1235
+ apiKey="${this.apiKey}"
1236
+ config={{
1237
+ // AI-generated optimizations
1238
+ enablePerformanceTracking: true,
1239
+ enableErrorTracking: true,
1240
+ framework: '${aiAnalysis.framework.name}',
1241
+ integrationStrategy: '${aiAnalysis.integrationStrategy}'
1242
+ }}
1243
+ >
1244
+ {/* Your app components */}
1245
+ </HumanBehaviorProvider>
1246
+ );
1247
+ }
1248
+
1249
+ export default App;`,
1250
+ description: 'AI-optimized React component with HumanBehaviorProvider'
1251
+ });
1252
+ break;
1253
+ default:
1254
+ modifications.push({
1255
+ filePath: 'humanbehavior-init.js',
1256
+ action: 'create',
1257
+ content: `// AI-Optimized Vanilla JS Integration
1258
+ import { HumanBehaviorTracker } from 'humanbehavior-js';
1259
+
1260
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}', {
1261
+ // AI-generated configuration
1262
+ framework: '${aiAnalysis.framework.name}',
1263
+ integrationStrategy: '${aiAnalysis.integrationStrategy}',
1264
+ compatibilityMode: '${aiAnalysis.compatibilityMode}',
1265
+ enablePerformanceTracking: true,
1266
+ enableErrorTracking: true
1267
+ });`,
1268
+ description: 'AI-optimized vanilla JS initialization'
1269
+ });
1270
+ }
1271
+ return modifications;
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ * Remote AI Service Implementation
1277
+ *
1278
+ * This connects to your deployed Lambda function via API Gateway
1279
+ */
1280
+ class RemoteAIService {
1281
+ constructor(config) {
1282
+ this.config = Object.assign({ timeout: 10000 }, config);
1283
+ }
1284
+ /**
1285
+ * Analyze code patterns using your deployed AI service
1286
+ */
1287
+ analyzeCodePatterns(codeSamples) {
1288
+ return __awaiter(this, void 0, void 0, function* () {
1289
+ try {
1290
+ const response = yield fetch(`${this.config.apiEndpoint}/analyze`, {
1291
+ method: 'POST',
1292
+ headers: {
1293
+ 'Content-Type': 'application/json',
1294
+ },
1295
+ body: JSON.stringify({ codeSamples }),
1296
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
1297
+ });
1298
+ if (!response.ok) {
1299
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
1300
+ }
1301
+ const result = yield response.json();
1302
+ return result.analysis;
1303
+ }
1304
+ catch (error) {
1305
+ console.warn('Remote AI service failed, falling back to heuristic analysis:', error);
1306
+ return this.performHeuristicAnalysis(codeSamples);
1307
+ }
1308
+ });
1309
+ }
1310
+ /**
1311
+ * Resolve conflicts using your deployed AI service
1312
+ */
1313
+ resolveConflicts(conflicts, framework) {
1314
+ return __awaiter(this, void 0, void 0, function* () {
1315
+ try {
1316
+ const response = yield fetch(`${this.config.apiEndpoint}/resolve-conflicts`, {
1317
+ method: 'POST',
1318
+ headers: {
1319
+ 'Content-Type': 'application/json',
1320
+ },
1321
+ body: JSON.stringify({ conflicts, framework }),
1322
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
1323
+ });
1324
+ if (!response.ok) {
1325
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
1326
+ }
1327
+ const result = yield response.json();
1328
+ return result.resolutions || [];
1329
+ }
1330
+ catch (error) {
1331
+ console.warn('Remote AI conflict resolution failed, using heuristic approach:', error);
1332
+ return this.resolveConflictsHeuristic(conflicts, framework);
1333
+ }
1334
+ });
1335
+ }
1336
+ /**
1337
+ * Generate optimizations using your deployed AI service
1338
+ */
1339
+ generateOptimizations(framework, patterns) {
1340
+ return __awaiter(this, void 0, void 0, function* () {
1341
+ try {
1342
+ const response = yield fetch(`${this.config.apiEndpoint}/optimize`, {
1343
+ method: 'POST',
1344
+ headers: {
1345
+ 'Content-Type': 'application/json',
1346
+ },
1347
+ body: JSON.stringify({ framework, patterns }),
1348
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
1349
+ });
1350
+ if (!response.ok) {
1351
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
1352
+ }
1353
+ const result = yield response.json();
1354
+ return result.optimizations || [];
1355
+ }
1356
+ catch (error) {
1357
+ console.warn('Remote AI optimization generation failed, using heuristic approach:', error);
1358
+ return this.generateOptimizationsHeuristic(framework, patterns);
1359
+ }
1360
+ });
1361
+ }
1362
+ /**
1363
+ * Heuristic analysis fallback
1364
+ */
1365
+ performHeuristicAnalysis(codeSamples) {
1366
+ const patterns = codeSamples.join(' ').toLowerCase();
1367
+ // Framework detection
1368
+ let framework = { name: 'vanilla', type: 'vanilla' };
1369
+ let confidence = 0.5;
1370
+ 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')) {
1371
+ framework = { name: 'nuxt', type: 'nuxt' };
1372
+ confidence = 0.95;
1373
+ }
1374
+ 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/')) {
1375
+ framework = { name: 'nextjs', type: 'nextjs' };
1376
+ confidence = 0.95;
1377
+ }
1378
+ else if (patterns.includes('react')) {
1379
+ framework = { name: 'react', type: 'react' };
1380
+ confidence = 0.9;
1381
+ }
1382
+ else if (patterns.includes('vue')) {
1383
+ framework = { name: 'vue', type: 'vue' };
1384
+ confidence = 0.9;
1385
+ }
1386
+ else if (patterns.includes('angular')) {
1387
+ framework = { name: 'angular', type: 'angular' };
1388
+ confidence = 0.9;
1389
+ }
1390
+ else if (patterns.includes('svelte')) {
1391
+ framework = { name: 'svelte', type: 'svelte' };
1392
+ confidence = 0.9;
1393
+ }
1394
+ // Integration strategy
1395
+ let integrationStrategy = 'script';
1396
+ if (framework.type === 'react' || framework.type === 'nextjs') {
1397
+ integrationStrategy = 'provider';
1398
+ }
1399
+ else if (framework.type === 'vue') {
1400
+ integrationStrategy = 'plugin';
1401
+ }
1402
+ else if (framework.type === 'angular') {
1403
+ integrationStrategy = 'module';
1404
+ }
1405
+ // Compatibility mode
1406
+ let compatibilityMode = 'modern';
1407
+ if (patterns.includes('require(') || patterns.includes('var ')) {
1408
+ compatibilityMode = 'legacy';
1409
+ }
1410
+ return {
1411
+ framework,
1412
+ confidence,
1413
+ patterns: codeSamples,
1414
+ conflicts: [],
1415
+ recommendations: [],
1416
+ integrationStrategy,
1417
+ compatibilityMode
1418
+ };
1419
+ }
1420
+ /**
1421
+ * Heuristic conflict resolution
1422
+ */
1423
+ resolveConflictsHeuristic(conflicts, framework) {
1424
+ const resolutions = [];
1425
+ for (const conflict of conflicts) {
1426
+ switch (conflict) {
1427
+ case 'existing_humanbehavior_code':
1428
+ resolutions.push('update_existing_integration');
1429
+ break;
1430
+ case 'existing_provider':
1431
+ resolutions.push('merge_providers');
1432
+ break;
1433
+ case 'module_system_conflict':
1434
+ resolutions.push('hybrid_module_support');
1435
+ break;
1436
+ default:
1437
+ resolutions.push('skip_conflict');
1438
+ }
1439
+ }
1440
+ return resolutions;
1441
+ }
1442
+ /**
1443
+ * Heuristic optimization generation
1444
+ */
1445
+ generateOptimizationsHeuristic(framework, patterns) {
1446
+ const optimizations = [];
1447
+ switch (framework.type) {
1448
+ case 'react':
1449
+ optimizations.push('Use React.memo for performance optimization');
1450
+ optimizations.push('Implement error boundaries for better error tracking');
1451
+ optimizations.push('Consider using React.lazy for code splitting');
1452
+ break;
1453
+ case 'vue':
1454
+ optimizations.push('Use Vue 3 Composition API for better performance');
1455
+ optimizations.push('Implement proper error handling in components');
1456
+ optimizations.push('Consider using Vue Router for navigation tracking');
1457
+ break;
1458
+ case 'angular':
1459
+ optimizations.push('Use Angular standalone components for better tree-shaking');
1460
+ optimizations.push('Implement proper error handling with ErrorHandler');
1461
+ optimizations.push('Consider using Angular signals for state management');
1462
+ break;
1463
+ default:
1464
+ optimizations.push('Enable performance tracking');
1465
+ optimizations.push('Implement error tracking');
1466
+ optimizations.push('Consider progressive enhancement');
1467
+ }
1468
+ return optimizations;
1469
+ }
1470
+ }
1471
+
1472
+ /**
1473
+ * Manual Framework Installation Wizard
1474
+ *
1475
+ * This wizard allows users to manually specify their framework instead of auto-detection.
1476
+ * Useful when auto-detection fails or users want more control.
1477
+ */
1478
+ class ManualFrameworkInstallationWizard extends AutoInstallationWizard {
1479
+ constructor(apiKey, projectRoot = process.cwd(), framework) {
1480
+ super(apiKey, projectRoot);
1481
+ this.selectedFramework = framework.toLowerCase();
1482
+ this.framework = this.createFrameworkInfo(this.selectedFramework);
1483
+ }
1484
+ /**
1485
+ * Manual installation with user-specified framework
1486
+ */
1487
+ install() {
1488
+ return __awaiter(this, void 0, void 0, function* () {
1489
+ try {
1490
+ // Step 1: Handle framework selection
1491
+ if (this.selectedFramework === 'auto') {
1492
+ // Use full AI detection for "Other" option
1493
+ this.framework = yield this.runFullDetection();
1494
+ }
1495
+ else {
1496
+ // Set framework based on user selection
1497
+ this.framework = this.createFrameworkInfo(this.selectedFramework);
1498
+ if (!this.framework) {
1499
+ this.framework = { name: 'unknown', type: 'vanilla' };
1500
+ }
1501
+ // Step 2: Run full detection logic to find entry points, file names, etc.
1502
+ const detectedFramework = yield this.runFullDetection();
1503
+ // Step 3: Merge manual framework with detected details
1504
+ this.framework = Object.assign(Object.assign({}, detectedFramework), { name: this.framework.name, type: this.framework.type });
1505
+ }
1506
+ // Step 4: Install package
1507
+ yield this.installPackage();
1508
+ // Step 5: Generate and apply code modifications
1509
+ const modifications = yield this.generateModifications();
1510
+ yield this.applyModifications(modifications);
1511
+ // Step 6: Generate next steps
1512
+ const nextSteps = this.generateManualNextSteps();
1513
+ return {
1514
+ success: true,
1515
+ framework: this.framework,
1516
+ modifications,
1517
+ errors: [],
1518
+ nextSteps,
1519
+ selectedFramework: this.selectedFramework,
1520
+ manualMode: true
1521
+ };
1522
+ }
1523
+ catch (error) {
1524
+ return {
1525
+ success: false,
1526
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
1527
+ modifications: [],
1528
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
1529
+ nextSteps: [],
1530
+ selectedFramework: this.selectedFramework,
1531
+ manualMode: true
1532
+ };
1533
+ }
1534
+ });
1535
+ }
1536
+ /**
1537
+ * Run full detection logic to find entry points, file names, bundler, etc.
1538
+ */
1539
+ runFullDetection() {
1540
+ return __awaiter(this, void 0, void 0, function* () {
1541
+ if (this.selectedFramework === 'auto') {
1542
+ // Use AI service for auto-detection
1543
+ const aiService = new RemoteAIService({
1544
+ apiEndpoint: 'https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod'
1545
+ });
1546
+ // Use AI service directly for detection
1547
+ const projectFiles = yield this.scanProjectFiles();
1548
+ const codeSamples = yield this.extractCodeSamples(projectFiles);
1549
+ const aiAnalysis = yield aiService.analyzeCodePatterns(codeSamples);
1550
+ return aiAnalysis.framework;
1551
+ }
1552
+ else {
1553
+ // Use traditional detection for manual frameworks
1554
+ const tempWizard = new AutoInstallationWizard(this.apiKey, this.projectRoot);
1555
+ const detected = yield tempWizard.detectFramework();
1556
+ return detected;
1557
+ }
1558
+ });
1559
+ }
1560
+ /**
1561
+ * Scan project files for analysis
1562
+ */
1563
+ scanProjectFiles() {
1564
+ return __awaiter(this, void 0, void 0, function* () {
1565
+ const files = [];
1566
+ const scanDir = (dir, depth = 0) => {
1567
+ if (depth > 3)
1568
+ return; // Limit depth
1569
+ try {
1570
+ const items = fs.readdirSync(dir);
1571
+ for (const item of items) {
1572
+ const fullPath = path.join(dir, item);
1573
+ const stat = fs.statSync(fullPath);
1574
+ if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
1575
+ scanDir(fullPath, depth + 1);
1576
+ }
1577
+ else if (stat.isFile() && this.isRelevantFile(item)) {
1578
+ files.push(fullPath);
1579
+ }
1580
+ }
1581
+ }
1582
+ catch (error) {
1583
+ // Skip inaccessible directories
1584
+ }
1585
+ };
1586
+ scanDir(this.projectRoot);
1587
+ return files;
1588
+ });
1589
+ }
1590
+ /**
1591
+ * Check if file is relevant for analysis
1592
+ */
1593
+ isRelevantFile(filename) {
1594
+ const relevantExtensions = [
1595
+ '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',
1596
+ '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'
1597
+ ];
1598
+ const relevantNames = [
1599
+ 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',
1600
+ 'next.config', 'nuxt.config', 'angular.json', 'svelte.config'
1601
+ ];
1602
+ return relevantExtensions.some(ext => filename.endsWith(ext)) ||
1603
+ relevantNames.some(name => filename.includes(name));
1604
+ }
1605
+ /**
1606
+ * Extract code samples for AI analysis
1607
+ */
1608
+ extractCodeSamples(files) {
1609
+ return __awaiter(this, void 0, void 0, function* () {
1610
+ const samples = [];
1611
+ for (const file of files.slice(0, 20)) { // Limit to 20 files
1612
+ try {
1613
+ const content = fs.readFileSync(file, 'utf8');
1614
+ const relativePath = path.relative(this.projectRoot, file);
1615
+ samples.push(`File: ${relativePath}\n${content.substring(0, 1000)}`);
1616
+ }
1617
+ catch (error) {
1618
+ // Skip unreadable files
1619
+ }
1620
+ }
1621
+ return samples;
1622
+ });
1623
+ }
1624
+ /**
1625
+ * Create framework info based on user selection
1626
+ */
1627
+ createFrameworkInfo(framework) {
1628
+ const frameworkMap = {
1629
+ 'react': { name: 'react', type: 'react' },
1630
+ 'nextjs': { name: 'nextjs', type: 'nextjs' },
1631
+ 'next': { name: 'nextjs', type: 'nextjs' },
1632
+ 'vue': { name: 'vue', type: 'vue' },
1633
+ 'nuxt': { name: 'nuxt', type: 'nuxt' },
1634
+ 'nuxtjs': { name: 'nuxt', type: 'nuxt' },
1635
+ 'angular': { name: 'angular', type: 'angular' },
1636
+ 'svelte': { name: 'svelte', type: 'svelte' },
1637
+ 'sveltekit': { name: 'svelte', type: 'svelte' },
1638
+ 'remix': { name: 'remix', type: 'remix' },
1639
+ 'vanilla': { name: 'vanilla', type: 'vanilla' },
1640
+ 'node': { name: 'node', type: 'node' },
1641
+ 'auto': { name: 'auto-detected', type: 'auto' }
1642
+ };
1643
+ return frameworkMap[framework] || { name: framework, type: 'vanilla' };
1644
+ }
1645
+ /**
1646
+ * Override framework detection to use manual selection
1647
+ */
1648
+ detectFramework() {
1649
+ return __awaiter(this, void 0, void 0, function* () {
1650
+ return this.framework || { name: 'unknown', type: 'vanilla' };
1651
+ });
1652
+ }
1653
+ /**
1654
+ * Generate next steps with manual mode info
1655
+ */
1656
+ generateManualNextSteps() {
1657
+ var _a;
1658
+ return [
1659
+ '✅ Manual framework installation completed!',
1660
+ `🎯 Selected framework: ${((_a = this.framework) === null || _a === void 0 ? void 0 : _a.name) || 'unknown'}`,
1661
+ `🔧 Integration strategy: ${this.getIntegrationStrategy()}`,
1662
+ '🚀 Your app is now ready to track user behavior',
1663
+ '📊 View sessions in your HumanBehavior dashboard'
1664
+ ];
1665
+ }
1666
+ /**
1667
+ * Get integration strategy based on framework
1668
+ */
1669
+ getIntegrationStrategy() {
1670
+ var _a;
1671
+ if (!((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type))
1672
+ return 'script';
1673
+ switch (this.framework.type) {
1674
+ case 'react':
1675
+ case 'nextjs':
1676
+ return 'provider';
1677
+ case 'vue':
1678
+ return 'plugin';
1679
+ case 'angular':
1680
+ return 'module';
1681
+ default:
1682
+ return 'script';
1683
+ }
1684
+ }
1685
+ }
1686
+
1687
+ /**
1688
+ * AI-Enhanced HumanBehavior SDK Auto-Installation CLI
1689
+ *
1690
+ * Usage: npx humanbehavior-js ai-auto-install [api-key]
1691
+ *
1692
+ * This tool uses AI to intelligently detect frameworks, analyze code patterns,
1693
+ * and generate optimal integration code that's both future-proof and backward-compatible.
1694
+ */
1695
+ class AIAutoInstallCLI {
1696
+ constructor(options) {
1697
+ this.options = options;
1698
+ this.rl = readline.createInterface({
1699
+ input: process.stdin,
1700
+ output: process.stdout
1701
+ });
1702
+ }
1703
+ run() {
1704
+ return __awaiter(this, void 0, void 0, function* () {
1705
+ console.log('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');
1706
+ console.log('================================================\n');
1707
+ try {
1708
+ // Get API key
1709
+ const apiKey = yield this.getApiKey();
1710
+ if (!apiKey) {
1711
+ console.error('❌ API key is required');
1712
+ process.exit(1);
1713
+ }
1714
+ // Get project path
1715
+ const projectPath = this.options.projectPath || process.cwd();
1716
+ // Choose installation mode
1717
+ const installationMode = yield this.chooseInstallationMode();
1718
+ // Confirm installation
1719
+ if (!this.options.yes) {
1720
+ const confirmed = yield this.confirmInstallation(projectPath, installationMode);
1721
+ if (!confirmed) {
1722
+ console.log('Installation cancelled.');
1723
+ process.exit(0);
1724
+ }
1725
+ }
1726
+ // Run installation
1727
+ console.log('🔍 Analyzing your project with AI...');
1728
+ let result;
1729
+ if (this.options.browser) {
1730
+ const wizard = new AIBrowserInstallationWizard(apiKey);
1731
+ result = yield wizard.install();
1732
+ }
1733
+ else if (installationMode === 'manual') {
1734
+ // Manual AI-Enhanced framework selection
1735
+ const framework = yield this.chooseFramework();
1736
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
1737
+ result = yield wizard.install();
1738
+ }
1739
+ else if (installationMode.startsWith('manual:')) {
1740
+ // Manual framework selection with pre-selected framework
1741
+ const framework = installationMode.split(':')[1];
1742
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
1743
+ result = yield wizard.install();
1744
+ }
1745
+ else {
1746
+ const wizard = new AutoInstallationWizard(apiKey, projectPath);
1747
+ result = yield wizard.install();
1748
+ }
1749
+ // Display results
1750
+ this.displayResults(result, installationMode);
1751
+ }
1752
+ catch (error) {
1753
+ console.error('❌ Error:', error instanceof Error ? error.message : error);
1754
+ process.exit(1);
1755
+ }
1756
+ finally {
1757
+ this.rl.close();
1758
+ }
1759
+ });
1760
+ }
1761
+ getApiKey() {
1762
+ return __awaiter(this, void 0, void 0, function* () {
1763
+ if (this.options.apiKey) {
1764
+ return this.options.apiKey;
1765
+ }
1766
+ return new Promise((resolve) => {
1767
+ this.rl.question('Enter your HumanBehavior API key: ', (answer) => {
1768
+ resolve(answer.trim());
1769
+ });
1770
+ });
1771
+ });
1772
+ }
1773
+ chooseInstallationMode() {
1774
+ return __awaiter(this, void 0, void 0, function* () {
1775
+ if (this.options.manual && this.options.framework) {
1776
+ return `manual:${this.options.framework}`;
1777
+ }
1778
+ if (this.options.useAI !== undefined) {
1779
+ return this.options.useAI ? 'ai' : 'traditional';
1780
+ }
1781
+ console.log('🤖 Choose installation mode:');
1782
+ console.log('1. Manual AI-Enhanced (recommended) - Choose your framework and use AI for optimization');
1783
+ console.log('2. Traditional - Standard framework detection and installation');
1784
+ console.log('3. Browser - Browser-based AI detection and code generation\n');
1785
+ return new Promise((resolve) => {
1786
+ this.rl.question('Select mode (1-3, default: 1): ', (answer) => {
1787
+ const choice = answer.trim() || '1';
1788
+ if (choice === '1')
1789
+ resolve('manual');
1790
+ else if (choice === '2')
1791
+ resolve('traditional');
1792
+ else if (choice === '3')
1793
+ resolve('browser');
1794
+ else
1795
+ resolve('manual');
1796
+ });
1797
+ });
1798
+ });
1799
+ }
1800
+ confirmInstallation(projectPath, installationMode) {
1801
+ return __awaiter(this, void 0, void 0, function* () {
1802
+ console.log(`📁 Project path: ${projectPath}`);
1803
+ console.log(`🤖 Installation mode: ${this.getInstallationModeDisplay(installationMode)}`);
1804
+ console.log('⚠️ This will modify your codebase to integrate HumanBehavior SDK.');
1805
+ console.log(' The following changes will be made:');
1806
+ console.log(' - Install humanbehavior-js package');
1807
+ console.log(' - Analyze code patterns with AI (if enabled)');
1808
+ console.log(' - Modify your main app file');
1809
+ console.log(' - Create environment files');
1810
+ console.log(' - Add AI-optimized SDK initialization code\n');
1811
+ return new Promise((resolve) => {
1812
+ this.rl.question('Continue with installation? (y/n): ', (answer) => {
1813
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
1814
+ });
1815
+ });
1816
+ });
1817
+ }
1818
+ getInstallationModeDisplay(mode) {
1819
+ if (mode === 'manual')
1820
+ return 'Manual AI-Enhanced';
1821
+ if (mode === 'traditional')
1822
+ return 'Traditional';
1823
+ if (mode.startsWith('manual:')) {
1824
+ const framework = mode.split(':')[1];
1825
+ return `Manual AI-Enhanced (${framework})`;
1826
+ }
1827
+ if (mode === 'browser')
1828
+ return 'Browser';
1829
+ return 'Unknown';
1830
+ }
1831
+ chooseFramework() {
1832
+ return __awaiter(this, void 0, void 0, function* () {
1833
+ console.log('\n🎯 Choose your framework:');
1834
+ console.log('1. Vanilla JS (HTML)');
1835
+ console.log('2. React');
1836
+ console.log('3. Next.js');
1837
+ console.log('4. Vue');
1838
+ console.log('5. Nuxt');
1839
+ console.log('6. Angular');
1840
+ console.log('7. Svelte');
1841
+ console.log('8. Remix');
1842
+ console.log('9. Node.js');
1843
+ console.log('10. Other (Auto-detect)\n');
1844
+ return new Promise((resolve) => {
1845
+ this.rl.question('Select framework (1-10, default: 1): ', (answer) => {
1846
+ const choice = answer.trim() || '1';
1847
+ const frameworks = ['vanilla', 'react', 'nextjs', 'vue', 'nuxt', 'angular', 'svelte', 'remix', 'node', 'auto'];
1848
+ const index = parseInt(choice) - 1;
1849
+ resolve(frameworks[index] || 'vanilla');
1850
+ });
1851
+ });
1852
+ });
1853
+ }
1854
+ displayResults(result, installationMode) {
1855
+ if (result.success) {
1856
+ console.log('\n✅ Installation completed successfully!');
1857
+ if (installationMode === 'ai' && result.aiAnalysis) {
1858
+ console.log(`🎯 AI Analysis Results:`);
1859
+ console.log(` Framework: ${result.aiAnalysis.framework.name} (confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%)`);
1860
+ console.log(` Integration Strategy: ${result.aiAnalysis.integrationStrategy}`);
1861
+ console.log(` Compatibility Mode: ${result.aiAnalysis.compatibilityMode}`);
1862
+ if (result.aiAnalysis.patterns.length > 0) {
1863
+ console.log(` Detected Patterns: ${result.aiAnalysis.patterns.length} patterns`);
1864
+ }
1865
+ if (result.aiAnalysis.recommendations.length > 0) {
1866
+ console.log(` AI Recommendations:`);
1867
+ result.aiAnalysis.recommendations.forEach((rec) => {
1868
+ console.log(` • ${rec}`);
1869
+ });
1870
+ }
1871
+ }
1872
+ else {
1873
+ console.log(`📦 Framework detected: ${result.framework.name}`);
1874
+ }
1875
+ if (result.framework.bundler) {
1876
+ console.log(`🔧 Bundler: ${result.framework.bundler}`);
1877
+ }
1878
+ if (result.framework.packageManager) {
1879
+ console.log(`📋 Package Manager: ${result.framework.packageManager}`);
1880
+ }
1881
+ console.log('\n📝 Changes made:');
1882
+ result.modifications.forEach((mod) => {
1883
+ console.log(` ${mod.action === 'create' ? '➕' : '✏️'} ${mod.description}`);
1884
+ console.log(` ${mod.filePath}`);
1885
+ });
1886
+ console.log('\n🎯 Next steps:');
1887
+ result.nextSteps.forEach((step) => {
1888
+ console.log(` ${step}`);
1889
+ });
1890
+ if (installationMode === 'ai' && result.learningData) {
1891
+ console.log('\n🧠 Learning Data:');
1892
+ console.log(` Framework: ${result.learningData.framework}`);
1893
+ console.log(` Patterns: ${result.learningData.patterns.length} detected`);
1894
+ console.log(` Success: ${result.learningData.success ? 'Yes' : 'No'}`);
1895
+ }
1896
+ console.log('\n🚀 Your app is now ready to track user behavior!');
1897
+ console.log('📊 View sessions in your HumanBehavior dashboard');
1898
+ }
1899
+ else {
1900
+ console.log('\n❌ Installation failed:');
1901
+ result.errors.forEach((error) => {
1902
+ console.log(` ${error}`);
1903
+ });
1904
+ console.log('\n💡 Try running with --help for more options');
1905
+ }
1906
+ }
1907
+ }
1908
+ // CLI argument parsing
1909
+ function parseArgs() {
1910
+ const args = process.argv.slice(2);
1911
+ const options = {};
1912
+ for (let i = 0; i < args.length; i++) {
1913
+ const arg = args[i];
1914
+ if (arg === '--yes' || arg === '-y') {
1915
+ options.yes = true;
1916
+ }
1917
+ else if (arg === '--dry-run' || arg === '-d') {
1918
+ options.dryRun = true;
1919
+ }
1920
+ else if (arg === '--project' || arg === '-p') {
1921
+ options.projectPath = args[i + 1];
1922
+ i++;
1923
+ }
1924
+ else if (arg === '--traditional' || arg === '-t') {
1925
+ options.useAI = false;
1926
+ }
1927
+ else if (arg === '--browser' || arg === '-b') {
1928
+ options.browser = true;
1929
+ }
1930
+ else if (arg === '--manual' || arg === '-m') {
1931
+ options.manual = true;
1932
+ }
1933
+ else if (arg === '--framework' || arg === '-f') {
1934
+ options.framework = args[i + 1];
1935
+ i++;
1936
+ }
1937
+ else if (arg === '--help' || arg === '-h') {
1938
+ showHelp();
1939
+ process.exit(0);
1940
+ }
1941
+ else if (!options.apiKey) {
1942
+ options.apiKey = arg;
1943
+ }
1944
+ }
1945
+ return options;
1946
+ }
1947
+ function showHelp() {
1948
+ console.log(`
1949
+ AI-Enhanced HumanBehavior SDK Auto-Installation CLI
1950
+
1951
+ Usage: npx humanbehavior-js ai-auto-install [api-key] [options]
1952
+
1953
+ This tool uses AI to intelligently detect frameworks, analyze code patterns,
1954
+ and generate optimal integration code that's both future-proof and backward-compatible.
1955
+
1956
+ Arguments:
1957
+ api-key Your HumanBehavior API key
1958
+
1959
+ Options:
1960
+ -y, --yes Skip all prompts and use defaults
1961
+ -d, --dry-run Show what would be changed without making changes
1962
+ -p, --project <path> Project directory (default: current directory)
1963
+ -t, --traditional Force traditional installation mode
1964
+ -b, --browser Browser-based AI installation
1965
+ -m, --manual Manual framework selection
1966
+ -f, --framework <f> Specify framework for manual mode
1967
+ -h, --help Show this help message
1968
+
1969
+ Installation Modes:
1970
+ 1. Manual AI-Enhanced (default): Choose your framework and use AI for optimization
1971
+ 2. Traditional: Standard framework detection and installation
1972
+ 3. Browser: Browser-based AI detection and code generation
1973
+
1974
+ Examples:
1975
+ npx humanbehavior-js ai-auto-install your-api-key
1976
+ npx humanbehavior-js ai-auto-install your-api-key --manual --framework react
1977
+ npx humanbehavior-js ai-auto-install your-api-key --traditional
1978
+ npx humanbehavior-js ai-auto-install your-api-key --browser
1979
+
1980
+ Supported Frameworks:
1981
+ ✅ React (CRA, Vite, Webpack)
1982
+ ✅ Next.js (App Router, Pages Router)
1983
+ ✅ Vue (Vue CLI, Vite)
1984
+ ✅ Angular
1985
+ ✅ Svelte (SvelteKit, Vite)
1986
+ ✅ Remix
1987
+ ✅ Vanilla JS/TS
1988
+ ✅ Node.js (CommonJS & ESM)
1989
+
1990
+ AI Features:
1991
+ 🔍 Intelligent framework detection beyond package.json
1992
+ 📊 Code pattern analysis and optimization
1993
+ 🔄 Future-proof integration strategies
1994
+ 🔙 Backward compatibility with legacy frameworks
1995
+ 🧠 Learning from installation patterns
1996
+ ⚡ Adaptive code generation for new frameworks
1997
+ 🔧 Smart conflict resolution
1998
+ 📈 Performance optimization recommendations
1999
+
2000
+ The AI-enhanced tool will:
2001
+ 1. 🔍 Analyze your codebase with AI to detect patterns
2002
+ 2. 🎯 Determine optimal integration strategy
2003
+ 3. 📦 Install the humanbehavior-js package
2004
+ 4. ✏️ Generate AI-optimized integration code
2005
+ 5. 🔧 Apply modifications with conflict resolution
2006
+ 6. 🧠 Learn from the installation for future improvements
2007
+ 7. 🚀 Make your app ready to track user behavior
2008
+ `);
2009
+ }
2010
+ // Main execution
2011
+ const options = parseArgs();
2012
+ // Check if we have enough arguments (api-key is required)
2013
+ if (process.argv.length < 3 || process.argv.includes('--help') || process.argv.includes('-h')) {
2014
+ showHelp();
2015
+ process.exit(0);
2016
+ }
2017
+ const cli = new AIAutoInstallCLI(options);
2018
+ cli.run().catch((error) => {
2019
+ console.error('❌ Fatal error:', error);
2020
+ process.exit(1);
2021
+ });
2022
+
2023
+ export { AIAutoInstallCLI };
2024
+ //# sourceMappingURL=ai-auto-install.js.map