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,3208 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+ var path = require('path');
5
+ var readline = require('readline');
6
+
7
+ function _interopNamespaceDefault(e) {
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
25
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
26
+ var readline__namespace = /*#__PURE__*/_interopNamespaceDefault(readline);
27
+
28
+ /******************************************************************************
29
+ Copyright (c) Microsoft Corporation.
30
+
31
+ Permission to use, copy, modify, and/or distribute this software for any
32
+ purpose with or without fee is hereby granted.
33
+
34
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
35
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
36
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
37
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
38
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
39
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
40
+ PERFORMANCE OF THIS SOFTWARE.
41
+ ***************************************************************************** */
42
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
43
+
44
+
45
+ function __awaiter(thisArg, _arguments, P, generator) {
46
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
47
+ return new (P || (P = Promise))(function (resolve, reject) {
48
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
49
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
50
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
51
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
52
+ });
53
+ }
54
+
55
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
56
+ var e = new Error(message);
57
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
58
+ };
59
+
60
+ /**
61
+ * HumanBehavior SDK Auto-Installation Wizard
62
+ *
63
+ * This wizard automatically detects the user's framework and modifies their codebase
64
+ * to integrate the SDK with minimal user intervention.
65
+ */
66
+ class AutoInstallationWizard {
67
+ constructor(apiKey, projectRoot = process.cwd()) {
68
+ this.framework = null;
69
+ this.apiKey = apiKey;
70
+ this.projectRoot = projectRoot;
71
+ }
72
+ /**
73
+ * Main installation method - detects framework and auto-installs
74
+ */
75
+ install() {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ try {
78
+ // Step 1: Detect framework
79
+ this.framework = yield this.detectFramework();
80
+ // Step 2: Install package
81
+ yield this.installPackage();
82
+ // Step 3: Generate and apply code modifications
83
+ const modifications = yield this.generateModifications();
84
+ yield this.applyModifications(modifications);
85
+ // Step 4: Generate next steps
86
+ const nextSteps = this.generateNextSteps();
87
+ return {
88
+ success: true,
89
+ framework: this.framework,
90
+ modifications,
91
+ errors: [],
92
+ nextSteps
93
+ };
94
+ }
95
+ catch (error) {
96
+ return {
97
+ success: false,
98
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
99
+ modifications: [],
100
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
101
+ nextSteps: []
102
+ };
103
+ }
104
+ });
105
+ }
106
+ /**
107
+ * Detect the current framework and project setup
108
+ */
109
+ detectFramework() {
110
+ return __awaiter(this, void 0, void 0, function* () {
111
+ const packageJsonPath = path__namespace.join(this.projectRoot, 'package.json');
112
+ if (!fs__namespace.existsSync(packageJsonPath)) {
113
+ return {
114
+ name: 'vanilla',
115
+ type: 'vanilla',
116
+ projectRoot: this.projectRoot
117
+ };
118
+ }
119
+ const packageJson = JSON.parse(fs__namespace.readFileSync(packageJsonPath, 'utf8'));
120
+ const dependencies = Object.assign(Object.assign({}, packageJson.dependencies), packageJson.devDependencies);
121
+ // Detect framework
122
+ let framework = {
123
+ name: 'vanilla',
124
+ type: 'vanilla',
125
+ projectRoot: this.projectRoot
126
+ };
127
+ if (dependencies.nuxt) {
128
+ framework = {
129
+ name: 'nuxt',
130
+ type: 'nuxt',
131
+ hasTypeScript: !!dependencies.typescript,
132
+ hasRouter: true,
133
+ projectRoot: this.projectRoot
134
+ };
135
+ }
136
+ else if (dependencies.next) {
137
+ framework = {
138
+ name: 'nextjs',
139
+ type: 'nextjs',
140
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],
141
+ hasRouter: true,
142
+ projectRoot: this.projectRoot
143
+ };
144
+ }
145
+ else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {
146
+ framework = {
147
+ name: 'remix',
148
+ type: 'remix',
149
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
150
+ hasRouter: true,
151
+ projectRoot: this.projectRoot
152
+ };
153
+ }
154
+ else if (dependencies.react) {
155
+ framework = {
156
+ name: 'react',
157
+ type: 'react',
158
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
159
+ hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],
160
+ projectRoot: this.projectRoot
161
+ };
162
+ }
163
+ else if (dependencies.vue) {
164
+ framework = {
165
+ name: 'vue',
166
+ type: 'vue',
167
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],
168
+ hasRouter: !!dependencies['vue-router'],
169
+ projectRoot: this.projectRoot
170
+ };
171
+ }
172
+ else if (dependencies['@angular/core']) {
173
+ framework = {
174
+ name: 'angular',
175
+ type: 'angular',
176
+ hasTypeScript: true,
177
+ hasRouter: true,
178
+ projectRoot: this.projectRoot
179
+ };
180
+ }
181
+ else if (dependencies.svelte) {
182
+ framework = {
183
+ name: 'svelte',
184
+ type: 'svelte',
185
+ hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],
186
+ hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],
187
+ projectRoot: this.projectRoot
188
+ };
189
+ }
190
+ // Detect bundler
191
+ if (dependencies.vite) {
192
+ framework.bundler = 'vite';
193
+ }
194
+ else if (dependencies.webpack) {
195
+ framework.bundler = 'webpack';
196
+ }
197
+ else if (dependencies.esbuild) {
198
+ framework.bundler = 'esbuild';
199
+ }
200
+ else if (dependencies.rollup) {
201
+ framework.bundler = 'rollup';
202
+ }
203
+ // Detect package manager
204
+ if (fs__namespace.existsSync(path__namespace.join(this.projectRoot, 'yarn.lock'))) {
205
+ framework.packageManager = 'yarn';
206
+ }
207
+ else if (fs__namespace.existsSync(path__namespace.join(this.projectRoot, 'pnpm-lock.yaml'))) {
208
+ framework.packageManager = 'pnpm';
209
+ }
210
+ else {
211
+ framework.packageManager = 'npm';
212
+ }
213
+ return framework;
214
+ });
215
+ }
216
+ /**
217
+ * Install the SDK package
218
+ */
219
+ installPackage() {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ var _a, _b;
222
+ const { execSync } = yield import('child_process');
223
+ const command = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.packageManager) === 'yarn'
224
+ ? 'yarn add humanbehavior-js'
225
+ : ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.packageManager) === 'pnpm'
226
+ ? 'pnpm add humanbehavior-js'
227
+ : 'npm install humanbehavior-js';
228
+ try {
229
+ execSync(command, { cwd: this.projectRoot, stdio: 'inherit' });
230
+ }
231
+ catch (error) {
232
+ throw new Error(`Failed to install humanbehavior-js: ${error}`);
233
+ }
234
+ });
235
+ }
236
+ /**
237
+ * Generate code modifications based on framework
238
+ */
239
+ generateModifications() {
240
+ return __awaiter(this, void 0, void 0, function* () {
241
+ var _a;
242
+ const modifications = [];
243
+ switch ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type) {
244
+ case 'react':
245
+ modifications.push(...yield this.generateReactModifications());
246
+ break;
247
+ case 'nextjs':
248
+ modifications.push(...yield this.generateNextJSModifications());
249
+ break;
250
+ case 'nuxt':
251
+ modifications.push(...yield this.generateNuxtModifications());
252
+ break;
253
+ case 'remix':
254
+ modifications.push(...yield this.generateRemixModifications());
255
+ break;
256
+ case 'vue':
257
+ modifications.push(...yield this.generateVueModifications());
258
+ break;
259
+ case 'angular':
260
+ modifications.push(...yield this.generateAngularModifications());
261
+ break;
262
+ case 'svelte':
263
+ modifications.push(...yield this.generateSvelteModifications());
264
+ break;
265
+ default:
266
+ modifications.push(...yield this.generateVanillaModifications());
267
+ }
268
+ return modifications;
269
+ });
270
+ }
271
+ /**
272
+ * Generate React-specific modifications
273
+ */
274
+ generateReactModifications() {
275
+ return __awaiter(this, void 0, void 0, function* () {
276
+ const modifications = [];
277
+ // Find main App component or index file
278
+ const appFile = this.findReactAppFile();
279
+ if (appFile) {
280
+ const content = fs__namespace.readFileSync(appFile, 'utf8');
281
+ const modifiedContent = this.injectReactProvider(content, appFile);
282
+ modifications.push({
283
+ filePath: appFile,
284
+ action: 'modify',
285
+ content: modifiedContent,
286
+ description: 'Added HumanBehaviorProvider to React app'
287
+ });
288
+ }
289
+ // Create or append to environment file
290
+ modifications.push(this.createEnvironmentModification(this.framework));
291
+ return modifications;
292
+ });
293
+ }
294
+ /**
295
+ * Generate Next.js-specific modifications
296
+ */
297
+ generateNextJSModifications() {
298
+ return __awaiter(this, void 0, void 0, function* () {
299
+ const modifications = [];
300
+ // Check for App Router
301
+ const appLayoutFile = path__namespace.join(this.projectRoot, 'src', 'app', 'layout.tsx');
302
+ const pagesLayoutFile = path__namespace.join(this.projectRoot, 'src', 'pages', '_app.tsx');
303
+ if (fs__namespace.existsSync(appLayoutFile)) {
304
+ // Create providers.tsx file for App Router
305
+ modifications.push({
306
+ filePath: path__namespace.join(this.projectRoot, 'src', 'app', 'providers.tsx'),
307
+ action: 'create',
308
+ content: `'use client';
309
+
310
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
311
+
312
+ export function Providers({ children }: { children: React.ReactNode }) {
313
+ return (
314
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
315
+ {children}
316
+ </HumanBehaviorProvider>
317
+ );
318
+ }`,
319
+ description: 'Created providers.tsx file for Next.js App Router'
320
+ });
321
+ // Modify layout.tsx to use the provider
322
+ const content = fs__namespace.readFileSync(appLayoutFile, 'utf8');
323
+ const modifiedContent = this.injectNextJSAppRouter(content);
324
+ modifications.push({
325
+ filePath: appLayoutFile,
326
+ action: 'modify',
327
+ content: modifiedContent,
328
+ description: 'Added Providers wrapper to Next.js App Router layout'
329
+ });
330
+ }
331
+ else if (fs__namespace.existsSync(pagesLayoutFile)) {
332
+ // Create providers.tsx file for Pages Router
333
+ modifications.push({
334
+ filePath: path__namespace.join(this.projectRoot, 'src', 'components', 'providers.tsx'),
335
+ action: 'create',
336
+ content: `'use client';
337
+
338
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
339
+
340
+ export function Providers({ children }: { children: React.ReactNode }) {
341
+ return (
342
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
343
+ {children}
344
+ </HumanBehaviorProvider>
345
+ );
346
+ }`,
347
+ description: 'Created providers.tsx file for Pages Router'
348
+ });
349
+ // Modify _app.tsx to use the provider
350
+ const content = fs__namespace.readFileSync(pagesLayoutFile, 'utf8');
351
+ const modifiedContent = this.injectNextJSPagesRouter(content);
352
+ modifications.push({
353
+ filePath: pagesLayoutFile,
354
+ action: 'modify',
355
+ content: modifiedContent,
356
+ description: 'Added Providers wrapper to Next.js Pages Router'
357
+ });
358
+ }
359
+ // Create or append to environment file
360
+ modifications.push(this.createEnvironmentModification(this.framework));
361
+ return modifications;
362
+ });
363
+ }
364
+ /**
365
+ * Generate Nuxt-specific modifications
366
+ */
367
+ generateNuxtModifications() {
368
+ return __awaiter(this, void 0, void 0, function* () {
369
+ const modifications = [];
370
+ // Create plugin file for Nuxt (in app directory)
371
+ const pluginFile = path__namespace.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');
372
+ modifications.push({
373
+ filePath: pluginFile,
374
+ action: 'create',
375
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
376
+
377
+ export default defineNuxtPlugin(() => {
378
+ const config = useRuntimeConfig();
379
+
380
+ // Initialize HumanBehavior SDK (client-side only)
381
+ if (typeof window !== 'undefined') {
382
+ const apiKey = config.public.humanBehaviorApiKey;
383
+ console.log('HumanBehavior: API key:', apiKey ? 'present' : 'missing');
384
+
385
+ if (apiKey) {
386
+ try {
387
+ const tracker = HumanBehaviorTracker.init(apiKey);
388
+ console.log('HumanBehavior: Tracker initialized successfully');
389
+ } catch (error) {
390
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
391
+ }
392
+ } else {
393
+ console.error('HumanBehavior: No API key found in runtime config');
394
+ }
395
+ }
396
+ });`,
397
+ description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'
398
+ });
399
+ // Create environment configuration
400
+ const nuxtConfigFile = path__namespace.join(this.projectRoot, 'nuxt.config.ts');
401
+ if (fs__namespace.existsSync(nuxtConfigFile)) {
402
+ const content = fs__namespace.readFileSync(nuxtConfigFile, 'utf8');
403
+ const modifiedContent = this.injectNuxtConfig(content);
404
+ modifications.push({
405
+ filePath: nuxtConfigFile,
406
+ action: 'modify',
407
+ content: modifiedContent,
408
+ description: 'Added HumanBehavior runtime config to Nuxt config'
409
+ });
410
+ }
411
+ // Create or append to environment file
412
+ modifications.push(this.createEnvironmentModification(this.framework));
413
+ return modifications;
414
+ });
415
+ }
416
+ /**
417
+ * Generate Remix-specific modifications
418
+ */
419
+ generateRemixModifications() {
420
+ return __awaiter(this, void 0, void 0, function* () {
421
+ const modifications = [];
422
+ // Find root.tsx file
423
+ const rootFile = path__namespace.join(this.projectRoot, 'app', 'root.tsx');
424
+ if (fs__namespace.existsSync(rootFile)) {
425
+ const content = fs__namespace.readFileSync(rootFile, 'utf8');
426
+ const modifiedContent = this.injectRemixProvider(content);
427
+ modifications.push({
428
+ filePath: rootFile,
429
+ action: 'modify',
430
+ content: modifiedContent,
431
+ description: 'Added HumanBehaviorProvider to Remix root component'
432
+ });
433
+ }
434
+ // Create or append to environment file
435
+ modifications.push(this.createEnvironmentModification(this.framework));
436
+ return modifications;
437
+ });
438
+ }
439
+ /**
440
+ * Generate Vue-specific modifications
441
+ */
442
+ generateVueModifications() {
443
+ return __awaiter(this, void 0, void 0, function* () {
444
+ const modifications = [];
445
+ // Find main.js or main.ts
446
+ const mainFile = this.findVueMainFile();
447
+ if (mainFile) {
448
+ const content = fs__namespace.readFileSync(mainFile, 'utf8');
449
+ const modifiedContent = this.injectVuePlugin(content);
450
+ modifications.push({
451
+ filePath: mainFile,
452
+ action: 'modify',
453
+ content: modifiedContent,
454
+ description: 'Added HumanBehaviorPlugin to Vue app'
455
+ });
456
+ }
457
+ // Create or append to environment file
458
+ modifications.push(this.createEnvironmentModification(this.framework));
459
+ return modifications;
460
+ });
461
+ }
462
+ /**
463
+ * Generate Angular-specific modifications
464
+ */
465
+ generateAngularModifications() {
466
+ return __awaiter(this, void 0, void 0, function* () {
467
+ const modifications = [];
468
+ // Check for modern Angular (standalone components) vs legacy (NgModule)
469
+ const appModuleFile = path__namespace.join(this.projectRoot, 'src', 'app', 'app.module.ts');
470
+ const appComponentFile = path__namespace.join(this.projectRoot, 'src', 'app', 'app.ts');
471
+ const mainFile = path__namespace.join(this.projectRoot, 'src', 'main.ts');
472
+ const isModernAngular = fs__namespace.existsSync(appComponentFile) && !fs__namespace.existsSync(appModuleFile);
473
+ if (isModernAngular) {
474
+ // Modern Angular 17+ with standalone components
475
+ if (fs__namespace.existsSync(mainFile)) {
476
+ const content = fs__namespace.readFileSync(mainFile, 'utf8');
477
+ const modifiedContent = this.injectAngularStandaloneInit(content);
478
+ modifications.push({
479
+ filePath: mainFile,
480
+ action: 'modify',
481
+ content: modifiedContent,
482
+ description: 'Added HumanBehavior initialization to Angular main.ts'
483
+ });
484
+ }
485
+ }
486
+ else if (fs__namespace.existsSync(appModuleFile)) {
487
+ // Legacy Angular with NgModule
488
+ const content = fs__namespace.readFileSync(appModuleFile, 'utf8');
489
+ const modifiedContent = this.injectAngularModule(content);
490
+ modifications.push({
491
+ filePath: appModuleFile,
492
+ action: 'modify',
493
+ content: modifiedContent,
494
+ description: 'Added HumanBehaviorModule to Angular app'
495
+ });
496
+ }
497
+ // Handle Angular environment file (legacy structure)
498
+ const envFile = path__namespace.join(this.projectRoot, 'src', 'environments', 'environment.ts');
499
+ if (fs__namespace.existsSync(envFile)) {
500
+ const content = fs__namespace.readFileSync(envFile, 'utf8');
501
+ if (!content.includes('humanBehaviorApiKey')) {
502
+ const modifiedContent = content.replace(/export const environment = {([\s\S]*?)};/, `export const environment = {
503
+ $1,
504
+ humanBehaviorApiKey: process.env['HUMANBEHAVIOR_API_KEY'] || ''
505
+ };`);
506
+ modifications.push({
507
+ filePath: envFile,
508
+ action: 'modify',
509
+ content: modifiedContent,
510
+ description: 'Added API key to Angular environment'
511
+ });
512
+ }
513
+ }
514
+ // Create or append to environment file
515
+ modifications.push(this.createEnvironmentModification(this.framework));
516
+ return modifications;
517
+ });
518
+ }
519
+ /**
520
+ * Generate Svelte-specific modifications
521
+ */
522
+ generateSvelteModifications() {
523
+ return __awaiter(this, void 0, void 0, function* () {
524
+ const modifications = [];
525
+ // Check for SvelteKit
526
+ const svelteConfigFile = path__namespace.join(this.projectRoot, 'svelte.config.js');
527
+ const isSvelteKit = fs__namespace.existsSync(svelteConfigFile);
528
+ if (isSvelteKit) {
529
+ // SvelteKit - create layout file
530
+ const layoutFile = path__namespace.join(this.projectRoot, 'src', 'routes', '+layout.svelte');
531
+ if (fs__namespace.existsSync(layoutFile)) {
532
+ const content = fs__namespace.readFileSync(layoutFile, 'utf8');
533
+ const modifiedContent = this.injectSvelteKitLayout(content);
534
+ modifications.push({
535
+ filePath: layoutFile,
536
+ action: 'modify',
537
+ content: modifiedContent,
538
+ description: 'Added HumanBehavior store to SvelteKit layout'
539
+ });
540
+ }
541
+ }
542
+ else {
543
+ // Regular Svelte - modify main file
544
+ const mainFile = this.findSvelteMainFile();
545
+ if (mainFile) {
546
+ const content = fs__namespace.readFileSync(mainFile, 'utf8');
547
+ const modifiedContent = this.injectSvelteStore(content);
548
+ modifications.push({
549
+ filePath: mainFile,
550
+ action: 'modify',
551
+ content: modifiedContent,
552
+ description: 'Added HumanBehavior store to Svelte app'
553
+ });
554
+ }
555
+ }
556
+ // Create or append to environment file
557
+ modifications.push(this.createEnvironmentModification(this.framework));
558
+ return modifications;
559
+ });
560
+ }
561
+ /**
562
+ * Generate vanilla JS/TS modifications
563
+ */
564
+ generateVanillaModifications() {
565
+ return __awaiter(this, void 0, void 0, function* () {
566
+ const modifications = [];
567
+ // Find HTML file to inject script
568
+ const htmlFile = this.findHTMLFile();
569
+ if (htmlFile) {
570
+ const content = fs__namespace.readFileSync(htmlFile, 'utf8');
571
+ const modifiedContent = this.injectVanillaScript(content);
572
+ modifications.push({
573
+ filePath: htmlFile,
574
+ action: 'modify',
575
+ content: modifiedContent,
576
+ description: 'Added HumanBehavior CDN script to HTML file'
577
+ });
578
+ }
579
+ // Create or append to environment file
580
+ modifications.push(this.createEnvironmentModification(this.framework));
581
+ return modifications;
582
+ });
583
+ }
584
+ /**
585
+ * Apply modifications to the codebase
586
+ */
587
+ applyModifications(modifications) {
588
+ return __awaiter(this, void 0, void 0, function* () {
589
+ for (const modification of modifications) {
590
+ try {
591
+ const dir = path__namespace.dirname(modification.filePath);
592
+ if (!fs__namespace.existsSync(dir)) {
593
+ fs__namespace.mkdirSync(dir, { recursive: true });
594
+ }
595
+ switch (modification.action) {
596
+ case 'create':
597
+ fs__namespace.writeFileSync(modification.filePath, modification.content);
598
+ break;
599
+ case 'modify':
600
+ fs__namespace.writeFileSync(modification.filePath, modification.content);
601
+ break;
602
+ case 'append':
603
+ fs__namespace.appendFileSync(modification.filePath, '\n' + modification.content);
604
+ break;
605
+ }
606
+ }
607
+ catch (error) {
608
+ throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);
609
+ }
610
+ }
611
+ });
612
+ }
613
+ /**
614
+ * Generate next steps for the user
615
+ */
616
+ generateNextSteps() {
617
+ var _a, _b;
618
+ const steps = [
619
+ '✅ SDK installed and configured automatically!',
620
+ '🚀 Your app is now tracking user behavior',
621
+ '📊 View sessions in your HumanBehavior dashboard',
622
+ '🔧 Customize tracking in your code as needed'
623
+ ];
624
+ 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') {
625
+ steps.push('💡 Use the useHumanBehavior() hook to track custom events');
626
+ }
627
+ return steps;
628
+ }
629
+ // Helper methods for file detection and content injection
630
+ findReactAppFile() {
631
+ const possibleFiles = [
632
+ 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',
633
+ 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'
634
+ ];
635
+ for (const file of possibleFiles) {
636
+ const fullPath = path__namespace.join(this.projectRoot, file);
637
+ if (fs__namespace.existsSync(fullPath)) {
638
+ return fullPath;
639
+ }
640
+ }
641
+ return null;
642
+ }
643
+ findVueMainFile() {
644
+ const possibleFiles = [
645
+ 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'
646
+ ];
647
+ for (const file of possibleFiles) {
648
+ const fullPath = path__namespace.join(this.projectRoot, file);
649
+ if (fs__namespace.existsSync(fullPath)) {
650
+ return fullPath;
651
+ }
652
+ }
653
+ return null;
654
+ }
655
+ findSvelteMainFile() {
656
+ const possibleFiles = [
657
+ 'src/main.js', 'src/main.ts', 'src/main.svelte'
658
+ ];
659
+ for (const file of possibleFiles) {
660
+ const fullPath = path__namespace.join(this.projectRoot, file);
661
+ if (fs__namespace.existsSync(fullPath)) {
662
+ return fullPath;
663
+ }
664
+ }
665
+ return null;
666
+ }
667
+ findHTMLFile() {
668
+ const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];
669
+ for (const file of possibleFiles) {
670
+ const fullPath = path__namespace.join(this.projectRoot, file);
671
+ if (fs__namespace.existsSync(fullPath)) {
672
+ return fullPath;
673
+ }
674
+ }
675
+ return null;
676
+ }
677
+ injectReactProvider(content, filePath) {
678
+ var _a;
679
+ filePath.endsWith('.tsx') || filePath.endsWith('.ts');
680
+ // Check if already has HumanBehaviorProvider
681
+ if (content.includes('HumanBehaviorProvider')) {
682
+ return content;
683
+ }
684
+ // Determine the correct environment variable syntax based on bundler
685
+ const isVite = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.bundler) === 'vite';
686
+ const envVar = isVite
687
+ ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!'
688
+ : 'process.env.HUMANBEHAVIOR_API_KEY!';
689
+ const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;
690
+ // Simple injection - in production, you'd want more sophisticated parsing
691
+ if (content.includes('function App()') || content.includes('const App =')) {
692
+ return content.replace(/(function App\(\)|const App =)/, `${importStatement}\n\n$1`).replace(/return \(([\s\S]*?)\);/, `return (
693
+ <HumanBehaviorProvider apiKey={${envVar}}>
694
+ $1
695
+ </HumanBehaviorProvider>
696
+ );`);
697
+ }
698
+ return `${importStatement}\n\n${content}`;
699
+ }
700
+ injectNextJSAppRouter(content) {
701
+ if (content.includes('Providers')) {
702
+ return content;
703
+ }
704
+ const importStatement = `import { Providers } from './providers';`;
705
+ // First, add the import statement
706
+ let modifiedContent = content.replace(/export default function RootLayout/, `${importStatement}\n\nexport default function RootLayout`);
707
+ // Then wrap the body content with Providers
708
+ // Use a more specific approach to handle the body content
709
+ modifiedContent = modifiedContent.replace(/<body([^>]*)>([\s\S]*?)<\/body>/, (match, bodyAttrs, bodyContent) => {
710
+ // Trim whitespace and newlines from bodyContent
711
+ const trimmedContent = bodyContent.trim();
712
+ return `<body${bodyAttrs}>
713
+ <Providers>
714
+ ${trimmedContent}
715
+ </Providers>
716
+ </body>`;
717
+ });
718
+ return modifiedContent;
719
+ }
720
+ injectNextJSPagesRouter(content) {
721
+ if (content.includes('Providers')) {
722
+ return content;
723
+ }
724
+ const importStatement = `import { Providers } from '../components/providers';`;
725
+ return content.replace(/function MyApp/, `${importStatement}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/, `return (
726
+ <Providers>
727
+ $1
728
+ </Providers>
729
+ );`);
730
+ }
731
+ injectRemixProvider(content) {
732
+ if (content.includes('HumanBehaviorProvider')) {
733
+ return content;
734
+ }
735
+ const importStatement = `import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';`;
736
+ const useLoaderDataImport = `import { useLoaderData } from "@remix-run/react";`;
737
+ // Add imports more robustly
738
+ let modifiedContent = content;
739
+ // Add HumanBehaviorProvider import - find the last import and add after it
740
+ if (!content.includes('HumanBehaviorProvider')) {
741
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
742
+ if (lastImportIndex !== -1) {
743
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
744
+ if (nextLineIndex !== -1) {
745
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
746
+ importStatement + '\n' +
747
+ modifiedContent.slice(nextLineIndex + 1);
748
+ }
749
+ else {
750
+ modifiedContent = modifiedContent + '\n' + importStatement;
751
+ }
752
+ }
753
+ else {
754
+ modifiedContent = importStatement + '\n' + modifiedContent;
755
+ }
756
+ }
757
+ // Add useLoaderData import - find the last import and add after it
758
+ if (!content.includes('useLoaderData')) {
759
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
760
+ if (lastImportIndex !== -1) {
761
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
762
+ if (nextLineIndex !== -1) {
763
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
764
+ useLoaderDataImport + '\n' +
765
+ modifiedContent.slice(nextLineIndex + 1);
766
+ }
767
+ else {
768
+ modifiedContent = modifiedContent + '\n' + useLoaderDataImport;
769
+ }
770
+ }
771
+ else {
772
+ modifiedContent = useLoaderDataImport + '\n' + modifiedContent;
773
+ }
774
+ }
775
+ // Add loader function before the App component
776
+ if (!content.includes('export const loader')) {
777
+ modifiedContent = modifiedContent.replace(/export default function App\(\)/, `export const loader = createHumanBehaviorLoader();
778
+
779
+ export default function App()`);
780
+ }
781
+ // Wrap the App component content with HumanBehaviorProvider
782
+ modifiedContent = modifiedContent.replace(/export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/, `export default function App() {
783
+ const data = useLoaderData<typeof loader>();
784
+
785
+ return (
786
+ <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
787
+ $1
788
+ </HumanBehaviorProvider>
789
+ );
790
+ }`);
791
+ return modifiedContent;
792
+ }
793
+ injectVuePlugin(content) {
794
+ if (content.includes('HumanBehaviorPlugin')) {
795
+ return content;
796
+ }
797
+ const importStatement = `import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';`;
798
+ const pluginUsage = `app.use(HumanBehaviorPlugin, {
799
+ apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY
800
+ });`;
801
+ // Handle both Vue 2 and Vue 3 patterns
802
+ if (content.includes('createApp')) {
803
+ // Vue 3
804
+ return content.replace(/import.*from.*['"]vue['"]/, `$&\n${importStatement}`).replace(/app\.mount\(/, `${pluginUsage}\n\napp.mount(`);
805
+ }
806
+ else {
807
+ // Vue 2
808
+ return content.replace(/import.*from.*['"]vue['"]/, `$&\n${importStatement}`).replace(/new Vue\(/, `${pluginUsage}\n\nnew Vue(`);
809
+ }
810
+ }
811
+ injectAngularModule(content) {
812
+ if (content.includes('HumanBehaviorModule')) {
813
+ return content;
814
+ }
815
+ const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;
816
+ const environmentImport = `import { environment } from '../environments/environment';`;
817
+ // Add environment import if not present
818
+ let modifiedContent = content;
819
+ if (!content.includes('environment')) {
820
+ modifiedContent = content.replace(/import.*from.*['"]@angular/, `${environmentImport}\n$&`);
821
+ }
822
+ return modifiedContent.replace(/imports:\s*\[([\s\S]*?)\]/, `imports: [
823
+ $1,
824
+ HumanBehaviorModule.forRoot({
825
+ apiKey: environment.humanBehaviorApiKey
826
+ })
827
+ ]`).replace(/import.*from.*['"]@angular/, `$&\n${importStatement}`);
828
+ }
829
+ injectAngularStandaloneInit(content) {
830
+ if (content.includes('initializeHumanBehavior')) {
831
+ return content;
832
+ }
833
+ const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;
834
+ // Add import at the top
835
+ let modifiedContent = content.replace(/import.*from.*['"]@angular/, `${importStatement}\n$&`);
836
+ // Add initialization after bootstrapApplication
837
+ modifiedContent = modifiedContent.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/, `$1
838
+
839
+ // Initialize HumanBehavior SDK (client-side only)
840
+ if (typeof window !== 'undefined') {
841
+ const tracker = initializeHumanBehavior(
842
+ '${this.apiKey}'
843
+ );
844
+ }`);
845
+ return modifiedContent;
846
+ }
847
+ injectSvelteStore(content) {
848
+ if (content.includes('humanBehaviorStore')) {
849
+ return content;
850
+ }
851
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
852
+ const initCode = `humanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
853
+ return `${importStatement}\n${initCode}\n\n${content}`;
854
+ }
855
+ injectSvelteKitLayout(content) {
856
+ if (content.includes('humanBehaviorStore')) {
857
+ return content;
858
+ }
859
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
860
+ const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;
861
+ const initCode = `humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
862
+ // Add to script section - handle different script tag patterns
863
+ if (content.includes('<script lang="ts">')) {
864
+ return content.replace(/<script lang="ts">/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
865
+ }
866
+ else if (content.includes('<script>')) {
867
+ return content.replace(/<script>/, `<script>\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
868
+ }
869
+ else if (content.includes('<script context="module">')) {
870
+ return content.replace(/<script\s+context="module">/, `<script context="module">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
871
+ }
872
+ else {
873
+ // If no script tag found, add one at the beginning
874
+ return content.replace(/<svelte:head>/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}\n</script>\n\n<svelte:head>`);
875
+ }
876
+ }
877
+ injectVanillaScript(content) {
878
+ if (content.includes('humanbehavior-js')) {
879
+ return content;
880
+ }
881
+ const cdnScript = `<script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"></script>`;
882
+ const initScript = `<script>
883
+ // Initialize HumanBehavior SDK
884
+ // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available
885
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}');
886
+ </script>`;
887
+ return content.replace(/<\/head>/, ` ${cdnScript}\n ${initScript}\n</head>`);
888
+ }
889
+ injectNuxtConfig(content) {
890
+ if (content.includes('humanBehaviorApiKey')) {
891
+ return content;
892
+ }
893
+ // Add runtime config by inserting it after the opening brace
894
+ return content.replace(/export default defineNuxtConfig\(\{/, `export default defineNuxtConfig({
895
+ runtimeConfig: {
896
+ public: {
897
+ humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY
898
+ }
899
+ },`);
900
+ }
901
+ /**
902
+ * Helper method to find the best environment file for a framework
903
+ */
904
+ findBestEnvFile(framework) {
905
+ const possibleEnvFiles = [
906
+ '.env.local',
907
+ '.env.development.local',
908
+ '.env.development',
909
+ '.env.local.development',
910
+ '.env',
911
+ '.env.production',
912
+ '.env.staging'
913
+ ];
914
+ // Framework-specific environment variable names
915
+ const getEnvVarName = (framework) => {
916
+ // Handle React+Vite specifically
917
+ if (framework.type === 'react' && framework.bundler === 'vite') {
918
+ return 'VITE_HUMANBEHAVIOR_API_KEY';
919
+ }
920
+ // Framework-specific mappings
921
+ const envVarNames = {
922
+ react: 'HUMANBEHAVIOR_API_KEY',
923
+ nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
924
+ vue: 'VITE_HUMANBEHAVIOR_API_KEY',
925
+ svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
926
+ angular: 'HUMANBEHAVIOR_API_KEY',
927
+ nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
928
+ remix: 'HUMANBEHAVIOR_API_KEY',
929
+ vanilla: 'HUMANBEHAVIOR_API_KEY',
930
+ node: 'HUMANBEHAVIOR_API_KEY',
931
+ auto: 'HUMANBEHAVIOR_API_KEY'
932
+ };
933
+ return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';
934
+ };
935
+ const envVarName = getEnvVarName(framework);
936
+ // Check for existing files
937
+ for (const envFile of possibleEnvFiles) {
938
+ const fullPath = path__namespace.join(this.projectRoot, envFile);
939
+ if (fs__namespace.existsSync(fullPath)) {
940
+ return { filePath: fullPath, envVarName };
941
+ }
942
+ }
943
+ // Framework-specific default file creation
944
+ const defaultFiles = {
945
+ react: '.env.local',
946
+ nextjs: '.env.local',
947
+ vue: '.env.local',
948
+ svelte: '.env',
949
+ angular: '.env',
950
+ nuxt: '.env',
951
+ remix: '.env.local',
952
+ vanilla: '.env',
953
+ node: '.env',
954
+ auto: '.env'
955
+ };
956
+ const defaultFile = defaultFiles[framework.type] || '.env';
957
+ return {
958
+ filePath: path__namespace.join(this.projectRoot, defaultFile),
959
+ envVarName
960
+ };
961
+ }
962
+ /**
963
+ * Helper method to create or append to environment files
964
+ */
965
+ createEnvironmentModification(framework) {
966
+ const { filePath, envVarName } = this.findBestEnvFile(framework);
967
+ if (fs__namespace.existsSync(filePath)) {
968
+ // Check if the variable already exists
969
+ const content = fs__namespace.readFileSync(filePath, 'utf8');
970
+ if (content.includes(envVarName)) {
971
+ // Variable exists, don't modify
972
+ return {
973
+ filePath,
974
+ action: 'modify',
975
+ content: content, // No change
976
+ description: `API key already exists in ${path__namespace.basename(filePath)}`
977
+ };
978
+ }
979
+ else {
980
+ // Append to existing file
981
+ return {
982
+ filePath,
983
+ action: 'append',
984
+ content: `\n${envVarName}=${this.apiKey}`,
985
+ description: `Added API key to existing ${path__namespace.basename(filePath)}`
986
+ };
987
+ }
988
+ }
989
+ else {
990
+ // Create new file
991
+ return {
992
+ filePath,
993
+ action: 'create',
994
+ content: `${envVarName}=${this.apiKey}`,
995
+ description: `Created ${path__namespace.basename(filePath)} with API key`
996
+ };
997
+ }
998
+ }
999
+ }
1000
+
1001
+ /**
1002
+ * AI-Enhanced HumanBehavior SDK Auto-Installation Wizard
1003
+ *
1004
+ * This wizard uses AI to intelligently detect frameworks, analyze code patterns,
1005
+ * and generate optimal integration code that's both future-proof and backward-compatible.
1006
+ *
1007
+ * 🚀 KEY FEATURES:
1008
+ * - AI-powered framework detection beyond package.json
1009
+ * - Intelligent code pattern analysis
1010
+ * - Future-proof integration strategies
1011
+ * - Backward compatibility with legacy frameworks
1012
+ * - Adaptive code generation for new frameworks
1013
+ * - Smart conflict resolution
1014
+ * - Learning from user feedback
1015
+ * - Centralized AI service (no user API keys required)
1016
+ */
1017
+ /**
1018
+ * Default AI Service Implementation
1019
+ * Uses heuristic analysis when centralized service is not available
1020
+ */
1021
+ class DefaultAIService {
1022
+ analyzeCodePatterns(codeSamples) {
1023
+ return __awaiter(this, void 0, void 0, function* () {
1024
+ return this.analyzeWithHeuristics(codeSamples);
1025
+ });
1026
+ }
1027
+ resolveConflicts(conflicts, framework) {
1028
+ return __awaiter(this, void 0, void 0, function* () {
1029
+ // Default conflict resolution strategies
1030
+ const resolutions = [];
1031
+ for (const conflict of conflicts) {
1032
+ switch (conflict) {
1033
+ case 'existing_humanbehavior_code':
1034
+ resolutions.push('update_existing_integration');
1035
+ break;
1036
+ case 'existing_provider':
1037
+ resolutions.push('merge_providers');
1038
+ break;
1039
+ case 'module_system_conflict':
1040
+ resolutions.push('hybrid_module_support');
1041
+ break;
1042
+ default:
1043
+ resolutions.push('skip_conflict');
1044
+ }
1045
+ }
1046
+ return resolutions;
1047
+ });
1048
+ }
1049
+ generateOptimizations(framework, patterns) {
1050
+ return __awaiter(this, void 0, void 0, function* () {
1051
+ const optimizations = [];
1052
+ // Framework-specific optimizations
1053
+ switch (framework.type) {
1054
+ case 'react':
1055
+ optimizations.push('Use React.memo for performance optimization');
1056
+ optimizations.push('Implement error boundaries for better error tracking');
1057
+ optimizations.push('Consider using React.lazy for code splitting');
1058
+ break;
1059
+ case 'vue':
1060
+ optimizations.push('Use Vue 3 Composition API for better performance');
1061
+ optimizations.push('Implement proper error handling in components');
1062
+ optimizations.push('Consider using Vue Router for navigation tracking');
1063
+ break;
1064
+ case 'angular':
1065
+ optimizations.push('Use Angular standalone components for better tree-shaking');
1066
+ optimizations.push('Implement proper error handling with ErrorHandler');
1067
+ optimizations.push('Consider using Angular signals for state management');
1068
+ break;
1069
+ default:
1070
+ optimizations.push('Enable performance tracking');
1071
+ optimizations.push('Implement error tracking');
1072
+ optimizations.push('Consider progressive enhancement');
1073
+ }
1074
+ return optimizations;
1075
+ });
1076
+ }
1077
+ analyzeWithHeuristics(codeSamples) {
1078
+ const patterns = codeSamples.join(' ').toLowerCase();
1079
+ // Framework detection
1080
+ let framework = { name: 'vanilla', type: 'vanilla' };
1081
+ let confidence = 0.5;
1082
+ 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')) {
1083
+ framework = { name: 'nuxt', type: 'nuxt' };
1084
+ confidence = 0.95;
1085
+ }
1086
+ 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/')) {
1087
+ framework = { name: 'nextjs', type: 'nextjs' };
1088
+ confidence = 0.95;
1089
+ }
1090
+ else if (patterns.includes('react')) {
1091
+ framework = { name: 'react', type: 'react' };
1092
+ confidence = 0.9;
1093
+ }
1094
+ else if (patterns.includes('vue')) {
1095
+ framework = { name: 'vue', type: 'vue' };
1096
+ confidence = 0.9;
1097
+ }
1098
+ else if (patterns.includes('angular')) {
1099
+ framework = { name: 'angular', type: 'angular' };
1100
+ confidence = 0.9;
1101
+ }
1102
+ else if (patterns.includes('svelte')) {
1103
+ framework = { name: 'svelte', type: 'svelte' };
1104
+ confidence = 0.9;
1105
+ }
1106
+ // Integration strategy
1107
+ let integrationStrategy = 'script';
1108
+ if (framework.type === 'react' || framework.type === 'nextjs') {
1109
+ integrationStrategy = 'provider';
1110
+ }
1111
+ else if (framework.type === 'vue') {
1112
+ integrationStrategy = 'plugin';
1113
+ }
1114
+ else if (framework.type === 'angular') {
1115
+ integrationStrategy = 'module';
1116
+ }
1117
+ // Compatibility mode
1118
+ let compatibilityMode = 'modern';
1119
+ if (patterns.includes('require(') || patterns.includes('var ')) {
1120
+ compatibilityMode = 'legacy';
1121
+ }
1122
+ return {
1123
+ framework,
1124
+ confidence,
1125
+ patterns: codeSamples,
1126
+ conflicts: [],
1127
+ recommendations: [],
1128
+ integrationStrategy,
1129
+ compatibilityMode
1130
+ };
1131
+ }
1132
+ }
1133
+ class AIEnhancedInstallationWizard extends AutoInstallationWizard {
1134
+ constructor(apiKey, projectRoot = process.cwd(), aiService) {
1135
+ super(apiKey, projectRoot);
1136
+ this.learningCache = new Map();
1137
+ this.patternDatabase = new Map();
1138
+ this.aiService = aiService || new DefaultAIService();
1139
+ this.loadLearningData();
1140
+ }
1141
+ /**
1142
+ * AI-enhanced installation with intelligent analysis
1143
+ */
1144
+ install() {
1145
+ return __awaiter(this, void 0, void 0, function* () {
1146
+ try {
1147
+ // Step 1: AI-powered framework detection
1148
+ const aiAnalysis = yield this.performAICodeAnalysis();
1149
+ // Step 2: Smart framework detection with AI validation
1150
+ this.framework = yield this.detectFrameworkWithAI(aiAnalysis);
1151
+ // Step 3: Generate AI-optimized modifications
1152
+ const modifications = yield this.generateAIOptimizedModifications(aiAnalysis);
1153
+ // Step 4: Apply modifications with conflict resolution
1154
+ yield this.applyModificationsWithAI(modifications, aiAnalysis);
1155
+ // Step 5: Generate intelligent next steps
1156
+ const nextSteps = this.generateAINextSteps(aiAnalysis);
1157
+ // Step 6: Learn from this installation
1158
+ yield this.learnFromInstallation(aiAnalysis, modifications);
1159
+ return {
1160
+ success: true,
1161
+ framework: this.framework,
1162
+ modifications,
1163
+ errors: [],
1164
+ nextSteps,
1165
+ aiAnalysis,
1166
+ learningData: {
1167
+ patterns: aiAnalysis.patterns,
1168
+ framework: this.framework.name,
1169
+ success: true
1170
+ }
1171
+ };
1172
+ }
1173
+ catch (error) {
1174
+ return {
1175
+ success: false,
1176
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
1177
+ modifications: [],
1178
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
1179
+ nextSteps: [],
1180
+ aiAnalysis: {
1181
+ framework: { name: 'unknown', type: 'vanilla' },
1182
+ confidence: 0,
1183
+ patterns: [],
1184
+ conflicts: [],
1185
+ recommendations: [],
1186
+ integrationStrategy: 'script',
1187
+ compatibilityMode: 'legacy'
1188
+ },
1189
+ learningData: {
1190
+ patterns: [],
1191
+ framework: 'unknown',
1192
+ success: false
1193
+ }
1194
+ };
1195
+ }
1196
+ });
1197
+ }
1198
+ /**
1199
+ * AI-powered code analysis using centralized service
1200
+ */
1201
+ performAICodeAnalysis() {
1202
+ return __awaiter(this, void 0, void 0, function* () {
1203
+ const projectFiles = yield this.scanProjectFiles();
1204
+ const codeSamples = yield this.extractCodeSamples(projectFiles);
1205
+ // Use centralized AI service (no user API key required)
1206
+ return yield this.aiService.analyzeCodePatterns(codeSamples);
1207
+ });
1208
+ }
1209
+ /**
1210
+ * Scan project files for analysis
1211
+ */
1212
+ scanProjectFiles() {
1213
+ return __awaiter(this, void 0, void 0, function* () {
1214
+ const files = [];
1215
+ const scanDir = (dir, depth = 0) => {
1216
+ if (depth > 3)
1217
+ return; // Limit depth
1218
+ try {
1219
+ const items = fs__namespace.readdirSync(dir);
1220
+ for (const item of items) {
1221
+ const fullPath = path__namespace.join(dir, item);
1222
+ const stat = fs__namespace.statSync(fullPath);
1223
+ if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
1224
+ scanDir(fullPath, depth + 1);
1225
+ }
1226
+ else if (stat.isFile() && this.isRelevantFile(item)) {
1227
+ files.push(fullPath);
1228
+ }
1229
+ }
1230
+ }
1231
+ catch (error) {
1232
+ // Skip inaccessible directories
1233
+ }
1234
+ };
1235
+ scanDir(this.projectRoot);
1236
+ return files;
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Check if file is relevant for analysis
1241
+ */
1242
+ isRelevantFile(filename) {
1243
+ const relevantExtensions = [
1244
+ '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',
1245
+ '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'
1246
+ ];
1247
+ const relevantNames = [
1248
+ 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',
1249
+ 'next.config', 'nuxt.config', 'angular.json', 'svelte.config',
1250
+ 'app/layout', 'app/page', 'pages/index', 'pages/_app', 'pages/_document'
1251
+ ];
1252
+ return relevantExtensions.some(ext => filename.endsWith(ext)) ||
1253
+ relevantNames.some(name => filename.includes(name));
1254
+ }
1255
+ /**
1256
+ * Extract code samples for AI analysis
1257
+ */
1258
+ extractCodeSamples(files) {
1259
+ return __awaiter(this, void 0, void 0, function* () {
1260
+ const samples = [];
1261
+ for (const file of files.slice(0, 20)) { // Limit to 20 files
1262
+ try {
1263
+ const content = fs__namespace.readFileSync(file, 'utf8');
1264
+ const relativePath = path__namespace.relative(this.projectRoot, file);
1265
+ // Extract relevant code patterns
1266
+ const patterns = this.extractCodePatterns(content);
1267
+ if (patterns.length > 0) {
1268
+ samples.push(`File: ${relativePath}\n${patterns.join('\n')}`);
1269
+ }
1270
+ }
1271
+ catch (error) {
1272
+ // Skip unreadable files
1273
+ }
1274
+ }
1275
+ return samples;
1276
+ });
1277
+ }
1278
+ /**
1279
+ * Extract relevant code patterns
1280
+ */
1281
+ extractCodePatterns(content) {
1282
+ const patterns = [];
1283
+ // Framework-specific patterns
1284
+ const frameworkPatterns = {
1285
+ react: [
1286
+ /import\s+React\s+from\s+['"]react['"]/gi,
1287
+ /from\s+['"]react['"]/gi,
1288
+ /function\s+\w+\s*\(\s*\)\s*{/gi,
1289
+ /const\s+\w+\s*=\s*\(\s*\)\s*=>\s*{/gi
1290
+ ],
1291
+ vue: [
1292
+ /import\s+{\s*createApp\s*}\s+from\s+['"]vue['"]/gi,
1293
+ /from\s+['"]vue['"]/gi,
1294
+ /<template>/gi,
1295
+ /<script\s+setup>/gi
1296
+ ],
1297
+ angular: [
1298
+ /import\s+{\s*Component\s*}\s+from\s+['"]@angular\/core['"]/gi,
1299
+ /@Component\s*\(\s*{/gi,
1300
+ /from\s+['"]@angular/gi
1301
+ ],
1302
+ svelte: [
1303
+ /<script>/gi,
1304
+ /import\s+.*\s+from\s+['"]svelte/gi,
1305
+ /from\s+['"]svelte/gi
1306
+ ],
1307
+ nextjs: [
1308
+ /import\s+.*\s+from\s+['"]next/gi,
1309
+ /from\s+['"]next/gi,
1310
+ /export\s+default\s+function\s+Page/gi,
1311
+ /export\s+default\s+function\s+Layout/gi,
1312
+ /export\s+default\s+function\s+Loading/gi,
1313
+ /export\s+default\s+function\s+Error/gi,
1314
+ /export\s+default\s+function\s+Not-found/gi,
1315
+ /useRouter\s+from\s+['"]next\/navigation['"]/gi,
1316
+ /useRouter\s+from\s+['"]next\/router['"]/gi,
1317
+ /Link\s+from\s+['"]next\/link['"]/gi,
1318
+ /Image\s+from\s+['"]next\/image['"]/gi,
1319
+ /getServerSideProps/gi,
1320
+ /getStaticProps/gi,
1321
+ /getStaticPaths/gi,
1322
+ /next\.config/gi,
1323
+ /app\/layout\.tsx/gi,
1324
+ /app\/page\.tsx/gi,
1325
+ /pages\/.*\.tsx/gi,
1326
+ /pages\/.*\.jsx/gi,
1327
+ /pages\/.*\.ts/gi,
1328
+ /pages\/.*\.js/gi
1329
+ ],
1330
+ nuxt: [
1331
+ /import\s+.*\s+from\s+['"]nuxt/gi,
1332
+ /from\s+['"]nuxt/gi,
1333
+ /export\s+default\s+defineNuxtConfig/gi,
1334
+ /defineNuxtConfig/gi,
1335
+ /nuxt\.config\.ts/gi,
1336
+ /nuxt\.config\.js/gi,
1337
+ /@nuxt\//gi,
1338
+ /#app/gi,
1339
+ /useNuxtApp/gi,
1340
+ /useRuntimeConfig/gi,
1341
+ /useSeoMeta/gi,
1342
+ /useHead/gi,
1343
+ /useLazyFetch/gi,
1344
+ /useFetch/gi,
1345
+ /useAsyncData/gi,
1346
+ /<NuxtLayout/gi,
1347
+ /<NuxtPage/gi,
1348
+ /NuxtLayout/gi,
1349
+ /NuxtPage/gi,
1350
+ /pages\/.*\.vue/gi,
1351
+ /layouts\/.*\.vue/gi,
1352
+ /components\/.*\.vue/gi,
1353
+ /composables\/.*\.ts/gi,
1354
+ /middleware\/.*\.ts/gi,
1355
+ /server\/.*\.ts/gi,
1356
+ /plugins\/.*\.ts/gi,
1357
+ /public\//gi,
1358
+ /assets\//gi,
1359
+ /content\//gi
1360
+ ]
1361
+ };
1362
+ // Extract patterns for each framework
1363
+ for (const [framework, regexes] of Object.entries(frameworkPatterns)) {
1364
+ for (const regex of regexes) {
1365
+ const matches = content.match(regex);
1366
+ if (matches) {
1367
+ // Add raw patterns for heuristic analysis
1368
+ patterns.push(...matches.slice(0, 3));
1369
+ // Also add formatted patterns for debugging
1370
+ patterns.push(`${framework.toUpperCase()}: ${matches.slice(0, 3).join(', ')}`);
1371
+ }
1372
+ }
1373
+ }
1374
+ // Extract import patterns
1375
+ const importMatches = content.match(/import\s+.*\s+from\s+['"][^'"]+['"]/gi);
1376
+ if (importMatches) {
1377
+ patterns.push(`IMPORTS: ${importMatches.slice(0, 5).join(', ')}`);
1378
+ }
1379
+ // Extract export patterns
1380
+ const exportMatches = content.match(/export\s+.*/gi);
1381
+ if (exportMatches) {
1382
+ patterns.push(`EXPORTS: ${exportMatches.slice(0, 3).join(', ')}`);
1383
+ }
1384
+ return patterns;
1385
+ }
1386
+ /**
1387
+ * AI-enhanced framework detection
1388
+ */
1389
+ detectFrameworkWithAI(aiAnalysis) {
1390
+ const _super = Object.create(null, {
1391
+ detectFramework: { get: () => super.detectFramework }
1392
+ });
1393
+ return __awaiter(this, void 0, void 0, function* () {
1394
+ // Combine AI analysis with traditional detection
1395
+ const traditionalFramework = yield _super.detectFramework.call(this);
1396
+ // Use AI analysis if confidence is high, but preserve bundler info
1397
+ if (aiAnalysis.confidence > 0.8) {
1398
+ return Object.assign(Object.assign({}, aiAnalysis.framework), { bundler: traditionalFramework.bundler, packageManager: traditionalFramework.packageManager, hasTypeScript: traditionalFramework.hasTypeScript, hasRouter: traditionalFramework.hasRouter, projectRoot: this.projectRoot });
1399
+ }
1400
+ // Merge AI insights with traditional detection
1401
+ return Object.assign(Object.assign({}, traditionalFramework), (aiAnalysis.framework.type !== 'vanilla' && {
1402
+ type: aiAnalysis.framework.type,
1403
+ name: aiAnalysis.framework.name
1404
+ }));
1405
+ });
1406
+ }
1407
+ /**
1408
+ * Generate AI-optimized modifications
1409
+ */
1410
+ generateAIOptimizedModifications(aiAnalysis) {
1411
+ const _super = Object.create(null, {
1412
+ generateModifications: { get: () => super.generateModifications }
1413
+ });
1414
+ return __awaiter(this, void 0, void 0, function* () {
1415
+ const baseModifications = yield _super.generateModifications.call(this);
1416
+ // Enhance with AI recommendations
1417
+ const enhancedModifications = baseModifications.map(mod => {
1418
+ return this.enhanceModificationWithAI(mod, aiAnalysis);
1419
+ });
1420
+ // Add AI-specific optimizations
1421
+ const aiOptimizations = this.generateAIOptimizations(aiAnalysis);
1422
+ enhancedModifications.push(...aiOptimizations);
1423
+ return enhancedModifications;
1424
+ });
1425
+ }
1426
+ /**
1427
+ * Enhance modification with AI insights
1428
+ */
1429
+ enhanceModificationWithAI(mod, aiAnalysis) {
1430
+ let enhancedContent = mod.content;
1431
+ // Add compatibility comments
1432
+ if (aiAnalysis.compatibilityMode === 'legacy') {
1433
+ enhancedContent = `// HumanBehavior SDK - Legacy Compatibility Mode\n${enhancedContent}`;
1434
+ }
1435
+ // Add future-proofing comments
1436
+ if (aiAnalysis.integrationStrategy === 'provider') {
1437
+ enhancedContent = `// HumanBehavior SDK - Provider Pattern (Future-proof)\n${enhancedContent}`;
1438
+ }
1439
+ // Add conflict resolution
1440
+ if (aiAnalysis.conflicts.length > 0) {
1441
+ enhancedContent = `// Conflict Resolution: ${aiAnalysis.conflicts.join(', ')}\n${enhancedContent}`;
1442
+ }
1443
+ return Object.assign(Object.assign({}, mod), { content: enhancedContent, description: `${mod.description} (AI-optimized)` });
1444
+ }
1445
+ /**
1446
+ * Generate AI-specific optimizations
1447
+ */
1448
+ generateAIOptimizations(aiAnalysis) {
1449
+ const optimizations = [];
1450
+ // AI optimizations are now handled through environment variables and code injection
1451
+ // No separate config file needed - everything is integrated into the existing codebase
1452
+ return optimizations;
1453
+ }
1454
+ /**
1455
+ * Apply modifications with AI conflict resolution
1456
+ */
1457
+ applyModificationsWithAI(modifications, aiAnalysis) {
1458
+ return __awaiter(this, void 0, void 0, function* () {
1459
+ for (const modification of modifications) {
1460
+ try {
1461
+ // Check for conflicts
1462
+ const conflicts = yield this.detectConflicts(modification);
1463
+ if (conflicts.length > 0) {
1464
+ // Resolve conflicts using centralized AI service
1465
+ const resolutions = yield this.aiService.resolveConflicts(conflicts, aiAnalysis.framework);
1466
+ const resolvedModification = yield this.resolveConflicts(modification, conflicts, resolutions, aiAnalysis);
1467
+ yield this.applyModification(resolvedModification);
1468
+ }
1469
+ else {
1470
+ yield this.applyModification(modification);
1471
+ }
1472
+ }
1473
+ catch (error) {
1474
+ throw new Error(`Failed to apply AI-optimized modification to ${modification.filePath}: ${error}`);
1475
+ }
1476
+ }
1477
+ });
1478
+ }
1479
+ /**
1480
+ * Detect potential conflicts
1481
+ */
1482
+ detectConflicts(modification) {
1483
+ return __awaiter(this, void 0, void 0, function* () {
1484
+ const conflicts = [];
1485
+ if (fs__namespace.existsSync(modification.filePath)) {
1486
+ const existingContent = fs__namespace.readFileSync(modification.filePath, 'utf8');
1487
+ // Check for existing HumanBehavior code
1488
+ if (existingContent.includes('HumanBehavior') || existingContent.includes('humanbehavior')) {
1489
+ conflicts.push('existing_humanbehavior_code');
1490
+ }
1491
+ // Check for conflicting providers/plugins
1492
+ if (modification.content.includes('Provider') && existingContent.includes('Provider')) {
1493
+ conflicts.push('existing_provider');
1494
+ }
1495
+ // Check for TypeScript conflicts
1496
+ if (modification.content.includes('import') && existingContent.includes('require(')) {
1497
+ conflicts.push('module_system_conflict');
1498
+ }
1499
+ }
1500
+ return conflicts;
1501
+ });
1502
+ }
1503
+ /**
1504
+ * Resolve conflicts with AI
1505
+ */
1506
+ resolveConflicts(modification, conflicts, resolutions, aiAnalysis) {
1507
+ return __awaiter(this, void 0, void 0, function* () {
1508
+ let resolvedContent = modification.content;
1509
+ for (let i = 0; i < conflicts.length; i++) {
1510
+ const conflict = conflicts[i];
1511
+ const resolution = resolutions[i];
1512
+ switch (resolution) {
1513
+ case 'update_existing_integration':
1514
+ resolvedContent = `// Updated HumanBehavior Integration\n${resolvedContent}`;
1515
+ break;
1516
+ case 'merge_providers':
1517
+ resolvedContent = resolvedContent.replace(/<HumanBehaviorProvider/g, '<HumanBehaviorProvider key="updated"');
1518
+ break;
1519
+ case 'hybrid_module_support':
1520
+ resolvedContent = `// Hybrid module system support\n${resolvedContent}`;
1521
+ break;
1522
+ case 'skip_conflict':
1523
+ // Skip this modification
1524
+ return Object.assign(Object.assign({}, modification), { content: '', description: `${modification.description} (skipped due to conflict)` });
1525
+ default:
1526
+ // Default resolution
1527
+ resolvedContent = `// Conflict resolved: ${conflict}\n${resolvedContent}`;
1528
+ }
1529
+ }
1530
+ return Object.assign(Object.assign({}, modification), { content: resolvedContent, description: `${modification.description} (conflict-resolved)` });
1531
+ });
1532
+ }
1533
+ /**
1534
+ * Apply single modification
1535
+ */
1536
+ applyModification(modification) {
1537
+ return __awaiter(this, void 0, void 0, function* () {
1538
+ if (!modification.content)
1539
+ return; // Skip empty modifications
1540
+ const dir = path__namespace.dirname(modification.filePath);
1541
+ if (!fs__namespace.existsSync(dir)) {
1542
+ fs__namespace.mkdirSync(dir, { recursive: true });
1543
+ }
1544
+ switch (modification.action) {
1545
+ case 'create':
1546
+ fs__namespace.writeFileSync(modification.filePath, modification.content);
1547
+ break;
1548
+ case 'modify':
1549
+ fs__namespace.writeFileSync(modification.filePath, modification.content);
1550
+ break;
1551
+ case 'append':
1552
+ fs__namespace.appendFileSync(modification.filePath, '\n' + modification.content);
1553
+ break;
1554
+ }
1555
+ });
1556
+ }
1557
+ /**
1558
+ * Generate AI-enhanced next steps
1559
+ */
1560
+ generateAINextSteps(aiAnalysis) {
1561
+ const steps = [
1562
+ '✅ AI-optimized SDK installation completed!',
1563
+ `🎯 Framework detected: ${aiAnalysis.framework.name} (confidence: ${Math.round(aiAnalysis.confidence * 100)}%)`,
1564
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
1565
+ `🔄 Compatibility mode: ${aiAnalysis.compatibilityMode}`,
1566
+ '🚀 Your app is now tracking user behavior with AI-optimized configuration'
1567
+ ];
1568
+ if (aiAnalysis.recommendations.length > 0) {
1569
+ steps.push('💡 AI Recommendations:');
1570
+ aiAnalysis.recommendations.forEach(rec => steps.push(` • ${rec}`));
1571
+ }
1572
+ return steps;
1573
+ }
1574
+ /**
1575
+ * Learn from installation for future improvements
1576
+ */
1577
+ learnFromInstallation(aiAnalysis, modifications) {
1578
+ return __awaiter(this, void 0, void 0, function* () {
1579
+ const learningData = {
1580
+ timestamp: new Date().toISOString(),
1581
+ framework: aiAnalysis.framework.name,
1582
+ patterns: aiAnalysis.patterns,
1583
+ integrationStrategy: aiAnalysis.integrationStrategy,
1584
+ compatibilityMode: aiAnalysis.compatibilityMode,
1585
+ modifications: modifications.length,
1586
+ success: true
1587
+ };
1588
+ // Store learning data
1589
+ this.learningCache.set(`${aiAnalysis.framework.name}_${Date.now()}`, learningData);
1590
+ // Update pattern database
1591
+ if (!this.patternDatabase.has(aiAnalysis.framework.name)) {
1592
+ this.patternDatabase.set(aiAnalysis.framework.name, []);
1593
+ }
1594
+ this.patternDatabase.get(aiAnalysis.framework.name).push(learningData);
1595
+ // Save to disk
1596
+ yield this.saveLearningData();
1597
+ });
1598
+ }
1599
+ /**
1600
+ * Load learning data from disk
1601
+ */
1602
+ loadLearningData() {
1603
+ // Don't load learning data from user's project - keep it in memory only
1604
+ // This prevents cluttering the user's project with internal files
1605
+ }
1606
+ /**
1607
+ * Save learning data to disk
1608
+ */
1609
+ saveLearningData() {
1610
+ return __awaiter(this, void 0, void 0, function* () {
1611
+ // Don't save learning data to user's project - keep it in memory only
1612
+ // This prevents cluttering the user's project with internal files
1613
+ });
1614
+ }
1615
+ /**
1616
+ * Get AI insights for a specific framework
1617
+ */
1618
+ getAIInsights(frameworkName) {
1619
+ return this.patternDatabase.get(frameworkName) || [];
1620
+ }
1621
+ /**
1622
+ * Get learning statistics
1623
+ */
1624
+ getLearningStats() {
1625
+ const stats = {
1626
+ totalInstallations: this.learningCache.size,
1627
+ frameworks: {},
1628
+ patterns: {}
1629
+ };
1630
+ for (const [framework, data] of this.patternDatabase.entries()) {
1631
+ stats.frameworks[framework] = data.length;
1632
+ }
1633
+ return stats;
1634
+ }
1635
+ }
1636
+ /**
1637
+ * Browser-based AI installation wizard
1638
+ */
1639
+ class AIBrowserInstallationWizard {
1640
+ constructor(apiKey, aiService) {
1641
+ this.apiKey = apiKey;
1642
+ this.aiService = aiService || new DefaultAIService();
1643
+ }
1644
+ install() {
1645
+ return __awaiter(this, void 0, void 0, function* () {
1646
+ try {
1647
+ // AI-powered browser detection
1648
+ const aiAnalysis = yield this.performBrowserAIAnalysis();
1649
+ // Generate AI-optimized browser modifications
1650
+ const modifications = this.generateAIBrowserModifications(aiAnalysis);
1651
+ return {
1652
+ success: true,
1653
+ framework: aiAnalysis.framework,
1654
+ modifications,
1655
+ errors: [],
1656
+ nextSteps: [
1657
+ '✅ AI-optimized browser integration ready!',
1658
+ `🎯 Framework detected: ${aiAnalysis.framework.name}`,
1659
+ `🔧 Integration strategy: ${aiAnalysis.integrationStrategy}`,
1660
+ '📋 Copy the generated code to your project',
1661
+ '🚀 Your app will be ready to track user behavior'
1662
+ ],
1663
+ aiAnalysis,
1664
+ learningData: {
1665
+ patterns: aiAnalysis.patterns,
1666
+ framework: aiAnalysis.framework.name,
1667
+ success: true
1668
+ }
1669
+ };
1670
+ }
1671
+ catch (error) {
1672
+ return {
1673
+ success: false,
1674
+ framework: { name: 'unknown', type: 'vanilla' },
1675
+ modifications: [],
1676
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
1677
+ nextSteps: [],
1678
+ aiAnalysis: {
1679
+ framework: { name: 'unknown', type: 'vanilla' },
1680
+ confidence: 0,
1681
+ patterns: [],
1682
+ conflicts: [],
1683
+ recommendations: [],
1684
+ integrationStrategy: 'script',
1685
+ compatibilityMode: 'legacy'
1686
+ },
1687
+ learningData: {
1688
+ patterns: [],
1689
+ framework: 'unknown',
1690
+ success: false
1691
+ }
1692
+ };
1693
+ }
1694
+ });
1695
+ }
1696
+ performBrowserAIAnalysis() {
1697
+ return __awaiter(this, void 0, void 0, function* () {
1698
+ // Browser-based framework detection
1699
+ this.detectBrowserFramework();
1700
+ // Analyze browser environment
1701
+ const patterns = this.analyzeBrowserPatterns();
1702
+ // Use centralized AI service for analysis
1703
+ const codeSamples = [`Browser Environment: ${patterns.join(', ')}`];
1704
+ return yield this.aiService.analyzeCodePatterns(codeSamples);
1705
+ });
1706
+ }
1707
+ detectBrowserFramework() {
1708
+ if (typeof window !== 'undefined') {
1709
+ if (window.React) {
1710
+ return { name: 'react', type: 'react' };
1711
+ }
1712
+ if (window.Vue) {
1713
+ return { name: 'vue', type: 'vue' };
1714
+ }
1715
+ if (window.angular) {
1716
+ return { name: 'angular', type: 'angular' };
1717
+ }
1718
+ }
1719
+ return { name: 'vanilla', type: 'vanilla' };
1720
+ }
1721
+ analyzeBrowserPatterns() {
1722
+ const patterns = [];
1723
+ if (typeof window !== 'undefined') {
1724
+ // Analyze global objects
1725
+ if (window.React)
1726
+ patterns.push('React global detected');
1727
+ if (window.Vue)
1728
+ patterns.push('Vue global detected');
1729
+ if (window.angular)
1730
+ patterns.push('Angular global detected');
1731
+ // Analyze DOM patterns
1732
+ if (document.querySelector('[data-reactroot]'))
1733
+ patterns.push('React DOM detected');
1734
+ if (document.querySelector('[data-vue]'))
1735
+ patterns.push('Vue DOM detected');
1736
+ // Analyze script patterns
1737
+ const scripts = document.querySelectorAll('script');
1738
+ scripts.forEach(script => {
1739
+ if (script.src.includes('react'))
1740
+ patterns.push('React script detected');
1741
+ if (script.src.includes('vue'))
1742
+ patterns.push('Vue script detected');
1743
+ });
1744
+ }
1745
+ return patterns;
1746
+ }
1747
+ generateAIBrowserModifications(aiAnalysis) {
1748
+ const modifications = [];
1749
+ switch (aiAnalysis.framework.type) {
1750
+ case 'react':
1751
+ modifications.push({
1752
+ filePath: 'App.jsx',
1753
+ action: 'create',
1754
+ content: `// AI-Optimized React Integration
1755
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
1756
+
1757
+ function App() {
1758
+ return (
1759
+ <HumanBehaviorProvider
1760
+ apiKey="${this.apiKey}"
1761
+ config={{
1762
+ // AI-generated optimizations
1763
+ enablePerformanceTracking: true,
1764
+ enableErrorTracking: true,
1765
+ framework: '${aiAnalysis.framework.name}',
1766
+ integrationStrategy: '${aiAnalysis.integrationStrategy}'
1767
+ }}
1768
+ >
1769
+ {/* Your app components */}
1770
+ </HumanBehaviorProvider>
1771
+ );
1772
+ }
1773
+
1774
+ export default App;`,
1775
+ description: 'AI-optimized React component with HumanBehaviorProvider'
1776
+ });
1777
+ break;
1778
+ default:
1779
+ modifications.push({
1780
+ filePath: 'humanbehavior-init.js',
1781
+ action: 'create',
1782
+ content: `// AI-Optimized Vanilla JS Integration
1783
+ import { HumanBehaviorTracker } from 'humanbehavior-js';
1784
+
1785
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}', {
1786
+ // AI-generated configuration
1787
+ framework: '${aiAnalysis.framework.name}',
1788
+ integrationStrategy: '${aiAnalysis.integrationStrategy}',
1789
+ compatibilityMode: '${aiAnalysis.compatibilityMode}',
1790
+ enablePerformanceTracking: true,
1791
+ enableErrorTracking: true
1792
+ });`,
1793
+ description: 'AI-optimized vanilla JS initialization'
1794
+ });
1795
+ }
1796
+ return modifications;
1797
+ }
1798
+ }
1799
+
1800
+ /**
1801
+ * Remote AI Service Implementation
1802
+ *
1803
+ * This connects to your deployed Lambda function via API Gateway
1804
+ */
1805
+ class RemoteAIService {
1806
+ constructor(config) {
1807
+ this.config = Object.assign({ timeout: 10000 }, config);
1808
+ }
1809
+ /**
1810
+ * Analyze code patterns using your deployed AI service
1811
+ */
1812
+ analyzeCodePatterns(codeSamples) {
1813
+ return __awaiter(this, void 0, void 0, function* () {
1814
+ try {
1815
+ const response = yield fetch(`${this.config.apiEndpoint}/analyze`, {
1816
+ method: 'POST',
1817
+ headers: {
1818
+ 'Content-Type': 'application/json',
1819
+ },
1820
+ body: JSON.stringify({ codeSamples }),
1821
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
1822
+ });
1823
+ if (!response.ok) {
1824
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
1825
+ }
1826
+ const result = yield response.json();
1827
+ return result.analysis;
1828
+ }
1829
+ catch (error) {
1830
+ console.warn('Remote AI service failed, falling back to heuristic analysis:', error);
1831
+ return this.performHeuristicAnalysis(codeSamples);
1832
+ }
1833
+ });
1834
+ }
1835
+ /**
1836
+ * Resolve conflicts using your deployed AI service
1837
+ */
1838
+ resolveConflicts(conflicts, framework) {
1839
+ return __awaiter(this, void 0, void 0, function* () {
1840
+ try {
1841
+ const response = yield fetch(`${this.config.apiEndpoint}/resolve-conflicts`, {
1842
+ method: 'POST',
1843
+ headers: {
1844
+ 'Content-Type': 'application/json',
1845
+ },
1846
+ body: JSON.stringify({ conflicts, framework }),
1847
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
1848
+ });
1849
+ if (!response.ok) {
1850
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
1851
+ }
1852
+ const result = yield response.json();
1853
+ return result.resolutions || [];
1854
+ }
1855
+ catch (error) {
1856
+ console.warn('Remote AI conflict resolution failed, using heuristic approach:', error);
1857
+ return this.resolveConflictsHeuristic(conflicts, framework);
1858
+ }
1859
+ });
1860
+ }
1861
+ /**
1862
+ * Generate optimizations using your deployed AI service
1863
+ */
1864
+ generateOptimizations(framework, patterns) {
1865
+ return __awaiter(this, void 0, void 0, function* () {
1866
+ try {
1867
+ const response = yield fetch(`${this.config.apiEndpoint}/optimize`, {
1868
+ method: 'POST',
1869
+ headers: {
1870
+ 'Content-Type': 'application/json',
1871
+ },
1872
+ body: JSON.stringify({ framework, patterns }),
1873
+ signal: AbortSignal.timeout(this.config.timeout || 10000)
1874
+ });
1875
+ if (!response.ok) {
1876
+ throw new Error(`AI service returned ${response.status}: ${response.statusText}`);
1877
+ }
1878
+ const result = yield response.json();
1879
+ return result.optimizations || [];
1880
+ }
1881
+ catch (error) {
1882
+ console.warn('Remote AI optimization generation failed, using heuristic approach:', error);
1883
+ return this.generateOptimizationsHeuristic(framework, patterns);
1884
+ }
1885
+ });
1886
+ }
1887
+ /**
1888
+ * Heuristic analysis fallback
1889
+ */
1890
+ performHeuristicAnalysis(codeSamples) {
1891
+ const patterns = codeSamples.join(' ').toLowerCase();
1892
+ // Framework detection
1893
+ let framework = { name: 'vanilla', type: 'vanilla' };
1894
+ let confidence = 0.5;
1895
+ 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')) {
1896
+ framework = { name: 'nuxt', type: 'nuxt' };
1897
+ confidence = 0.95;
1898
+ }
1899
+ 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/')) {
1900
+ framework = { name: 'nextjs', type: 'nextjs' };
1901
+ confidence = 0.95;
1902
+ }
1903
+ else if (patterns.includes('react')) {
1904
+ framework = { name: 'react', type: 'react' };
1905
+ confidence = 0.9;
1906
+ }
1907
+ else if (patterns.includes('vue')) {
1908
+ framework = { name: 'vue', type: 'vue' };
1909
+ confidence = 0.9;
1910
+ }
1911
+ else if (patterns.includes('angular')) {
1912
+ framework = { name: 'angular', type: 'angular' };
1913
+ confidence = 0.9;
1914
+ }
1915
+ else if (patterns.includes('svelte')) {
1916
+ framework = { name: 'svelte', type: 'svelte' };
1917
+ confidence = 0.9;
1918
+ }
1919
+ // Integration strategy
1920
+ let integrationStrategy = 'script';
1921
+ if (framework.type === 'react' || framework.type === 'nextjs') {
1922
+ integrationStrategy = 'provider';
1923
+ }
1924
+ else if (framework.type === 'vue') {
1925
+ integrationStrategy = 'plugin';
1926
+ }
1927
+ else if (framework.type === 'angular') {
1928
+ integrationStrategy = 'module';
1929
+ }
1930
+ // Compatibility mode
1931
+ let compatibilityMode = 'modern';
1932
+ if (patterns.includes('require(') || patterns.includes('var ')) {
1933
+ compatibilityMode = 'legacy';
1934
+ }
1935
+ return {
1936
+ framework,
1937
+ confidence,
1938
+ patterns: codeSamples,
1939
+ conflicts: [],
1940
+ recommendations: [],
1941
+ integrationStrategy,
1942
+ compatibilityMode
1943
+ };
1944
+ }
1945
+ /**
1946
+ * Heuristic conflict resolution
1947
+ */
1948
+ resolveConflictsHeuristic(conflicts, framework) {
1949
+ const resolutions = [];
1950
+ for (const conflict of conflicts) {
1951
+ switch (conflict) {
1952
+ case 'existing_humanbehavior_code':
1953
+ resolutions.push('update_existing_integration');
1954
+ break;
1955
+ case 'existing_provider':
1956
+ resolutions.push('merge_providers');
1957
+ break;
1958
+ case 'module_system_conflict':
1959
+ resolutions.push('hybrid_module_support');
1960
+ break;
1961
+ default:
1962
+ resolutions.push('skip_conflict');
1963
+ }
1964
+ }
1965
+ return resolutions;
1966
+ }
1967
+ /**
1968
+ * Heuristic optimization generation
1969
+ */
1970
+ generateOptimizationsHeuristic(framework, patterns) {
1971
+ const optimizations = [];
1972
+ switch (framework.type) {
1973
+ case 'react':
1974
+ optimizations.push('Use React.memo for performance optimization');
1975
+ optimizations.push('Implement error boundaries for better error tracking');
1976
+ optimizations.push('Consider using React.lazy for code splitting');
1977
+ break;
1978
+ case 'vue':
1979
+ optimizations.push('Use Vue 3 Composition API for better performance');
1980
+ optimizations.push('Implement proper error handling in components');
1981
+ optimizations.push('Consider using Vue Router for navigation tracking');
1982
+ break;
1983
+ case 'angular':
1984
+ optimizations.push('Use Angular standalone components for better tree-shaking');
1985
+ optimizations.push('Implement proper error handling with ErrorHandler');
1986
+ optimizations.push('Consider using Angular signals for state management');
1987
+ break;
1988
+ default:
1989
+ optimizations.push('Enable performance tracking');
1990
+ optimizations.push('Implement error tracking');
1991
+ optimizations.push('Consider progressive enhancement');
1992
+ }
1993
+ return optimizations;
1994
+ }
1995
+ }
1996
+
1997
+ /**
1998
+ * Manual Framework Installation Wizard
1999
+ *
2000
+ * This wizard allows users to manually specify their framework instead of auto-detection.
2001
+ * Useful when auto-detection fails or users want more control.
2002
+ */
2003
+ class ManualFrameworkInstallationWizard extends AutoInstallationWizard {
2004
+ constructor(apiKey, projectRoot = process.cwd(), framework) {
2005
+ super(apiKey, projectRoot);
2006
+ this.selectedFramework = framework.toLowerCase();
2007
+ this.framework = this.createFrameworkInfo(this.selectedFramework);
2008
+ }
2009
+ /**
2010
+ * Manual installation with user-specified framework
2011
+ */
2012
+ install() {
2013
+ return __awaiter(this, void 0, void 0, function* () {
2014
+ try {
2015
+ // Step 1: Handle framework selection
2016
+ if (this.selectedFramework === 'auto') {
2017
+ // Use full AI detection for "Other" option
2018
+ this.framework = yield this.runFullDetection();
2019
+ }
2020
+ else {
2021
+ // Set framework based on user selection
2022
+ this.framework = this.createFrameworkInfo(this.selectedFramework);
2023
+ if (!this.framework) {
2024
+ this.framework = { name: 'unknown', type: 'vanilla' };
2025
+ }
2026
+ // Step 2: Run full detection logic to find entry points, file names, etc.
2027
+ const detectedFramework = yield this.runFullDetection();
2028
+ // Step 3: Merge manual framework with detected details
2029
+ this.framework = Object.assign(Object.assign({}, detectedFramework), { name: this.framework.name, type: this.framework.type });
2030
+ }
2031
+ // Step 4: Install package
2032
+ yield this.installPackage();
2033
+ // Step 5: Generate and apply code modifications
2034
+ const modifications = yield this.generateModifications();
2035
+ yield this.applyModifications(modifications);
2036
+ // Step 6: Generate next steps
2037
+ const nextSteps = this.generateManualNextSteps();
2038
+ return {
2039
+ success: true,
2040
+ framework: this.framework,
2041
+ modifications,
2042
+ errors: [],
2043
+ nextSteps,
2044
+ selectedFramework: this.selectedFramework,
2045
+ manualMode: true
2046
+ };
2047
+ }
2048
+ catch (error) {
2049
+ return {
2050
+ success: false,
2051
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
2052
+ modifications: [],
2053
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
2054
+ nextSteps: [],
2055
+ selectedFramework: this.selectedFramework,
2056
+ manualMode: true
2057
+ };
2058
+ }
2059
+ });
2060
+ }
2061
+ /**
2062
+ * Run full detection logic to find entry points, file names, bundler, etc.
2063
+ */
2064
+ runFullDetection() {
2065
+ return __awaiter(this, void 0, void 0, function* () {
2066
+ if (this.selectedFramework === 'auto') {
2067
+ // Use AI service for auto-detection
2068
+ const aiService = new RemoteAIService({
2069
+ apiEndpoint: 'https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod'
2070
+ });
2071
+ // Use AI service directly for detection
2072
+ const projectFiles = yield this.scanProjectFiles();
2073
+ const codeSamples = yield this.extractCodeSamples(projectFiles);
2074
+ const aiAnalysis = yield aiService.analyzeCodePatterns(codeSamples);
2075
+ return aiAnalysis.framework;
2076
+ }
2077
+ else {
2078
+ // Use traditional detection for manual frameworks
2079
+ const tempWizard = new AutoInstallationWizard(this.apiKey, this.projectRoot);
2080
+ const detected = yield tempWizard.detectFramework();
2081
+ return detected;
2082
+ }
2083
+ });
2084
+ }
2085
+ /**
2086
+ * Scan project files for analysis
2087
+ */
2088
+ scanProjectFiles() {
2089
+ return __awaiter(this, void 0, void 0, function* () {
2090
+ const files = [];
2091
+ const scanDir = (dir, depth = 0) => {
2092
+ if (depth > 3)
2093
+ return; // Limit depth
2094
+ try {
2095
+ const items = fs__namespace.readdirSync(dir);
2096
+ for (const item of items) {
2097
+ const fullPath = path__namespace.join(dir, item);
2098
+ const stat = fs__namespace.statSync(fullPath);
2099
+ if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
2100
+ scanDir(fullPath, depth + 1);
2101
+ }
2102
+ else if (stat.isFile() && this.isRelevantFile(item)) {
2103
+ files.push(fullPath);
2104
+ }
2105
+ }
2106
+ }
2107
+ catch (error) {
2108
+ // Skip inaccessible directories
2109
+ }
2110
+ };
2111
+ scanDir(this.projectRoot);
2112
+ return files;
2113
+ });
2114
+ }
2115
+ /**
2116
+ * Check if file is relevant for analysis
2117
+ */
2118
+ isRelevantFile(filename) {
2119
+ const relevantExtensions = [
2120
+ '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.html',
2121
+ '.json', '.config.js', '.config.ts', '.babelrc', '.eslintrc'
2122
+ ];
2123
+ const relevantNames = [
2124
+ 'package.json', 'tsconfig.json', 'vite.config', 'webpack.config',
2125
+ 'next.config', 'nuxt.config', 'angular.json', 'svelte.config'
2126
+ ];
2127
+ return relevantExtensions.some(ext => filename.endsWith(ext)) ||
2128
+ relevantNames.some(name => filename.includes(name));
2129
+ }
2130
+ /**
2131
+ * Extract code samples for AI analysis
2132
+ */
2133
+ extractCodeSamples(files) {
2134
+ return __awaiter(this, void 0, void 0, function* () {
2135
+ const samples = [];
2136
+ for (const file of files.slice(0, 20)) { // Limit to 20 files
2137
+ try {
2138
+ const content = fs__namespace.readFileSync(file, 'utf8');
2139
+ const relativePath = path__namespace.relative(this.projectRoot, file);
2140
+ samples.push(`File: ${relativePath}\n${content.substring(0, 1000)}`);
2141
+ }
2142
+ catch (error) {
2143
+ // Skip unreadable files
2144
+ }
2145
+ }
2146
+ return samples;
2147
+ });
2148
+ }
2149
+ /**
2150
+ * Create framework info based on user selection
2151
+ */
2152
+ createFrameworkInfo(framework) {
2153
+ const frameworkMap = {
2154
+ 'react': { name: 'react', type: 'react' },
2155
+ 'nextjs': { name: 'nextjs', type: 'nextjs' },
2156
+ 'next': { name: 'nextjs', type: 'nextjs' },
2157
+ 'vue': { name: 'vue', type: 'vue' },
2158
+ 'nuxt': { name: 'nuxt', type: 'nuxt' },
2159
+ 'nuxtjs': { name: 'nuxt', type: 'nuxt' },
2160
+ 'angular': { name: 'angular', type: 'angular' },
2161
+ 'svelte': { name: 'svelte', type: 'svelte' },
2162
+ 'sveltekit': { name: 'svelte', type: 'svelte' },
2163
+ 'remix': { name: 'remix', type: 'remix' },
2164
+ 'vanilla': { name: 'vanilla', type: 'vanilla' },
2165
+ 'node': { name: 'node', type: 'node' },
2166
+ 'auto': { name: 'auto-detected', type: 'auto' }
2167
+ };
2168
+ return frameworkMap[framework] || { name: framework, type: 'vanilla' };
2169
+ }
2170
+ /**
2171
+ * Override framework detection to use manual selection
2172
+ */
2173
+ detectFramework() {
2174
+ return __awaiter(this, void 0, void 0, function* () {
2175
+ return this.framework || { name: 'unknown', type: 'vanilla' };
2176
+ });
2177
+ }
2178
+ /**
2179
+ * Generate next steps with manual mode info
2180
+ */
2181
+ generateManualNextSteps() {
2182
+ var _a;
2183
+ return [
2184
+ '✅ Manual framework installation completed!',
2185
+ `🎯 Selected framework: ${((_a = this.framework) === null || _a === void 0 ? void 0 : _a.name) || 'unknown'}`,
2186
+ `🔧 Integration strategy: ${this.getIntegrationStrategy()}`,
2187
+ '🚀 Your app is now ready to track user behavior',
2188
+ '📊 View sessions in your HumanBehavior dashboard'
2189
+ ];
2190
+ }
2191
+ /**
2192
+ * Get integration strategy based on framework
2193
+ */
2194
+ getIntegrationStrategy() {
2195
+ var _a;
2196
+ if (!((_a = this.framework) === null || _a === void 0 ? void 0 : _a.type))
2197
+ return 'script';
2198
+ switch (this.framework.type) {
2199
+ case 'react':
2200
+ case 'nextjs':
2201
+ return 'provider';
2202
+ case 'vue':
2203
+ return 'plugin';
2204
+ case 'angular':
2205
+ return 'module';
2206
+ default:
2207
+ return 'script';
2208
+ }
2209
+ }
2210
+ }
2211
+
2212
+ /**
2213
+ * AI-Enhanced HumanBehavior SDK Auto-Installation CLI
2214
+ *
2215
+ * Usage: npx humanbehavior-js ai-auto-install [api-key]
2216
+ *
2217
+ * This tool uses AI to intelligently detect frameworks, analyze code patterns,
2218
+ * and generate optimal integration code that's both future-proof and backward-compatible.
2219
+ */
2220
+ class AIAutoInstallCLI {
2221
+ constructor(options) {
2222
+ this.options = options;
2223
+ this.rl = readline__namespace.createInterface({
2224
+ input: process.stdin,
2225
+ output: process.stdout
2226
+ });
2227
+ }
2228
+ run() {
2229
+ return __awaiter(this, void 0, void 0, function* () {
2230
+ console.log('🤖 AI-Enhanced HumanBehavior SDK Auto-Installation');
2231
+ console.log('================================================\n');
2232
+ try {
2233
+ // Get API key
2234
+ const apiKey = yield this.getApiKey();
2235
+ if (!apiKey) {
2236
+ console.error('❌ API key is required');
2237
+ process.exit(1);
2238
+ }
2239
+ // Get project path
2240
+ const projectPath = this.options.projectPath || process.cwd();
2241
+ // Choose installation mode
2242
+ const installationMode = yield this.chooseInstallationMode();
2243
+ // Confirm installation
2244
+ if (!this.options.yes) {
2245
+ const confirmed = yield this.confirmInstallation(projectPath, installationMode);
2246
+ if (!confirmed) {
2247
+ console.log('Installation cancelled.');
2248
+ process.exit(0);
2249
+ }
2250
+ }
2251
+ // Run installation
2252
+ console.log('🔍 Analyzing your project with AI...');
2253
+ let result;
2254
+ if (this.options.browser) {
2255
+ const wizard = new AIBrowserInstallationWizard(apiKey);
2256
+ result = yield wizard.install();
2257
+ }
2258
+ else if (installationMode === 'manual') {
2259
+ // Manual AI-Enhanced framework selection
2260
+ const framework = yield this.chooseFramework();
2261
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
2262
+ result = yield wizard.install();
2263
+ }
2264
+ else if (installationMode.startsWith('manual:')) {
2265
+ // Manual framework selection with pre-selected framework
2266
+ const framework = installationMode.split(':')[1];
2267
+ const wizard = new ManualFrameworkInstallationWizard(apiKey, projectPath, framework);
2268
+ result = yield wizard.install();
2269
+ }
2270
+ else {
2271
+ const wizard = new AutoInstallationWizard(apiKey, projectPath);
2272
+ result = yield wizard.install();
2273
+ }
2274
+ // Display results
2275
+ this.displayResults(result, installationMode);
2276
+ }
2277
+ catch (error) {
2278
+ console.error('❌ Error:', error instanceof Error ? error.message : error);
2279
+ process.exit(1);
2280
+ }
2281
+ finally {
2282
+ this.rl.close();
2283
+ }
2284
+ });
2285
+ }
2286
+ getApiKey() {
2287
+ return __awaiter(this, void 0, void 0, function* () {
2288
+ if (this.options.apiKey) {
2289
+ return this.options.apiKey;
2290
+ }
2291
+ return new Promise((resolve) => {
2292
+ this.rl.question('Enter your HumanBehavior API key: ', (answer) => {
2293
+ resolve(answer.trim());
2294
+ });
2295
+ });
2296
+ });
2297
+ }
2298
+ chooseInstallationMode() {
2299
+ return __awaiter(this, void 0, void 0, function* () {
2300
+ if (this.options.manual && this.options.framework) {
2301
+ return `manual:${this.options.framework}`;
2302
+ }
2303
+ if (this.options.useAI !== undefined) {
2304
+ return this.options.useAI ? 'ai' : 'traditional';
2305
+ }
2306
+ console.log('🤖 Choose installation mode:');
2307
+ console.log('1. Manual AI-Enhanced (recommended) - Choose your framework and use AI for optimization');
2308
+ console.log('2. Traditional - Standard framework detection and installation');
2309
+ console.log('3. Browser - Browser-based AI detection and code generation\n');
2310
+ return new Promise((resolve) => {
2311
+ this.rl.question('Select mode (1-3, default: 1): ', (answer) => {
2312
+ const choice = answer.trim() || '1';
2313
+ if (choice === '1')
2314
+ resolve('manual');
2315
+ else if (choice === '2')
2316
+ resolve('traditional');
2317
+ else if (choice === '3')
2318
+ resolve('browser');
2319
+ else
2320
+ resolve('manual');
2321
+ });
2322
+ });
2323
+ });
2324
+ }
2325
+ confirmInstallation(projectPath, installationMode) {
2326
+ return __awaiter(this, void 0, void 0, function* () {
2327
+ console.log(`📁 Project path: ${projectPath}`);
2328
+ console.log(`🤖 Installation mode: ${this.getInstallationModeDisplay(installationMode)}`);
2329
+ console.log('⚠️ This will modify your codebase to integrate HumanBehavior SDK.');
2330
+ console.log(' The following changes will be made:');
2331
+ console.log(' - Install humanbehavior-js package');
2332
+ console.log(' - Analyze code patterns with AI (if enabled)');
2333
+ console.log(' - Modify your main app file');
2334
+ console.log(' - Create environment files');
2335
+ console.log(' - Add AI-optimized SDK initialization code\n');
2336
+ return new Promise((resolve) => {
2337
+ this.rl.question('Continue with installation? (y/n): ', (answer) => {
2338
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
2339
+ });
2340
+ });
2341
+ });
2342
+ }
2343
+ getInstallationModeDisplay(mode) {
2344
+ if (mode === 'manual')
2345
+ return 'Manual AI-Enhanced';
2346
+ if (mode === 'traditional')
2347
+ return 'Traditional';
2348
+ if (mode.startsWith('manual:')) {
2349
+ const framework = mode.split(':')[1];
2350
+ return `Manual AI-Enhanced (${framework})`;
2351
+ }
2352
+ if (mode === 'browser')
2353
+ return 'Browser';
2354
+ return 'Unknown';
2355
+ }
2356
+ chooseFramework() {
2357
+ return __awaiter(this, void 0, void 0, function* () {
2358
+ console.log('\n🎯 Choose your framework:');
2359
+ console.log('1. Vanilla JS (HTML)');
2360
+ console.log('2. React');
2361
+ console.log('3. Next.js');
2362
+ console.log('4. Vue');
2363
+ console.log('5. Nuxt');
2364
+ console.log('6. Angular');
2365
+ console.log('7. Svelte');
2366
+ console.log('8. Remix');
2367
+ console.log('9. Node.js');
2368
+ console.log('10. Other (Auto-detect)\n');
2369
+ return new Promise((resolve) => {
2370
+ this.rl.question('Select framework (1-10, default: 1): ', (answer) => {
2371
+ const choice = answer.trim() || '1';
2372
+ const frameworks = ['vanilla', 'react', 'nextjs', 'vue', 'nuxt', 'angular', 'svelte', 'remix', 'node', 'auto'];
2373
+ const index = parseInt(choice) - 1;
2374
+ resolve(frameworks[index] || 'vanilla');
2375
+ });
2376
+ });
2377
+ });
2378
+ }
2379
+ displayResults(result, installationMode) {
2380
+ if (result.success) {
2381
+ console.log('\n✅ Installation completed successfully!');
2382
+ if (installationMode === 'ai' && result.aiAnalysis) {
2383
+ console.log(`🎯 AI Analysis Results:`);
2384
+ console.log(` Framework: ${result.aiAnalysis.framework.name} (confidence: ${Math.round(result.aiAnalysis.confidence * 100)}%)`);
2385
+ console.log(` Integration Strategy: ${result.aiAnalysis.integrationStrategy}`);
2386
+ console.log(` Compatibility Mode: ${result.aiAnalysis.compatibilityMode}`);
2387
+ if (result.aiAnalysis.patterns.length > 0) {
2388
+ console.log(` Detected Patterns: ${result.aiAnalysis.patterns.length} patterns`);
2389
+ }
2390
+ if (result.aiAnalysis.recommendations.length > 0) {
2391
+ console.log(` AI Recommendations:`);
2392
+ result.aiAnalysis.recommendations.forEach((rec) => {
2393
+ console.log(` • ${rec}`);
2394
+ });
2395
+ }
2396
+ }
2397
+ else {
2398
+ console.log(`📦 Framework detected: ${result.framework.name}`);
2399
+ }
2400
+ if (result.framework.bundler) {
2401
+ console.log(`🔧 Bundler: ${result.framework.bundler}`);
2402
+ }
2403
+ if (result.framework.packageManager) {
2404
+ console.log(`📋 Package Manager: ${result.framework.packageManager}`);
2405
+ }
2406
+ console.log('\n📝 Changes made:');
2407
+ result.modifications.forEach((mod) => {
2408
+ console.log(` ${mod.action === 'create' ? '➕' : '✏️'} ${mod.description}`);
2409
+ console.log(` ${mod.filePath}`);
2410
+ });
2411
+ console.log('\n🎯 Next steps:');
2412
+ result.nextSteps.forEach((step) => {
2413
+ console.log(` ${step}`);
2414
+ });
2415
+ if (installationMode === 'ai' && result.learningData) {
2416
+ console.log('\n🧠 Learning Data:');
2417
+ console.log(` Framework: ${result.learningData.framework}`);
2418
+ console.log(` Patterns: ${result.learningData.patterns.length} detected`);
2419
+ console.log(` Success: ${result.learningData.success ? 'Yes' : 'No'}`);
2420
+ }
2421
+ console.log('\n🚀 Your app is now ready to track user behavior!');
2422
+ console.log('📊 View sessions in your HumanBehavior dashboard');
2423
+ }
2424
+ else {
2425
+ console.log('\n❌ Installation failed:');
2426
+ result.errors.forEach((error) => {
2427
+ console.log(` ${error}`);
2428
+ });
2429
+ console.log('\n💡 Try running with --help for more options');
2430
+ }
2431
+ }
2432
+ }
2433
+ // CLI argument parsing
2434
+ function parseArgs$1() {
2435
+ const args = process.argv.slice(2);
2436
+ const options = {};
2437
+ for (let i = 0; i < args.length; i++) {
2438
+ const arg = args[i];
2439
+ if (arg === '--yes' || arg === '-y') {
2440
+ options.yes = true;
2441
+ }
2442
+ else if (arg === '--dry-run' || arg === '-d') {
2443
+ options.dryRun = true;
2444
+ }
2445
+ else if (arg === '--project' || arg === '-p') {
2446
+ options.projectPath = args[i + 1];
2447
+ i++;
2448
+ }
2449
+ else if (arg === '--traditional' || arg === '-t') {
2450
+ options.useAI = false;
2451
+ }
2452
+ else if (arg === '--browser' || arg === '-b') {
2453
+ options.browser = true;
2454
+ }
2455
+ else if (arg === '--manual' || arg === '-m') {
2456
+ options.manual = true;
2457
+ }
2458
+ else if (arg === '--framework' || arg === '-f') {
2459
+ options.framework = args[i + 1];
2460
+ i++;
2461
+ }
2462
+ else if (arg === '--help' || arg === '-h') {
2463
+ showHelp$1();
2464
+ process.exit(0);
2465
+ }
2466
+ else if (!options.apiKey) {
2467
+ options.apiKey = arg;
2468
+ }
2469
+ }
2470
+ return options;
2471
+ }
2472
+ function showHelp$1() {
2473
+ console.log(`
2474
+ AI-Enhanced HumanBehavior SDK Auto-Installation CLI
2475
+
2476
+ Usage: npx humanbehavior-js ai-auto-install [api-key] [options]
2477
+
2478
+ This tool uses AI to intelligently detect frameworks, analyze code patterns,
2479
+ and generate optimal integration code that's both future-proof and backward-compatible.
2480
+
2481
+ Arguments:
2482
+ api-key Your HumanBehavior API key
2483
+
2484
+ Options:
2485
+ -y, --yes Skip all prompts and use defaults
2486
+ -d, --dry-run Show what would be changed without making changes
2487
+ -p, --project <path> Project directory (default: current directory)
2488
+ -t, --traditional Force traditional installation mode
2489
+ -b, --browser Browser-based AI installation
2490
+ -m, --manual Manual framework selection
2491
+ -f, --framework <f> Specify framework for manual mode
2492
+ -h, --help Show this help message
2493
+
2494
+ Installation Modes:
2495
+ 1. Manual AI-Enhanced (default): Choose your framework and use AI for optimization
2496
+ 2. Traditional: Standard framework detection and installation
2497
+ 3. Browser: Browser-based AI detection and code generation
2498
+
2499
+ Examples:
2500
+ npx humanbehavior-js ai-auto-install your-api-key
2501
+ npx humanbehavior-js ai-auto-install your-api-key --manual --framework react
2502
+ npx humanbehavior-js ai-auto-install your-api-key --traditional
2503
+ npx humanbehavior-js ai-auto-install your-api-key --browser
2504
+
2505
+ Supported Frameworks:
2506
+ ✅ React (CRA, Vite, Webpack)
2507
+ ✅ Next.js (App Router, Pages Router)
2508
+ ✅ Vue (Vue CLI, Vite)
2509
+ ✅ Angular
2510
+ ✅ Svelte (SvelteKit, Vite)
2511
+ ✅ Remix
2512
+ ✅ Vanilla JS/TS
2513
+ ✅ Node.js (CommonJS & ESM)
2514
+
2515
+ AI Features:
2516
+ 🔍 Intelligent framework detection beyond package.json
2517
+ 📊 Code pattern analysis and optimization
2518
+ 🔄 Future-proof integration strategies
2519
+ 🔙 Backward compatibility with legacy frameworks
2520
+ 🧠 Learning from installation patterns
2521
+ ⚡ Adaptive code generation for new frameworks
2522
+ 🔧 Smart conflict resolution
2523
+ 📈 Performance optimization recommendations
2524
+
2525
+ The AI-enhanced tool will:
2526
+ 1. 🔍 Analyze your codebase with AI to detect patterns
2527
+ 2. 🎯 Determine optimal integration strategy
2528
+ 3. 📦 Install the humanbehavior-js package
2529
+ 4. ✏️ Generate AI-optimized integration code
2530
+ 5. 🔧 Apply modifications with conflict resolution
2531
+ 6. 🧠 Learn from the installation for future improvements
2532
+ 7. 🚀 Make your app ready to track user behavior
2533
+ `);
2534
+ }
2535
+ // Main execution
2536
+ const options$1 = parseArgs$1();
2537
+ // Check if we have enough arguments (api-key is required)
2538
+ if (process.argv.length < 3 || process.argv.includes('--help') || process.argv.includes('-h')) {
2539
+ showHelp$1();
2540
+ process.exit(0);
2541
+ }
2542
+ const cli$1 = new AIAutoInstallCLI(options$1);
2543
+ cli$1.run().catch((error) => {
2544
+ console.error('❌ Fatal error:', error);
2545
+ process.exit(1);
2546
+ });
2547
+
2548
+ /**
2549
+ * HumanBehavior SDK Auto-Installation CLI
2550
+ *
2551
+ * Usage: npx humanbehavior-js auto-install [api-key]
2552
+ *
2553
+ * This tool automatically detects the user's framework and modifies their codebase
2554
+ * to integrate the SDK with minimal user intervention.
2555
+ */
2556
+ class AutoInstallCLI {
2557
+ constructor(options) {
2558
+ this.options = options;
2559
+ this.rl = readline__namespace.createInterface({
2560
+ input: process.stdin,
2561
+ output: process.stdout
2562
+ });
2563
+ }
2564
+ run() {
2565
+ return __awaiter(this, void 0, void 0, function* () {
2566
+ console.log('🚀 HumanBehavior SDK Auto-Installation');
2567
+ console.log('=====================================\n');
2568
+ try {
2569
+ // Get API key
2570
+ const apiKey = yield this.getApiKey();
2571
+ if (!apiKey) {
2572
+ console.error('❌ API key is required');
2573
+ process.exit(1);
2574
+ }
2575
+ // Get project path
2576
+ const projectPath = this.options.projectPath || process.cwd();
2577
+ // Confirm installation
2578
+ if (!this.options.yes) {
2579
+ const confirmed = yield this.confirmInstallation(projectPath);
2580
+ if (!confirmed) {
2581
+ console.log('Installation cancelled.');
2582
+ process.exit(0);
2583
+ }
2584
+ }
2585
+ // Run auto-installation
2586
+ console.log('🔍 Detecting your project setup...');
2587
+ const wizard = new AutoInstallationWizard(apiKey, projectPath);
2588
+ const result = yield wizard.install();
2589
+ // Display results
2590
+ this.displayResults(result);
2591
+ }
2592
+ catch (error) {
2593
+ console.error('❌ Error:', error instanceof Error ? error.message : error);
2594
+ process.exit(1);
2595
+ }
2596
+ finally {
2597
+ this.rl.close();
2598
+ }
2599
+ });
2600
+ }
2601
+ getApiKey() {
2602
+ return __awaiter(this, void 0, void 0, function* () {
2603
+ if (this.options.apiKey) {
2604
+ return this.options.apiKey;
2605
+ }
2606
+ return new Promise((resolve) => {
2607
+ this.rl.question('Enter your HumanBehavior API key: ', (answer) => {
2608
+ resolve(answer.trim());
2609
+ });
2610
+ });
2611
+ });
2612
+ }
2613
+ confirmInstallation(projectPath) {
2614
+ return __awaiter(this, void 0, void 0, function* () {
2615
+ console.log(`📁 Project path: ${projectPath}`);
2616
+ console.log('⚠️ This will modify your codebase to integrate HumanBehavior SDK.');
2617
+ console.log(' The following changes will be made:');
2618
+ console.log(' - Install humanbehavior-js package');
2619
+ console.log(' - Modify your main app file');
2620
+ console.log(' - Create environment files');
2621
+ console.log(' - Add SDK initialization code\n');
2622
+ return new Promise((resolve) => {
2623
+ this.rl.question('Continue with auto-installation? (y/n): ', (answer) => {
2624
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
2625
+ });
2626
+ });
2627
+ });
2628
+ }
2629
+ displayResults(result) {
2630
+ if (result.success) {
2631
+ console.log('\n✅ Installation completed successfully!');
2632
+ console.log(`📦 Framework detected: ${result.framework.name}`);
2633
+ if (result.framework.bundler) {
2634
+ console.log(`🔧 Bundler: ${result.framework.bundler}`);
2635
+ }
2636
+ if (result.framework.packageManager) {
2637
+ console.log(`📋 Package Manager: ${result.framework.packageManager}`);
2638
+ }
2639
+ console.log('\n📝 Changes made:');
2640
+ result.modifications.forEach((mod) => {
2641
+ console.log(` ${mod.action === 'create' ? '➕' : '✏️'} ${mod.description}`);
2642
+ console.log(` ${mod.filePath}`);
2643
+ });
2644
+ console.log('\n🎯 Next steps:');
2645
+ result.nextSteps.forEach((step) => {
2646
+ console.log(` ${step}`);
2647
+ });
2648
+ console.log('\n🚀 Your app is now ready to track user behavior!');
2649
+ console.log('📊 View sessions in your HumanBehavior dashboard');
2650
+ }
2651
+ else {
2652
+ console.log('\n❌ Installation failed:');
2653
+ result.errors.forEach((error) => {
2654
+ console.log(` ${error}`);
2655
+ });
2656
+ console.log('\n💡 Try running with --help for more options');
2657
+ }
2658
+ }
2659
+ }
2660
+ // CLI argument parsing
2661
+ function parseArgs() {
2662
+ const args = process.argv.slice(2);
2663
+ const options = {};
2664
+ for (let i = 0; i < args.length; i++) {
2665
+ const arg = args[i];
2666
+ if (arg === '--yes' || arg === '-y') {
2667
+ options.yes = true;
2668
+ }
2669
+ else if (arg === '--dry-run' || arg === '-d') {
2670
+ options.dryRun = true;
2671
+ }
2672
+ else if (arg === '--project' || arg === '-p') {
2673
+ options.projectPath = args[i + 1];
2674
+ i++;
2675
+ }
2676
+ else if (arg === '--help' || arg === '-h') {
2677
+ showHelp();
2678
+ process.exit(0);
2679
+ }
2680
+ else if (!options.apiKey) {
2681
+ options.apiKey = arg;
2682
+ }
2683
+ }
2684
+ return options;
2685
+ }
2686
+ function showHelp() {
2687
+ console.log(`
2688
+ HumanBehavior SDK Auto-Installation CLI
2689
+
2690
+ Usage: npx humanbehavior-js [api-key] [options]
2691
+
2692
+ This tool automatically detects your project's framework and modifies your codebase
2693
+ to integrate the HumanBehavior SDK with minimal user intervention.
2694
+
2695
+ Arguments:
2696
+ api-key Your HumanBehavior API key
2697
+
2698
+ Options:
2699
+ -y, --yes Skip all prompts and use defaults
2700
+ -d, --dry-run Show what would be changed without making changes
2701
+ -p, --project <path> Project directory (default: current directory)
2702
+ -h, --help Show this help message
2703
+
2704
+ Examples:
2705
+ npx humanbehavior-js your-api-key
2706
+ npx humanbehavior-js your-api-key --yes
2707
+ npx humanbehavior-js your-api-key -p /path/to/project
2708
+
2709
+ Supported Frameworks:
2710
+ ✅ React (CRA, Vite, Webpack)
2711
+ ✅ Next.js (App Router, Pages Router)
2712
+ ✅ Vue (Vue CLI, Vite)
2713
+ ✅ Angular
2714
+ ✅ Svelte (SvelteKit, Vite)
2715
+ ✅ Remix
2716
+ ✅ Vanilla JS/TS
2717
+ ✅ Node.js (CommonJS & ESM)
2718
+
2719
+ The tool will:
2720
+ 1. 🔍 Auto-detect your project's framework and setup
2721
+ 2. 📦 Install the humanbehavior-js package
2722
+ 3. ✏️ Modify your codebase to integrate the SDK
2723
+ 4. 🔧 Create environment files with your API key
2724
+ 5. 🚀 Make your app ready to track user behavior
2725
+ `);
2726
+ }
2727
+ // Main execution
2728
+ const options = parseArgs();
2729
+ // Check if we have enough arguments (api-key is required)
2730
+ if (process.argv.length < 3 || process.argv.includes('--help') || process.argv.includes('-h')) {
2731
+ showHelp();
2732
+ process.exit(0);
2733
+ }
2734
+ const cli = new AutoInstallCLI(options);
2735
+ cli.run().catch((error) => {
2736
+ console.error('❌ Fatal error:', error);
2737
+ process.exit(1);
2738
+ });
2739
+
2740
+ /**
2741
+ * Centralized AI Service Implementation
2742
+ *
2743
+ * This service runs on your backend infrastructure and provides AI-powered
2744
+ * code analysis without requiring users to provide their own API keys.
2745
+ *
2746
+ * The service can be deployed as:
2747
+ * - AWS Lambda function
2748
+ * - Docker container
2749
+ * - Express.js server
2750
+ * - Cloud function
2751
+ */
2752
+ /**
2753
+ * Centralized AI Service Implementation
2754
+ * This runs on your backend infrastructure
2755
+ */
2756
+ class CentralizedAIService {
2757
+ constructor(config) {
2758
+ this.cache = new Map();
2759
+ this.config = Object.assign({ openaiModel: 'gpt-4', maxTokens: 2000, temperature: 0.3, enableCaching: true, cacheTTL: 3600 }, config);
2760
+ this.initializeOpenAI();
2761
+ }
2762
+ /**
2763
+ * Initialize OpenAI client
2764
+ */
2765
+ initializeOpenAI() {
2766
+ try {
2767
+ // Import OpenAI dynamically to avoid bundling issues
2768
+ const { OpenAI } = require('openai');
2769
+ this.openai = new OpenAI({
2770
+ apiKey: this.config.openaiApiKey
2771
+ });
2772
+ }
2773
+ catch (error) {
2774
+ console.warn('OpenAI not available, falling back to heuristic analysis');
2775
+ this.openai = null;
2776
+ }
2777
+ }
2778
+ /**
2779
+ * Analyze code patterns using AI
2780
+ */
2781
+ analyzeCodePatterns(codeSamples) {
2782
+ return __awaiter(this, void 0, void 0, function* () {
2783
+ const request = {
2784
+ codeSamples,
2785
+ timestamp: new Date().toISOString()
2786
+ };
2787
+ // Check cache first
2788
+ const cacheKey = this.generateCacheKey(request);
2789
+ if (this.config.enableCaching) {
2790
+ const cached = this.cache.get(cacheKey);
2791
+ if (cached && this.isCacheValid(cached.timestamp)) {
2792
+ return cached.analysis;
2793
+ }
2794
+ }
2795
+ const analysis = yield this.performAIAnalysis(request);
2796
+ // Cache the result
2797
+ if (this.config.enableCaching) {
2798
+ this.cache.set(cacheKey, {
2799
+ analysis,
2800
+ timestamp: Date.now()
2801
+ });
2802
+ }
2803
+ return analysis;
2804
+ });
2805
+ }
2806
+ /**
2807
+ * Resolve conflicts using AI
2808
+ */
2809
+ resolveConflicts(conflicts, framework) {
2810
+ return __awaiter(this, void 0, void 0, function* () {
2811
+ var _a, _b;
2812
+ const request = {
2813
+ conflicts,
2814
+ framework,
2815
+ codeContext: 'HumanBehavior SDK integration'
2816
+ };
2817
+ if (!this.openai) {
2818
+ return this.resolveConflictsHeuristic(conflicts, framework);
2819
+ }
2820
+ try {
2821
+ const prompt = this.buildConflictResolutionPrompt(request);
2822
+ const response = yield this.openai.chat.completions.create({
2823
+ model: this.config.openaiModel,
2824
+ messages: [
2825
+ {
2826
+ role: 'system',
2827
+ content: 'You are an expert at resolving code integration conflicts. Provide specific resolution strategies.'
2828
+ },
2829
+ {
2830
+ role: 'user',
2831
+ content: prompt
2832
+ }
2833
+ ],
2834
+ max_tokens: this.config.maxTokens,
2835
+ temperature: this.config.temperature
2836
+ });
2837
+ const content = (_b = (_a = response.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content;
2838
+ if (content && typeof content === 'string') {
2839
+ return this.parseConflictResolutions(content);
2840
+ }
2841
+ return [];
2842
+ }
2843
+ catch (error) {
2844
+ console.warn('AI conflict resolution failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
2845
+ }
2846
+ return this.resolveConflictsHeuristic(conflicts, framework);
2847
+ });
2848
+ }
2849
+ /**
2850
+ * Generate optimizations using AI
2851
+ */
2852
+ generateOptimizations(framework, patterns) {
2853
+ return __awaiter(this, void 0, void 0, function* () {
2854
+ var _a, _b;
2855
+ const request = {
2856
+ framework,
2857
+ patterns,
2858
+ projectContext: 'HumanBehavior SDK integration'
2859
+ };
2860
+ if (!this.openai) {
2861
+ return this.generateOptimizationsHeuristic(framework, patterns);
2862
+ }
2863
+ try {
2864
+ const prompt = this.buildOptimizationPrompt(request);
2865
+ const response = yield this.openai.chat.completions.create({
2866
+ model: this.config.openaiModel,
2867
+ messages: [
2868
+ {
2869
+ role: 'system',
2870
+ content: 'You are an expert at optimizing code integration. Provide specific, actionable recommendations.'
2871
+ },
2872
+ {
2873
+ role: 'user',
2874
+ content: prompt
2875
+ }
2876
+ ],
2877
+ max_tokens: this.config.maxTokens,
2878
+ temperature: this.config.temperature
2879
+ });
2880
+ const content = (_b = (_a = response.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content;
2881
+ if (content) {
2882
+ return this.parseOptimizations(content);
2883
+ }
2884
+ }
2885
+ catch (error) {
2886
+ console.warn('AI optimization generation failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
2887
+ }
2888
+ return this.generateOptimizationsHeuristic(framework, patterns);
2889
+ });
2890
+ }
2891
+ /**
2892
+ * Perform AI analysis
2893
+ */
2894
+ performAIAnalysis(request) {
2895
+ return __awaiter(this, void 0, void 0, function* () {
2896
+ var _a, _b;
2897
+ if (!this.openai) {
2898
+ return this.performHeuristicAnalysis(request);
2899
+ }
2900
+ try {
2901
+ const prompt = this.buildAnalysisPrompt(request);
2902
+ const response = yield this.openai.chat.completions.create({
2903
+ model: this.config.openaiModel,
2904
+ messages: [
2905
+ {
2906
+ role: 'system',
2907
+ content: 'You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format.'
2908
+ },
2909
+ {
2910
+ role: 'user',
2911
+ content: prompt
2912
+ }
2913
+ ],
2914
+ max_tokens: this.config.maxTokens,
2915
+ temperature: this.config.temperature,
2916
+ response_format: { type: 'json_object' }
2917
+ });
2918
+ const content = (_b = (_a = response.choices[0]) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.content;
2919
+ if (content) {
2920
+ return this.parseAnalysisResult(content);
2921
+ }
2922
+ }
2923
+ catch (error) {
2924
+ console.warn('AI analysis failed, using heuristic approach:', error instanceof Error ? error.message : 'Unknown error');
2925
+ }
2926
+ return this.performHeuristicAnalysis(request);
2927
+ });
2928
+ }
2929
+ /**
2930
+ * Build analysis prompt
2931
+ */
2932
+ buildAnalysisPrompt(request) {
2933
+ return `Analyze these code samples to determine the framework and integration strategy:
2934
+
2935
+ ${request.codeSamples.join('\n\n')}
2936
+
2937
+ Provide analysis in JSON format with:
2938
+ - framework: { name, type, confidence (0-1) }
2939
+ - patterns: array of detected patterns
2940
+ - conflicts: array of potential conflicts
2941
+ - recommendations: array of integration recommendations
2942
+ - integrationStrategy: "provider" | "plugin" | "module" | "script" | "standalone"
2943
+ - compatibilityMode: "modern" | "legacy" | "hybrid"
2944
+
2945
+ Focus on:
2946
+ 1. Framework detection beyond package.json
2947
+ 2. Code patterns and architecture
2948
+ 3. Integration compatibility
2949
+ 4. Future-proof strategies
2950
+ 5. Backward compatibility needs
2951
+
2952
+ Respond with valid JSON only.`;
2953
+ }
2954
+ /**
2955
+ * Build conflict resolution prompt
2956
+ */
2957
+ buildConflictResolutionPrompt(request) {
2958
+ return `Resolve these integration conflicts for ${request.framework.name}:
2959
+
2960
+ Conflicts: ${request.conflicts.join(', ')}
2961
+
2962
+ Framework: ${request.framework.name} (${request.framework.type})
2963
+ Context: ${request.codeContext}
2964
+
2965
+ Provide specific resolution strategies for each conflict. Options:
2966
+ - update_existing_integration: Update existing code
2967
+ - merge_providers: Merge multiple providers
2968
+ - hybrid_module_support: Support both module systems
2969
+ - skip_conflict: Skip the modification
2970
+ - custom_resolution: Custom resolution strategy
2971
+
2972
+ Respond with a JSON array of resolution strategies.`;
2973
+ }
2974
+ /**
2975
+ * Build optimization prompt
2976
+ */
2977
+ buildOptimizationPrompt(request) {
2978
+ return `Generate optimizations for ${request.framework.name} integration:
2979
+
2980
+ Framework: ${request.framework.name} (${request.framework.type})
2981
+ Patterns: ${request.patterns.join(', ')}
2982
+ Context: ${request.projectContext}
2983
+
2984
+ Provide specific, actionable optimization recommendations for:
2985
+ 1. Performance improvements
2986
+ 2. Error handling
2987
+ 3. Code organization
2988
+ 4. Future-proofing
2989
+ 5. Backward compatibility
2990
+
2991
+ Respond with a JSON array of optimization recommendations.`;
2992
+ }
2993
+ /**
2994
+ * Parse analysis result
2995
+ */
2996
+ parseAnalysisResult(content) {
2997
+ try {
2998
+ const result = JSON.parse(content);
2999
+ return {
3000
+ framework: result.framework || { name: 'vanilla', type: 'vanilla' },
3001
+ confidence: result.confidence || 0.5,
3002
+ patterns: result.patterns || [],
3003
+ conflicts: result.conflicts || [],
3004
+ recommendations: result.recommendations || [],
3005
+ integrationStrategy: result.integrationStrategy || 'script',
3006
+ compatibilityMode: result.compatibilityMode || 'modern'
3007
+ };
3008
+ }
3009
+ catch (error) {
3010
+ console.warn('Failed to parse AI analysis result:', error);
3011
+ return this.getDefaultAnalysis();
3012
+ }
3013
+ }
3014
+ /**
3015
+ * Parse conflict resolutions
3016
+ */
3017
+ parseConflictResolutions(content) {
3018
+ try {
3019
+ const result = JSON.parse(content);
3020
+ return Array.isArray(result) ? result : [];
3021
+ }
3022
+ catch (error) {
3023
+ console.warn('Failed to parse conflict resolutions:', error);
3024
+ return [];
3025
+ }
3026
+ }
3027
+ /**
3028
+ * Parse optimizations
3029
+ */
3030
+ parseOptimizations(content) {
3031
+ try {
3032
+ const result = JSON.parse(content);
3033
+ return Array.isArray(result) ? result : [];
3034
+ }
3035
+ catch (error) {
3036
+ console.warn('Failed to parse optimizations:', error);
3037
+ return [];
3038
+ }
3039
+ }
3040
+ /**
3041
+ * Heuristic analysis fallback
3042
+ */
3043
+ performHeuristicAnalysis(request) {
3044
+ const patterns = request.codeSamples.join(' ').toLowerCase();
3045
+ // Framework detection
3046
+ let framework = { name: 'vanilla', type: 'vanilla' };
3047
+ let confidence = 0.5;
3048
+ if (patterns.includes('react')) {
3049
+ framework = { name: 'react', type: 'react' };
3050
+ confidence = 0.9;
3051
+ }
3052
+ else if (patterns.includes('vue')) {
3053
+ framework = { name: 'vue', type: 'vue' };
3054
+ confidence = 0.9;
3055
+ }
3056
+ else if (patterns.includes('angular')) {
3057
+ framework = { name: 'angular', type: 'angular' };
3058
+ confidence = 0.9;
3059
+ }
3060
+ else if (patterns.includes('svelte')) {
3061
+ framework = { name: 'svelte', type: 'svelte' };
3062
+ confidence = 0.9;
3063
+ }
3064
+ else if (patterns.includes('next')) {
3065
+ framework = { name: 'nextjs', type: 'nextjs' };
3066
+ confidence = 0.9;
3067
+ }
3068
+ else if (patterns.includes('nuxt')) {
3069
+ framework = { name: 'nuxt', type: 'nuxt' };
3070
+ confidence = 0.9;
3071
+ }
3072
+ // Integration strategy
3073
+ let integrationStrategy = 'script';
3074
+ if (framework.type === 'react' || framework.type === 'nextjs') {
3075
+ integrationStrategy = 'provider';
3076
+ }
3077
+ else if (framework.type === 'vue') {
3078
+ integrationStrategy = 'plugin';
3079
+ }
3080
+ else if (framework.type === 'angular') {
3081
+ integrationStrategy = 'module';
3082
+ }
3083
+ // Compatibility mode
3084
+ let compatibilityMode = 'modern';
3085
+ if (patterns.includes('require(') || patterns.includes('var ')) {
3086
+ compatibilityMode = 'legacy';
3087
+ }
3088
+ return {
3089
+ framework,
3090
+ confidence,
3091
+ patterns: request.codeSamples,
3092
+ conflicts: [],
3093
+ recommendations: [],
3094
+ integrationStrategy,
3095
+ compatibilityMode
3096
+ };
3097
+ }
3098
+ /**
3099
+ * Heuristic conflict resolution
3100
+ */
3101
+ resolveConflictsHeuristic(conflicts, framework) {
3102
+ const resolutions = [];
3103
+ for (const conflict of conflicts) {
3104
+ switch (conflict) {
3105
+ case 'existing_humanbehavior_code':
3106
+ resolutions.push('update_existing_integration');
3107
+ break;
3108
+ case 'existing_provider':
3109
+ resolutions.push('merge_providers');
3110
+ break;
3111
+ case 'module_system_conflict':
3112
+ resolutions.push('hybrid_module_support');
3113
+ break;
3114
+ default:
3115
+ resolutions.push('skip_conflict');
3116
+ }
3117
+ }
3118
+ return resolutions;
3119
+ }
3120
+ /**
3121
+ * Heuristic optimization generation
3122
+ */
3123
+ generateOptimizationsHeuristic(framework, patterns) {
3124
+ const optimizations = [];
3125
+ switch (framework.type) {
3126
+ case 'react':
3127
+ optimizations.push('Use React.memo for performance optimization');
3128
+ optimizations.push('Implement error boundaries for better error tracking');
3129
+ optimizations.push('Consider using React.lazy for code splitting');
3130
+ break;
3131
+ case 'vue':
3132
+ optimizations.push('Use Vue 3 Composition API for better performance');
3133
+ optimizations.push('Implement proper error handling in components');
3134
+ optimizations.push('Consider using Vue Router for navigation tracking');
3135
+ break;
3136
+ case 'angular':
3137
+ optimizations.push('Use Angular standalone components for better tree-shaking');
3138
+ optimizations.push('Implement proper error handling with ErrorHandler');
3139
+ optimizations.push('Consider using Angular signals for state management');
3140
+ break;
3141
+ default:
3142
+ optimizations.push('Enable performance tracking');
3143
+ optimizations.push('Implement error tracking');
3144
+ optimizations.push('Consider progressive enhancement');
3145
+ }
3146
+ return optimizations;
3147
+ }
3148
+ /**
3149
+ * Generate cache key
3150
+ */
3151
+ generateCacheKey(request) {
3152
+ const content = JSON.stringify(request);
3153
+ return Buffer.from(content).toString('base64').substring(0, 32);
3154
+ }
3155
+ /**
3156
+ * Check if cache is valid
3157
+ */
3158
+ isCacheValid(timestamp) {
3159
+ const now = Date.now();
3160
+ const ttl = (this.config.cacheTTL || 3600) * 1000; // Convert to milliseconds
3161
+ return (now - timestamp) < ttl;
3162
+ }
3163
+ /**
3164
+ * Get default analysis
3165
+ */
3166
+ getDefaultAnalysis() {
3167
+ return {
3168
+ framework: { name: 'vanilla', type: 'vanilla' },
3169
+ confidence: 0.5,
3170
+ patterns: [],
3171
+ conflicts: [],
3172
+ recommendations: [],
3173
+ integrationStrategy: 'script',
3174
+ compatibilityMode: 'modern'
3175
+ };
3176
+ }
3177
+ /**
3178
+ * Get service statistics
3179
+ */
3180
+ getStats() {
3181
+ return {
3182
+ cacheSize: this.cache.size,
3183
+ config: {
3184
+ model: this.config.openaiModel,
3185
+ maxTokens: this.config.maxTokens,
3186
+ temperature: this.config.temperature,
3187
+ caching: this.config.enableCaching
3188
+ },
3189
+ openaiAvailable: !!this.openai
3190
+ };
3191
+ }
3192
+ /**
3193
+ * Clear cache
3194
+ */
3195
+ clearCache() {
3196
+ this.cache.clear();
3197
+ }
3198
+ }
3199
+
3200
+ exports.AIAutoInstallCLI = AIAutoInstallCLI;
3201
+ exports.AIBrowserInstallationWizard = AIBrowserInstallationWizard;
3202
+ exports.AIEnhancedInstallationWizard = AIEnhancedInstallationWizard;
3203
+ exports.AutoInstallCLI = AutoInstallCLI;
3204
+ exports.AutoInstallationWizard = AutoInstallationWizard;
3205
+ exports.CentralizedAIService = CentralizedAIService;
3206
+ exports.InstallWizard = AutoInstallationWizard;
3207
+ exports.RemoteAIService = RemoteAIService;
3208
+ //# sourceMappingURL=index.cjs.map