humanbehavior-js 0.4.16 → 0.4.18

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 (89) hide show
  1. package/dist/cjs/wizard/index.cjs +6 -8
  2. package/dist/cjs/wizard/index.cjs.map +1 -1
  3. package/dist/cli/ai-auto-install.js +6 -8
  4. package/dist/cli/ai-auto-install.js.map +1 -1
  5. package/dist/esm/wizard/index.js +6 -8
  6. package/dist/esm/wizard/index.js.map +1 -1
  7. package/package/WIZARD_USAGE_GUIDE.md +381 -0
  8. package/package/canvas-recording-demo.html +143 -0
  9. package/package/clean-console-demo.html +39 -0
  10. package/package/dist/cjs/angular/index.cjs +14354 -0
  11. package/package/dist/cjs/angular/index.cjs.map +1 -0
  12. package/package/dist/cjs/index.cjs +14323 -0
  13. package/package/dist/cjs/index.cjs.map +1 -0
  14. package/package/dist/cjs/install-wizard.cjs +1530 -0
  15. package/package/dist/cjs/install-wizard.cjs.map +1 -0
  16. package/package/dist/cjs/react/index.cjs +14478 -0
  17. package/package/dist/cjs/react/index.cjs.map +1 -0
  18. package/package/dist/cjs/remix/index.cjs +14452 -0
  19. package/package/dist/cjs/remix/index.cjs.map +1 -0
  20. package/package/dist/cjs/svelte/index.cjs +14308 -0
  21. package/package/dist/cjs/svelte/index.cjs.map +1 -0
  22. package/package/dist/cjs/vue/index.cjs +14317 -0
  23. package/package/dist/cjs/vue/index.cjs.map +1 -0
  24. package/package/dist/cjs/wizard/index.cjs +3446 -0
  25. package/package/dist/cjs/wizard/index.cjs.map +1 -0
  26. package/package/dist/cli/ai-auto-install.cjs +57161 -0
  27. package/package/dist/cli/ai-auto-install.cjs.map +1 -0
  28. package/package/dist/cli/ai-auto-install.js +1969 -0
  29. package/package/dist/cli/ai-auto-install.js.map +1 -0
  30. package/package/dist/cli/auto-install.cjs +56352 -0
  31. package/package/dist/cli/auto-install.cjs.map +1 -0
  32. package/package/dist/cli/auto-install.js +1957 -0
  33. package/package/dist/cli/auto-install.js.map +1 -0
  34. package/package/dist/esm/angular/index.js +14350 -0
  35. package/package/dist/esm/angular/index.js.map +1 -0
  36. package/package/dist/esm/index.js +14309 -0
  37. package/package/dist/esm/index.js.map +1 -0
  38. package/package/dist/esm/install-wizard.js +1507 -0
  39. package/package/dist/esm/install-wizard.js.map +1 -0
  40. package/package/dist/esm/react/index.js +14472 -0
  41. package/package/dist/esm/react/index.js.map +1 -0
  42. package/package/dist/esm/remix/index.js +14448 -0
  43. package/package/dist/esm/remix/index.js.map +1 -0
  44. package/package/dist/esm/svelte/index.js +14306 -0
  45. package/package/dist/esm/svelte/index.js.map +1 -0
  46. package/package/dist/esm/vue/index.js +14315 -0
  47. package/package/dist/esm/vue/index.js.map +1 -0
  48. package/package/dist/esm/wizard/index.js +3415 -0
  49. package/package/dist/esm/wizard/index.js.map +1 -0
  50. package/package/dist/index.min.js +2 -0
  51. package/package/dist/index.min.js.map +1 -0
  52. package/package/dist/types/angular/index.d.ts +267 -0
  53. package/package/dist/types/index.d.ts +373 -0
  54. package/package/dist/types/install-wizard.d.ts +156 -0
  55. package/package/dist/types/react/index.d.ts +255 -0
  56. package/package/dist/types/remix/index.d.ts +246 -0
  57. package/package/dist/types/svelte/index.d.ts +232 -0
  58. package/package/dist/types/vue/index.d.ts +15 -0
  59. package/package/dist/types/wizard/index.d.ts +523 -0
  60. package/package/package.json +105 -0
  61. package/package/readme.md +281 -0
  62. package/package/rollup.config.js +422 -0
  63. package/package/simple-demo.html +26 -0
  64. package/package/simple-spa.html +838 -0
  65. package/package/src/angular/index.ts +79 -0
  66. package/package/src/api.ts +376 -0
  67. package/package/src/index.ts +28 -0
  68. package/package/src/react/AutoInstallWizard.tsx +557 -0
  69. package/package/src/react/browser.ts +8 -0
  70. package/package/src/react/index.tsx +308 -0
  71. package/package/src/redact.ts +521 -0
  72. package/package/src/remix/index.ts +16 -0
  73. package/package/src/svelte/index.ts +14 -0
  74. package/package/src/tracker.ts +1319 -0
  75. package/package/src/types/clack.d.ts +31 -0
  76. package/package/src/utils/logger.ts +144 -0
  77. package/package/src/vue/index.ts +29 -0
  78. package/package/src/wizard/README.md +114 -0
  79. package/package/src/wizard/ai/ai-install-wizard.ts +897 -0
  80. package/package/src/wizard/ai/manual-framework-wizard.ts +238 -0
  81. package/package/src/wizard/cli/ai-auto-install.ts +243 -0
  82. package/package/src/wizard/cli/auto-install.ts +224 -0
  83. package/package/src/wizard/core/install-wizard.ts +1744 -0
  84. package/package/src/wizard/index.ts +23 -0
  85. package/package/src/wizard/services/centralized-ai-service.ts +668 -0
  86. package/package/src/wizard/services/remote-ai-service.ts +240 -0
  87. package/package/tsconfig.json +24 -0
  88. package/package.json +1 -1
  89. package/src/wizard/cli/ai-auto-install.ts +4 -6
@@ -0,0 +1,1744 @@
1
+ /**
2
+ * HumanBehavior SDK Auto-Installation Wizard
3
+ *
4
+ * This wizard automatically detects the user's framework and modifies their codebase
5
+ * to integrate the SDK with minimal user intervention.
6
+ */
7
+
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+
11
+ export interface FrameworkInfo {
12
+ name: string;
13
+ type: 'react' | 'vue' | 'angular' | 'svelte' | 'nextjs' | 'nuxt' | 'remix' | 'vanilla' | 'astro' | 'gatsby' | 'node' | 'auto';
14
+ bundler?: 'vite' | 'webpack' | 'esbuild' | 'rollup';
15
+ packageManager?: 'npm' | 'yarn' | 'pnpm';
16
+ hasTypeScript?: boolean;
17
+ hasRouter?: boolean;
18
+ projectRoot?: string;
19
+ version?: string;
20
+ majorVersion?: number;
21
+ features?: {
22
+ hasReact18?: boolean;
23
+ hasVue3?: boolean;
24
+ hasNuxt3?: boolean;
25
+ hasAngularStandalone?: boolean;
26
+ hasNextAppRouter?: boolean;
27
+ hasSvelteKit?: boolean;
28
+ };
29
+ }
30
+
31
+ export interface CodeModification {
32
+ filePath: string;
33
+ action: 'create' | 'modify' | 'append';
34
+ content: string;
35
+ description: string;
36
+ }
37
+
38
+ export interface InstallationResult {
39
+ success: boolean;
40
+ framework: FrameworkInfo;
41
+ modifications: CodeModification[];
42
+ errors: string[];
43
+ nextSteps: string[];
44
+ }
45
+
46
+ export class AutoInstallationWizard {
47
+ protected apiKey: string;
48
+ protected projectRoot: string;
49
+ protected framework: FrameworkInfo | null = null;
50
+
51
+ constructor(apiKey: string, projectRoot: string = process.cwd()) {
52
+ this.apiKey = apiKey;
53
+ this.projectRoot = projectRoot;
54
+ }
55
+
56
+ /**
57
+ * Simple version comparison utility
58
+ */
59
+ private compareVersions(version1: string, version2: string): number {
60
+ const v1Parts = version1.split('.').map(Number);
61
+ const v2Parts = version2.split('.').map(Number);
62
+
63
+ for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
64
+ const v1 = v1Parts[i] || 0;
65
+ const v2 = v2Parts[i] || 0;
66
+ if (v1 > v2) return 1;
67
+ if (v1 < v2) return -1;
68
+ }
69
+ return 0;
70
+ }
71
+
72
+ private isVersionGte(version: string, target: string): boolean {
73
+ return this.compareVersions(version, target) >= 0;
74
+ }
75
+
76
+ private getMajorVersion(version: string): number {
77
+ return parseInt(version.split('.')[0]) || 0;
78
+ }
79
+
80
+ /**
81
+ * Main installation method - detects framework and auto-installs
82
+ */
83
+ async install(): Promise<InstallationResult> {
84
+ try {
85
+ // Step 1: Detect framework
86
+ this.framework = await this.detectFramework();
87
+
88
+ // Step 2: Install package
89
+ await this.installPackage();
90
+
91
+ // Step 3: Generate and apply code modifications
92
+ const modifications = await this.generateModifications();
93
+ await this.applyModifications(modifications);
94
+
95
+ // Step 4: Generate next steps
96
+ const nextSteps = this.generateNextSteps();
97
+
98
+ return {
99
+ success: true,
100
+ framework: this.framework,
101
+ modifications,
102
+ errors: [],
103
+ nextSteps
104
+ };
105
+ } catch (error) {
106
+ return {
107
+ success: false,
108
+ framework: this.framework || { name: 'unknown', type: 'vanilla' },
109
+ modifications: [],
110
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
111
+ nextSteps: []
112
+ };
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Detect the current framework and project setup
118
+ */
119
+ public async detectFramework(): Promise<FrameworkInfo> {
120
+ const packageJsonPath = path.join(this.projectRoot, 'package.json');
121
+
122
+ if (!fs.existsSync(packageJsonPath)) {
123
+ return {
124
+ name: 'vanilla',
125
+ type: 'vanilla',
126
+ projectRoot: this.projectRoot
127
+ };
128
+ }
129
+
130
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
131
+ const dependencies = {
132
+ ...packageJson.dependencies,
133
+ ...packageJson.devDependencies
134
+ };
135
+
136
+ // Detect framework with version information
137
+ let framework: FrameworkInfo = {
138
+ name: 'vanilla',
139
+ type: 'vanilla',
140
+ projectRoot: this.projectRoot,
141
+ features: {}
142
+ };
143
+
144
+ if (dependencies.nuxt) {
145
+ const nuxtVersion = dependencies.nuxt;
146
+ const isNuxt3 = this.isVersionGte(nuxtVersion, '3.0.0');
147
+
148
+ framework = {
149
+ name: 'nuxt',
150
+ type: 'nuxt',
151
+ version: nuxtVersion,
152
+ majorVersion: this.getMajorVersion(nuxtVersion),
153
+ hasTypeScript: !!dependencies.typescript,
154
+ hasRouter: true,
155
+ projectRoot: this.projectRoot,
156
+ features: {
157
+ hasNuxt3: isNuxt3
158
+ }
159
+ };
160
+ } else if (dependencies.next) {
161
+ const nextVersion = dependencies.next;
162
+ const isNext13 = this.isVersionGte(nextVersion, '13.0.0');
163
+
164
+ framework = {
165
+ name: 'nextjs',
166
+ type: 'nextjs',
167
+ version: nextVersion,
168
+ majorVersion: this.getMajorVersion(nextVersion),
169
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/node'],
170
+ hasRouter: true,
171
+ projectRoot: this.projectRoot,
172
+ features: {
173
+ hasNextAppRouter: isNext13
174
+ }
175
+ };
176
+ } else if (dependencies['@remix-run/react'] || dependencies['@remix-run/dev']) {
177
+ const remixVersion = dependencies['@remix-run/react'] || dependencies['@remix-run/dev'];
178
+ framework = {
179
+ name: 'remix',
180
+ type: 'remix',
181
+ version: remixVersion,
182
+ majorVersion: this.getMajorVersion(remixVersion),
183
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
184
+ hasRouter: true,
185
+ projectRoot: this.projectRoot,
186
+ features: {}
187
+ };
188
+ } else if (dependencies.react) {
189
+ const reactVersion = dependencies.react;
190
+ const isReact18 = this.isVersionGte(reactVersion, '18.0.0');
191
+
192
+ framework = {
193
+ name: 'react',
194
+ type: 'react',
195
+ version: reactVersion,
196
+ majorVersion: this.getMajorVersion(reactVersion),
197
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
198
+ hasRouter: !!dependencies['react-router-dom'] || !!dependencies['react-router'],
199
+ projectRoot: this.projectRoot,
200
+ features: {
201
+ hasReact18: isReact18
202
+ }
203
+ };
204
+ } else if (dependencies.vue) {
205
+ const vueVersion = dependencies.vue;
206
+ const isVue3 = this.isVersionGte(vueVersion, '3.0.0');
207
+
208
+ framework = {
209
+ name: 'vue',
210
+ type: 'vue',
211
+ version: vueVersion,
212
+ majorVersion: this.getMajorVersion(vueVersion),
213
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@vue/cli-service'],
214
+ hasRouter: !!dependencies['vue-router'],
215
+ projectRoot: this.projectRoot,
216
+ features: {
217
+ hasVue3: isVue3
218
+ }
219
+ };
220
+ } else if (dependencies['@angular/core']) {
221
+ const angularVersion = dependencies['@angular/core'];
222
+ const isAngular17 = this.isVersionGte(angularVersion, '17.0.0');
223
+
224
+ framework = {
225
+ name: 'angular',
226
+ type: 'angular',
227
+ version: angularVersion,
228
+ majorVersion: this.getMajorVersion(angularVersion),
229
+ hasTypeScript: true,
230
+ hasRouter: true,
231
+ projectRoot: this.projectRoot,
232
+ features: {
233
+ hasAngularStandalone: isAngular17
234
+ }
235
+ };
236
+ } else if (dependencies.svelte) {
237
+ const svelteVersion = dependencies.svelte;
238
+ const isSvelteKit = !!dependencies['@sveltejs/kit'];
239
+
240
+ framework = {
241
+ name: 'svelte',
242
+ type: 'svelte',
243
+ version: svelteVersion,
244
+ majorVersion: this.getMajorVersion(svelteVersion),
245
+ hasTypeScript: !!dependencies.typescript || !!dependencies['svelte-check'],
246
+ hasRouter: !!dependencies['svelte-routing'] || !!dependencies['@sveltejs/kit'],
247
+ projectRoot: this.projectRoot,
248
+ features: {
249
+ hasSvelteKit: isSvelteKit
250
+ }
251
+ };
252
+ } else if (dependencies.astro) {
253
+ const astroVersion = dependencies.astro;
254
+ framework = {
255
+ name: 'astro',
256
+ type: 'astro',
257
+ version: astroVersion,
258
+ majorVersion: this.getMajorVersion(astroVersion),
259
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@astrojs/ts-plugin'],
260
+ hasRouter: true,
261
+ projectRoot: this.projectRoot,
262
+ features: {}
263
+ };
264
+ } else if (dependencies.gatsby) {
265
+ const gatsbyVersion = dependencies.gatsby;
266
+ framework = {
267
+ name: 'gatsby',
268
+ type: 'gatsby',
269
+ version: gatsbyVersion,
270
+ majorVersion: this.getMajorVersion(gatsbyVersion),
271
+ hasTypeScript: !!dependencies.typescript || !!dependencies['@types/react'],
272
+ hasRouter: true,
273
+ projectRoot: this.projectRoot,
274
+ features: {}
275
+ };
276
+ }
277
+
278
+ // Detect bundler
279
+ if (dependencies.vite) {
280
+ framework.bundler = 'vite';
281
+ } else if (dependencies.webpack) {
282
+ framework.bundler = 'webpack';
283
+ } else if (dependencies.esbuild) {
284
+ framework.bundler = 'esbuild';
285
+ } else if (dependencies.rollup) {
286
+ framework.bundler = 'rollup';
287
+ }
288
+
289
+ // Detect package manager
290
+ if (fs.existsSync(path.join(this.projectRoot, 'yarn.lock'))) {
291
+ framework.packageManager = 'yarn';
292
+ } else if (fs.existsSync(path.join(this.projectRoot, 'pnpm-lock.yaml'))) {
293
+ framework.packageManager = 'pnpm';
294
+ } else {
295
+ framework.packageManager = 'npm';
296
+ }
297
+
298
+ return framework;
299
+ }
300
+
301
+ /**
302
+ * Install the SDK package
303
+ */
304
+ protected async installPackage(): Promise<void> {
305
+ const { execSync } = await import('child_process');
306
+
307
+ // Build base command
308
+ let command = this.framework?.packageManager === 'yarn'
309
+ ? 'yarn add humanbehavior-js'
310
+ : this.framework?.packageManager === 'pnpm'
311
+ ? 'pnpm add humanbehavior-js'
312
+ : 'npm install humanbehavior-js';
313
+
314
+ // Add legacy peer deps flag for npm to handle dependency conflicts
315
+ if (this.framework?.packageManager !== 'yarn' && this.framework?.packageManager !== 'pnpm') {
316
+ command += ' --legacy-peer-deps';
317
+ }
318
+
319
+ try {
320
+ execSync(command, { cwd: this.projectRoot, stdio: 'inherit' });
321
+ } catch (error) {
322
+ throw new Error(`Failed to install humanbehavior-js: ${error}`);
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Generate code modifications based on framework
328
+ */
329
+ protected async generateModifications(): Promise<CodeModification[]> {
330
+ const modifications: CodeModification[] = [];
331
+
332
+ switch (this.framework?.type) {
333
+ case 'react':
334
+ modifications.push(...await this.generateReactModifications());
335
+ break;
336
+ case 'nextjs':
337
+ modifications.push(...await this.generateNextJSModifications());
338
+ break;
339
+ case 'nuxt':
340
+ modifications.push(...await this.generateNuxtModifications());
341
+ break;
342
+ case 'astro':
343
+ modifications.push(...await this.generateAstroModifications());
344
+ break;
345
+ case 'gatsby':
346
+ modifications.push(...await this.generateGatsbyModifications());
347
+ break;
348
+ case 'remix':
349
+ modifications.push(...await this.generateRemixModifications());
350
+ break;
351
+ case 'vue':
352
+ modifications.push(...await this.generateVueModifications());
353
+ break;
354
+ case 'angular':
355
+ modifications.push(...await this.generateAngularModifications());
356
+ break;
357
+ case 'svelte':
358
+ modifications.push(...await this.generateSvelteModifications());
359
+ break;
360
+ default:
361
+ modifications.push(...await this.generateVanillaModifications());
362
+ }
363
+
364
+ return modifications;
365
+ }
366
+
367
+ /**
368
+ * Generate React-specific modifications
369
+ */
370
+ private async generateReactModifications(): Promise<CodeModification[]> {
371
+ const modifications: CodeModification[] = [];
372
+
373
+ // Find main App component or index file
374
+ const appFile = this.findReactAppFile();
375
+ if (appFile) {
376
+ const content = fs.readFileSync(appFile, 'utf8');
377
+ const modifiedContent = this.injectReactProvider(content, appFile);
378
+
379
+ modifications.push({
380
+ filePath: appFile,
381
+ action: 'modify',
382
+ content: modifiedContent,
383
+ description: 'Added HumanBehaviorProvider to React app'
384
+ });
385
+ }
386
+
387
+ // Create or append to environment file
388
+ modifications.push(this.createEnvironmentModification(this.framework!));
389
+
390
+ return modifications;
391
+ }
392
+
393
+ /**
394
+ * Generate Next.js-specific modifications
395
+ */
396
+ private async generateNextJSModifications(): Promise<CodeModification[]> {
397
+ const modifications: CodeModification[] = [];
398
+
399
+ // Check for App Router
400
+ const appLayoutFile = path.join(this.projectRoot, 'src', 'app', 'layout.tsx');
401
+ const pagesLayoutFile = path.join(this.projectRoot, 'src', 'pages', '_app.tsx');
402
+
403
+ if (fs.existsSync(appLayoutFile)) {
404
+ // Create providers.tsx file for App Router
405
+ modifications.push({
406
+ filePath: path.join(this.projectRoot, 'src', 'app', 'providers.tsx'),
407
+ action: 'create',
408
+ content: `'use client';
409
+
410
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
411
+
412
+ export function Providers({ children }: { children: React.ReactNode }) {
413
+ return (
414
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
415
+ {children}
416
+ </HumanBehaviorProvider>
417
+ );
418
+ }`,
419
+ description: 'Created providers.tsx file for Next.js App Router'
420
+ });
421
+
422
+ // Modify layout.tsx to use the provider
423
+ const content = fs.readFileSync(appLayoutFile, 'utf8');
424
+ const modifiedContent = this.injectNextJSAppRouter(content);
425
+
426
+ modifications.push({
427
+ filePath: appLayoutFile,
428
+ action: 'modify',
429
+ content: modifiedContent,
430
+ description: 'Added Providers wrapper to Next.js App Router layout'
431
+ });
432
+ } else if (fs.existsSync(pagesLayoutFile)) {
433
+ // Create providers.tsx file for Pages Router
434
+ modifications.push({
435
+ filePath: path.join(this.projectRoot, 'src', 'components', 'providers.tsx'),
436
+ action: 'create',
437
+ content: `'use client';
438
+
439
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
440
+
441
+ export function Providers({ children }: { children: React.ReactNode }) {
442
+ return (
443
+ <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>
444
+ {children}
445
+ </HumanBehaviorProvider>
446
+ );
447
+ }`,
448
+ description: 'Created providers.tsx file for Pages Router'
449
+ });
450
+
451
+ // Modify _app.tsx to use the provider
452
+ const content = fs.readFileSync(pagesLayoutFile, 'utf8');
453
+ const modifiedContent = this.injectNextJSPagesRouter(content);
454
+
455
+ modifications.push({
456
+ filePath: pagesLayoutFile,
457
+ action: 'modify',
458
+ content: modifiedContent,
459
+ description: 'Added Providers wrapper to Next.js Pages Router'
460
+ });
461
+ }
462
+
463
+ // Create or append to environment file
464
+ modifications.push(this.createEnvironmentModification(this.framework!));
465
+
466
+ return modifications;
467
+ }
468
+
469
+ /**
470
+ * Generate Astro-specific modifications
471
+ */
472
+ private async generateAstroModifications(): Promise<CodeModification[]> {
473
+ const modifications: CodeModification[] = [];
474
+
475
+ // Create Astro component for HumanBehavior
476
+ const astroComponentPath = path.join(this.projectRoot, 'src', 'components', 'HumanBehavior.astro');
477
+ const astroComponentContent = `---
478
+ // This component will only run on the client side
479
+ ---
480
+
481
+ <script>
482
+ import { HumanBehaviorTracker } from 'humanbehavior-js';
483
+
484
+ // Get API key from environment variable
485
+ const apiKey = import.meta.env.PUBLIC_HUMANBEHAVIOR_API_KEY;
486
+
487
+ console.log('HumanBehavior: API key found:', apiKey ? 'Yes' : 'No');
488
+
489
+ if (apiKey) {
490
+ try {
491
+ const tracker = HumanBehaviorTracker.init(apiKey);
492
+ console.log('HumanBehavior: Tracker initialized successfully');
493
+
494
+ // Test event to verify tracking is working
495
+ setTimeout(() => {
496
+ tracker.customEvent('astro_page_view', {
497
+ page: window.location.pathname,
498
+ framework: 'astro'
499
+ }).then(() => {
500
+ console.log('HumanBehavior: Test event sent successfully');
501
+ }).catch((error) => {
502
+ console.error('HumanBehavior: Failed to send test event:', error);
503
+ });
504
+ }, 1000);
505
+
506
+ } catch (error) {
507
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
508
+ }
509
+ } else {
510
+ console.error('HumanBehavior: No API key found');
511
+ }
512
+ </script>`;
513
+
514
+ modifications.push({
515
+ filePath: astroComponentPath,
516
+ action: 'create',
517
+ content: astroComponentContent,
518
+ description: 'Created Astro component for HumanBehavior SDK'
519
+ });
520
+
521
+ // Find and update layout file
522
+ const layoutFiles = [
523
+ path.join(this.projectRoot, 'src', 'layouts', 'Layout.astro'),
524
+ path.join(this.projectRoot, 'src', 'layouts', 'layout.astro'),
525
+ path.join(this.projectRoot, 'src', 'layouts', 'BaseLayout.astro')
526
+ ];
527
+
528
+ let layoutFile = null;
529
+ for (const file of layoutFiles) {
530
+ if (fs.existsSync(file)) {
531
+ layoutFile = file;
532
+ break;
533
+ }
534
+ }
535
+
536
+ if (layoutFile) {
537
+ const content = fs.readFileSync(layoutFile, 'utf8');
538
+ const modifiedContent = this.injectAstroLayout(content);
539
+
540
+ modifications.push({
541
+ filePath: layoutFile,
542
+ action: 'modify',
543
+ content: modifiedContent,
544
+ description: 'Added HumanBehavior component to Astro layout'
545
+ });
546
+ }
547
+
548
+ // Add environment variable
549
+ modifications.push(this.createEnvironmentModification(this.framework!));
550
+
551
+ return modifications;
552
+ }
553
+
554
+ /**
555
+ * Generate Nuxt-specific modifications
556
+ */
557
+ private async generateNuxtModifications(): Promise<CodeModification[]> {
558
+ const modifications: CodeModification[] = [];
559
+
560
+ // Create plugin file for Nuxt (in app directory)
561
+ const pluginFile = path.join(this.projectRoot, 'app', 'plugins', 'humanbehavior.client.ts');
562
+ modifications.push({
563
+ filePath: pluginFile,
564
+ action: 'create',
565
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
566
+
567
+ export default defineNuxtPlugin(() => {
568
+ const config = useRuntimeConfig();
569
+
570
+ // Initialize HumanBehavior SDK (client-side only)
571
+ if (typeof window !== 'undefined') {
572
+ const apiKey = config.public.humanBehaviorApiKey;
573
+ console.log('HumanBehavior: API key:', apiKey ? 'present' : 'missing');
574
+
575
+ if (apiKey) {
576
+ try {
577
+ const tracker = HumanBehaviorTracker.init(apiKey);
578
+ console.log('HumanBehavior: Tracker initialized successfully');
579
+ } catch (error) {
580
+ console.error('HumanBehavior: Failed to initialize tracker:', error);
581
+ }
582
+ } else {
583
+ console.error('HumanBehavior: No API key found in runtime config');
584
+ }
585
+ }
586
+ });`,
587
+ description: 'Created Nuxt plugin for HumanBehavior SDK in app directory'
588
+ });
589
+
590
+ // Create environment configuration
591
+ const nuxtConfigFile = path.join(this.projectRoot, 'nuxt.config.ts');
592
+ if (fs.existsSync(nuxtConfigFile)) {
593
+ const content = fs.readFileSync(nuxtConfigFile, 'utf8');
594
+ const modifiedContent = this.injectNuxtConfig(content);
595
+
596
+ modifications.push({
597
+ filePath: nuxtConfigFile,
598
+ action: 'modify',
599
+ content: modifiedContent,
600
+ description: 'Added HumanBehavior runtime config to Nuxt config'
601
+ });
602
+ }
603
+
604
+ // Create or append to environment file
605
+ modifications.push(this.createEnvironmentModification(this.framework!));
606
+
607
+ return modifications;
608
+ }
609
+
610
+ /**
611
+ * Generate Remix-specific modifications
612
+ */
613
+ private async generateRemixModifications(): Promise<CodeModification[]> {
614
+ const modifications: CodeModification[] = [];
615
+
616
+ // Find root.tsx file
617
+ const rootFile = path.join(this.projectRoot, 'app', 'root.tsx');
618
+ if (fs.existsSync(rootFile)) {
619
+ const content = fs.readFileSync(rootFile, 'utf8');
620
+ const modifiedContent = this.injectRemixProvider(content);
621
+
622
+ modifications.push({
623
+ filePath: rootFile,
624
+ action: 'modify',
625
+ content: modifiedContent,
626
+ description: 'Added HumanBehaviorProvider to Remix root component'
627
+ });
628
+ }
629
+
630
+ // Create or append to environment file
631
+ modifications.push(this.createEnvironmentModification(this.framework!));
632
+
633
+ return modifications;
634
+ }
635
+
636
+ /**
637
+ * Generate Vue-specific modifications
638
+ */
639
+ private async generateVueModifications(): Promise<CodeModification[]> {
640
+ const modifications: CodeModification[] = [];
641
+
642
+ // Find main.js or main.ts
643
+ const mainFile = this.findVueMainFile();
644
+ if (mainFile) {
645
+ const content = fs.readFileSync(mainFile, 'utf8');
646
+ const modifiedContent = this.injectVuePlugin(content);
647
+
648
+ modifications.push({
649
+ filePath: mainFile,
650
+ action: 'modify',
651
+ content: modifiedContent,
652
+ description: 'Added HumanBehaviorPlugin to Vue app'
653
+ });
654
+ }
655
+
656
+ // Create or append to environment file
657
+ modifications.push(this.createEnvironmentModification(this.framework!));
658
+
659
+ return modifications;
660
+ }
661
+
662
+ /**
663
+ * Generate Angular-specific modifications
664
+ */
665
+ private async generateAngularModifications(): Promise<CodeModification[]> {
666
+ const modifications: CodeModification[] = [];
667
+
668
+ // Check for modern Angular (standalone components) vs legacy (NgModule)
669
+ const appModuleFile = path.join(this.projectRoot, 'src', 'app', 'app.module.ts');
670
+ const appComponentFile = path.join(this.projectRoot, 'src', 'app', 'app.ts');
671
+ const mainFile = path.join(this.projectRoot, 'src', 'main.ts');
672
+
673
+ const isModernAngular = fs.existsSync(appComponentFile) && !fs.existsSync(appModuleFile);
674
+
675
+ if (isModernAngular) {
676
+ // Modern Angular 17+ with standalone components
677
+ if (fs.existsSync(mainFile)) {
678
+ const content = fs.readFileSync(mainFile, 'utf8');
679
+ const modifiedContent = this.injectAngularStandaloneInit(content);
680
+
681
+ modifications.push({
682
+ filePath: mainFile,
683
+ action: 'modify',
684
+ content: modifiedContent,
685
+ description: 'Added HumanBehavior initialization to Angular main.ts'
686
+ });
687
+ }
688
+ } else if (fs.existsSync(appModuleFile)) {
689
+ // Legacy Angular with NgModule
690
+ const content = fs.readFileSync(appModuleFile, 'utf8');
691
+ const modifiedContent = this.injectAngularModule(content);
692
+
693
+ modifications.push({
694
+ filePath: appModuleFile,
695
+ action: 'modify',
696
+ content: modifiedContent,
697
+ description: 'Added HumanBehaviorModule to Angular app'
698
+ });
699
+ }
700
+
701
+ // Handle Angular environment file (legacy structure)
702
+ const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');
703
+ if (fs.existsSync(envFile)) {
704
+ const content = fs.readFileSync(envFile, 'utf8');
705
+ if (!content.includes('humanBehaviorApiKey')) {
706
+ const modifiedContent = content.replace(
707
+ /export const environment = {([\s\S]*?)};/,
708
+ `export const environment = {
709
+ $1,
710
+ humanBehaviorApiKey: process.env['HUMANBEHAVIOR_API_KEY'] || ''
711
+ };`
712
+ );
713
+ modifications.push({
714
+ filePath: envFile,
715
+ action: 'modify',
716
+ content: modifiedContent,
717
+ description: 'Added API key to Angular environment'
718
+ });
719
+ }
720
+ }
721
+
722
+ // Create or append to environment file
723
+ modifications.push(this.createEnvironmentModification(this.framework!));
724
+
725
+ return modifications;
726
+ }
727
+
728
+ /**
729
+ * Generate Svelte-specific modifications
730
+ */
731
+ private async generateSvelteModifications(): Promise<CodeModification[]> {
732
+ const modifications: CodeModification[] = [];
733
+
734
+ // Check for SvelteKit
735
+ const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');
736
+ const isSvelteKit = fs.existsSync(svelteConfigFile);
737
+
738
+ if (isSvelteKit) {
739
+ // SvelteKit - create layout file
740
+ const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');
741
+ if (fs.existsSync(layoutFile)) {
742
+ const content = fs.readFileSync(layoutFile, 'utf8');
743
+ const modifiedContent = this.injectSvelteKitLayout(content);
744
+
745
+ modifications.push({
746
+ filePath: layoutFile,
747
+ action: 'modify',
748
+ content: modifiedContent,
749
+ description: 'Added HumanBehavior store to SvelteKit layout'
750
+ });
751
+ }
752
+ } else {
753
+ // Regular Svelte - modify main file
754
+ const mainFile = this.findSvelteMainFile();
755
+ if (mainFile) {
756
+ const content = fs.readFileSync(mainFile, 'utf8');
757
+ const modifiedContent = this.injectSvelteStore(content);
758
+
759
+ modifications.push({
760
+ filePath: mainFile,
761
+ action: 'modify',
762
+ content: modifiedContent,
763
+ description: 'Added HumanBehavior store to Svelte app'
764
+ });
765
+ }
766
+ }
767
+
768
+ // Create or append to environment file
769
+ modifications.push(this.createEnvironmentModification(this.framework!));
770
+
771
+ return modifications;
772
+ }
773
+
774
+ /**
775
+ * Generate vanilla JS/TS modifications
776
+ */
777
+ private async generateVanillaModifications(): Promise<CodeModification[]> {
778
+ const modifications: CodeModification[] = [];
779
+
780
+ // Find HTML file to inject script
781
+ const htmlFile = this.findHTMLFile();
782
+ if (htmlFile) {
783
+ const content = fs.readFileSync(htmlFile, 'utf8');
784
+ const modifiedContent = this.injectVanillaScript(content);
785
+
786
+ modifications.push({
787
+ filePath: htmlFile,
788
+ action: 'modify',
789
+ content: modifiedContent,
790
+ description: 'Added HumanBehavior CDN script to HTML file'
791
+ });
792
+ }
793
+
794
+ // Create or append to environment file
795
+ modifications.push(this.createEnvironmentModification(this.framework!));
796
+
797
+ return modifications;
798
+ }
799
+
800
+ /**
801
+ * Generate Gatsby-specific modifications
802
+ */
803
+ private async generateGatsbyModifications(): Promise<CodeModification[]> {
804
+ const modifications: CodeModification[] = [];
805
+
806
+ // Modify or create gatsby-browser.js for Gatsby
807
+ const gatsbyBrowserFile = path.join(this.projectRoot, 'gatsby-browser.js');
808
+
809
+ if (fs.existsSync(gatsbyBrowserFile)) {
810
+ const content = fs.readFileSync(gatsbyBrowserFile, 'utf8');
811
+ const modifiedContent = this.injectGatsbyBrowser(content);
812
+
813
+ modifications.push({
814
+ filePath: gatsbyBrowserFile,
815
+ action: 'modify',
816
+ content: modifiedContent,
817
+ description: 'Added HumanBehavior initialization to Gatsby browser'
818
+ });
819
+ } else {
820
+ // Create gatsby-browser.js if it doesn't exist
821
+ modifications.push({
822
+ filePath: gatsbyBrowserFile,
823
+ action: 'create',
824
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
825
+
826
+ export const onClientEntry = () => {
827
+ console.log('Gatsby browser entry point loaded');
828
+ const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;
829
+ console.log('API Key found:', apiKey ? 'Yes' : 'No');
830
+ if (apiKey) {
831
+ const tracker = HumanBehaviorTracker.init(apiKey);
832
+ console.log('HumanBehavior SDK initialized for Gatsby');
833
+ } else {
834
+ console.log('No API key found in environment variables');
835
+ }
836
+ };`,
837
+ description: 'Created gatsby-browser.js with HumanBehavior initialization'
838
+ });
839
+ }
840
+
841
+ // Create or append to environment file
842
+ modifications.push(this.createEnvironmentModification(this.framework!));
843
+
844
+ return modifications;
845
+ }
846
+
847
+
848
+
849
+ /**
850
+ * Apply modifications to the codebase
851
+ */
852
+ protected async applyModifications(modifications: CodeModification[]): Promise<void> {
853
+ for (const modification of modifications) {
854
+ try {
855
+ const dir = path.dirname(modification.filePath);
856
+ if (!fs.existsSync(dir)) {
857
+ fs.mkdirSync(dir, { recursive: true });
858
+ }
859
+
860
+ switch (modification.action) {
861
+ case 'create':
862
+ fs.writeFileSync(modification.filePath, modification.content);
863
+ break;
864
+ case 'modify':
865
+ fs.writeFileSync(modification.filePath, modification.content);
866
+ break;
867
+ case 'append':
868
+ fs.appendFileSync(modification.filePath, '\n' + modification.content);
869
+ break;
870
+ }
871
+ } catch (error) {
872
+ throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);
873
+ }
874
+ }
875
+ }
876
+
877
+ /**
878
+ * Generate next steps for the user
879
+ */
880
+ private generateNextSteps(): string[] {
881
+ const steps = [
882
+ '✅ SDK installed and configured automatically!',
883
+ '🚀 Your app is now tracking user behavior',
884
+ '📊 View sessions in your HumanBehavior dashboard',
885
+ '🔧 Customize tracking in your code as needed'
886
+ ];
887
+
888
+ if (this.framework?.type === 'react' || this.framework?.type === 'nextjs') {
889
+ steps.push('💡 Use the useHumanBehavior() hook to track custom events');
890
+ }
891
+
892
+ return steps;
893
+ }
894
+
895
+ // Helper methods for file detection and content injection
896
+ private findReactAppFile(): string | null {
897
+ const possibleFiles = [
898
+ 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',
899
+ 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'
900
+ ];
901
+
902
+ for (const file of possibleFiles) {
903
+ const fullPath = path.join(this.projectRoot, file);
904
+ if (fs.existsSync(fullPath)) {
905
+ return fullPath;
906
+ }
907
+ }
908
+ return null;
909
+ }
910
+
911
+ private findVueMainFile(): string | null {
912
+ const possibleFiles = [
913
+ 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'
914
+ ];
915
+
916
+ for (const file of possibleFiles) {
917
+ const fullPath = path.join(this.projectRoot, file);
918
+ if (fs.existsSync(fullPath)) {
919
+ return fullPath;
920
+ }
921
+ }
922
+ return null;
923
+ }
924
+
925
+ private findSvelteMainFile(): string | null {
926
+ const possibleFiles = [
927
+ 'src/main.js', 'src/main.ts', 'src/main.svelte'
928
+ ];
929
+
930
+ for (const file of possibleFiles) {
931
+ const fullPath = path.join(this.projectRoot, file);
932
+ if (fs.existsSync(fullPath)) {
933
+ return fullPath;
934
+ }
935
+ }
936
+ return null;
937
+ }
938
+
939
+ private findHTMLFile(): string | null {
940
+ const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];
941
+
942
+ for (const file of possibleFiles) {
943
+ const fullPath = path.join(this.projectRoot, file);
944
+ if (fs.existsSync(fullPath)) {
945
+ return fullPath;
946
+ }
947
+ }
948
+ return null;
949
+ }
950
+
951
+ private injectReactProvider(content: string, filePath: string): string {
952
+ const isTypeScript = filePath.endsWith('.tsx') || filePath.endsWith('.ts');
953
+
954
+ // Check if already has HumanBehaviorProvider
955
+ if (content.includes('HumanBehaviorProvider')) {
956
+ return content;
957
+ }
958
+
959
+ // Determine the correct environment variable syntax based on bundler
960
+ const isVite = this.framework?.bundler === 'vite';
961
+ const envVar = isVite
962
+ ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!'
963
+ : 'process.env.HUMANBEHAVIOR_API_KEY!';
964
+
965
+ const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;
966
+
967
+ // Enhanced parsing for React 18+ features
968
+ const hasReact18 = this.framework?.features?.hasReact18;
969
+
970
+ // Handle different React patterns
971
+ if (content.includes('function App()') || content.includes('const App =')) {
972
+ // Add import statement
973
+ let modifiedContent = content.replace(
974
+ /(import.*?from.*?['"]react['"];?)/,
975
+ `$1\n${importStatement}`
976
+ );
977
+
978
+ // If no React import found, add it at the top
979
+ if (!modifiedContent.includes(importStatement)) {
980
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
981
+ }
982
+
983
+ // Wrap the App component return with HumanBehaviorProvider
984
+ modifiedContent = modifiedContent.replace(
985
+ /(return\s*\([\s\S]*?\)\s*;)/,
986
+ `return (
987
+ <HumanBehaviorProvider apiKey={${envVar}}>
988
+ $1
989
+ </HumanBehaviorProvider>
990
+ );`
991
+ );
992
+
993
+ return modifiedContent;
994
+ }
995
+
996
+ // Handle React 18+ createRoot pattern
997
+ if (hasReact18 && content.includes('createRoot')) {
998
+ let modifiedContent = content.replace(
999
+ /(import.*?from.*?['"]react['"];?)/,
1000
+ `$1\n${importStatement}`
1001
+ );
1002
+
1003
+ if (!modifiedContent.includes(importStatement)) {
1004
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1005
+ }
1006
+
1007
+ // Wrap the root render with HumanBehaviorProvider
1008
+ modifiedContent = modifiedContent.replace(
1009
+ /(root\.render\s*\([\s\S]*?\)\s*;)/,
1010
+ `root.render(
1011
+ <HumanBehaviorProvider apiKey={${envVar}}>
1012
+ $1
1013
+ </HumanBehaviorProvider>
1014
+ );`
1015
+ );
1016
+
1017
+ return modifiedContent;
1018
+ }
1019
+
1020
+ // Fallback: simple injection
1021
+ return `${importStatement}\n\n${content}`;
1022
+ }
1023
+
1024
+ private injectNextJSAppRouter(content: string): string {
1025
+ if (content.includes('Providers')) {
1026
+ return content;
1027
+ }
1028
+
1029
+ const importStatement = `import { Providers } from './providers';`;
1030
+
1031
+ // First, add the import statement
1032
+ let modifiedContent = content.replace(
1033
+ /export default function RootLayout/,
1034
+ `${importStatement}\n\nexport default function RootLayout`
1035
+ );
1036
+
1037
+ // Then wrap the body content with Providers
1038
+ // Use a more specific approach to handle the body content
1039
+ modifiedContent = modifiedContent.replace(
1040
+ /<body([^>]*)>([\s\S]*?)<\/body>/,
1041
+ (match, bodyAttrs, bodyContent) => {
1042
+ // Trim whitespace and newlines from bodyContent
1043
+ const trimmedContent = bodyContent.trim();
1044
+ return `<body${bodyAttrs}>
1045
+ <Providers>
1046
+ ${trimmedContent}
1047
+ </Providers>
1048
+ </body>`;
1049
+ }
1050
+ );
1051
+
1052
+ return modifiedContent;
1053
+ }
1054
+
1055
+ private injectNextJSPagesRouter(content: string): string {
1056
+ if (content.includes('Providers')) {
1057
+ return content;
1058
+ }
1059
+
1060
+ const importStatement = `import { Providers } from '../components/providers';`;
1061
+
1062
+ return content.replace(
1063
+ /function MyApp/,
1064
+ `${importStatement}\n\nfunction MyApp`
1065
+ ).replace(
1066
+ /return \(([\s\S]*?)\);/,
1067
+ `return (
1068
+ <Providers>
1069
+ $1
1070
+ </Providers>
1071
+ );`
1072
+ );
1073
+ }
1074
+
1075
+ private injectRemixProvider(content: string): string {
1076
+ if (content.includes('HumanBehaviorProvider')) {
1077
+ return content;
1078
+ }
1079
+
1080
+ const importStatement = `import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';`;
1081
+ const useLoaderDataImport = `import { useLoaderData } from "@remix-run/react";`;
1082
+
1083
+ // Add imports more robustly
1084
+ let modifiedContent = content;
1085
+
1086
+ // Add HumanBehaviorProvider import - find the last import and add after it
1087
+ if (!content.includes('HumanBehaviorProvider')) {
1088
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
1089
+ if (lastImportIndex !== -1) {
1090
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
1091
+ if (nextLineIndex !== -1) {
1092
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
1093
+ importStatement + '\n' +
1094
+ modifiedContent.slice(nextLineIndex + 1);
1095
+ } else {
1096
+ modifiedContent = modifiedContent + '\n' + importStatement;
1097
+ }
1098
+ } else {
1099
+ modifiedContent = importStatement + '\n' + modifiedContent;
1100
+ }
1101
+ }
1102
+
1103
+ // Add useLoaderData import - find the last import and add after it
1104
+ if (!content.includes('useLoaderData')) {
1105
+ const lastImportIndex = modifiedContent.lastIndexOf('import');
1106
+ if (lastImportIndex !== -1) {
1107
+ const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
1108
+ if (nextLineIndex !== -1) {
1109
+ modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
1110
+ useLoaderDataImport + '\n' +
1111
+ modifiedContent.slice(nextLineIndex + 1);
1112
+ } else {
1113
+ modifiedContent = modifiedContent + '\n' + useLoaderDataImport;
1114
+ }
1115
+ } else {
1116
+ modifiedContent = useLoaderDataImport + '\n' + modifiedContent;
1117
+ }
1118
+ }
1119
+
1120
+
1121
+
1122
+ // Add loader function before the App component
1123
+ if (!content.includes('export const loader')) {
1124
+ modifiedContent = modifiedContent.replace(
1125
+ /export default function App\(\)/,
1126
+ `export const loader = createHumanBehaviorLoader();
1127
+
1128
+ export default function App()`
1129
+ );
1130
+ }
1131
+
1132
+ // Wrap the App component content with HumanBehaviorProvider
1133
+ modifiedContent = modifiedContent.replace(
1134
+ /export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/,
1135
+ `export default function App() {
1136
+ const data = useLoaderData<typeof loader>();
1137
+
1138
+ return (
1139
+ <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
1140
+ $1
1141
+ </HumanBehaviorProvider>
1142
+ );
1143
+ }`
1144
+ );
1145
+
1146
+ return modifiedContent;
1147
+ }
1148
+
1149
+ private injectVuePlugin(content: string): string {
1150
+ if (content.includes('HumanBehaviorPlugin')) {
1151
+ return content;
1152
+ }
1153
+
1154
+ const importStatement = `import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';`;
1155
+
1156
+ // Enhanced Vue 3 support with version detection
1157
+ const hasVue3 = this.framework?.features?.hasVue3;
1158
+
1159
+ if (hasVue3) {
1160
+ // Vue 3 with Composition API
1161
+ const pluginUsage = `app.use(HumanBehaviorPlugin, {
1162
+ apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY
1163
+ });`;
1164
+
1165
+ let modifiedContent = content;
1166
+
1167
+ // Add import statement
1168
+ if (!content.includes(importStatement)) {
1169
+ modifiedContent = content.replace(
1170
+ /(import.*?from.*?['"]vue['"];?)/,
1171
+ `$1\n${importStatement}`
1172
+ );
1173
+
1174
+ // If no Vue import found, add it at the top
1175
+ if (!modifiedContent.includes(importStatement)) {
1176
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1177
+ }
1178
+ }
1179
+
1180
+ // Handle createApp pattern
1181
+ if (content.includes('createApp')) {
1182
+ modifiedContent = modifiedContent.replace(
1183
+ /(app\.mount\(.*?\))/,
1184
+ `${pluginUsage}\n\n$1`
1185
+ );
1186
+ }
1187
+
1188
+ return modifiedContent;
1189
+ } else {
1190
+ // Vue 2 with Options API
1191
+ const pluginUsage = `Vue.use(HumanBehaviorPlugin, {
1192
+ apiKey: process.env.VUE_APP_HUMANBEHAVIOR_API_KEY
1193
+ });`;
1194
+
1195
+ let modifiedContent = content;
1196
+
1197
+ // Add import statement
1198
+ if (!content.includes(importStatement)) {
1199
+ modifiedContent = content.replace(
1200
+ /(import.*?from.*?['"]vue['"];?)/,
1201
+ `$1\n${importStatement}`
1202
+ );
1203
+
1204
+ if (!modifiedContent.includes(importStatement)) {
1205
+ modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1206
+ }
1207
+ }
1208
+
1209
+ // Handle new Vue pattern
1210
+ if (content.includes('new Vue')) {
1211
+ modifiedContent = modifiedContent.replace(
1212
+ /(new Vue\(.*?\))/,
1213
+ `${pluginUsage}\n\n$1`
1214
+ );
1215
+ }
1216
+
1217
+ return modifiedContent;
1218
+ }
1219
+ }
1220
+
1221
+ private injectAngularModule(content: string): string {
1222
+ if (content.includes('HumanBehaviorModule')) {
1223
+ return content;
1224
+ }
1225
+
1226
+ const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;
1227
+ const environmentImport = `import { environment } from '../environments/environment';`;
1228
+
1229
+ // Add environment import if not present
1230
+ let modifiedContent = content;
1231
+ if (!content.includes('environment')) {
1232
+ modifiedContent = content.replace(
1233
+ /import.*from.*['"]@angular/,
1234
+ `${environmentImport}\n$&`
1235
+ );
1236
+ }
1237
+
1238
+ return modifiedContent.replace(
1239
+ /imports:\s*\[([\s\S]*?)\]/,
1240
+ `imports: [
1241
+ $1,
1242
+ HumanBehaviorModule.forRoot({
1243
+ apiKey: environment.humanBehaviorApiKey
1244
+ })
1245
+ ]`
1246
+ ).replace(
1247
+ /import.*from.*['"]@angular/,
1248
+ `$&\n${importStatement}`
1249
+ );
1250
+ }
1251
+
1252
+ private injectAngularStandaloneInit(content: string): string {
1253
+ if (content.includes('initializeHumanBehavior')) {
1254
+ return content;
1255
+ }
1256
+
1257
+ const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;
1258
+
1259
+ // Add import at the top
1260
+ let modifiedContent = content.replace(
1261
+ /import.*from.*['"]@angular/,
1262
+ `${importStatement}\n$&`
1263
+ );
1264
+
1265
+ // Add initialization after bootstrapApplication
1266
+ modifiedContent = modifiedContent.replace(
1267
+ /(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/,
1268
+ `$1
1269
+
1270
+ // Initialize HumanBehavior SDK (client-side only)
1271
+ if (typeof window !== 'undefined') {
1272
+ const tracker = initializeHumanBehavior(
1273
+ '${this.apiKey}'
1274
+ );
1275
+ }`
1276
+ );
1277
+
1278
+ return modifiedContent;
1279
+ }
1280
+
1281
+ private injectSvelteStore(content: string): string {
1282
+ if (content.includes('humanBehaviorStore')) {
1283
+ return content;
1284
+ }
1285
+
1286
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
1287
+ const initCode = `humanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
1288
+
1289
+ return `${importStatement}\n${initCode}\n\n${content}`;
1290
+ }
1291
+
1292
+ private injectSvelteKitLayout(content: string): string {
1293
+ if (content.includes('humanBehaviorStore')) {
1294
+ return content;
1295
+ }
1296
+
1297
+ const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
1298
+ const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;
1299
+ const initCode = `humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
1300
+
1301
+ // Add to script section - handle different script tag patterns
1302
+ if (content.includes('<script lang="ts">')) {
1303
+ return content.replace(
1304
+ /<script lang="ts">/,
1305
+ `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`
1306
+ );
1307
+ } else if (content.includes('<script>')) {
1308
+ return content.replace(
1309
+ /<script>/,
1310
+ `<script>\n\t${envImport}\n\t${importStatement}\n\t${initCode}`
1311
+ );
1312
+ } else if (content.includes('<script context="module">')) {
1313
+ return content.replace(
1314
+ /<script\s+context="module">/,
1315
+ `<script context="module">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`
1316
+ );
1317
+ } else {
1318
+ // If no script tag found, add one at the beginning
1319
+ return content.replace(
1320
+ /<svelte:head>/,
1321
+ `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}\n</script>\n\n<svelte:head>`
1322
+ );
1323
+ }
1324
+ }
1325
+
1326
+ private injectVanillaScript(content: string): string {
1327
+ if (content.includes('humanbehavior-js')) {
1328
+ return content;
1329
+ }
1330
+
1331
+ const cdnScript = `<script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"></script>`;
1332
+ const initScript = `<script>
1333
+ // Initialize HumanBehavior SDK
1334
+ // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available
1335
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}');
1336
+ </script>`;
1337
+
1338
+ return content.replace(
1339
+ /<\/head>/,
1340
+ ` ${cdnScript}\n ${initScript}\n</head>`
1341
+ );
1342
+ }
1343
+
1344
+ /**
1345
+ * Inject Astro layout with HumanBehavior component
1346
+ */
1347
+ private injectAstroLayout(content: string): string {
1348
+ // Check if HumanBehavior component is already imported
1349
+ if (content.includes('HumanBehavior') || content.includes('humanbehavior-js')) {
1350
+ return content; // Already has HumanBehavior
1351
+ }
1352
+
1353
+ // Add import inside frontmatter if not present
1354
+ let modifiedContent = content;
1355
+ if (!content.includes('import HumanBehavior')) {
1356
+ const importStatement = 'import HumanBehavior from \'../components/HumanBehavior.astro\';';
1357
+ const frontmatterEndIndex = content.indexOf('---', 3);
1358
+ if (frontmatterEndIndex !== -1) {
1359
+ // Insert import inside frontmatter, before the closing ---
1360
+ modifiedContent = content.slice(0, frontmatterEndIndex) + '\n' + importStatement + '\n' + content.slice(frontmatterEndIndex);
1361
+ } else {
1362
+ // No frontmatter, add at the very beginning
1363
+ modifiedContent = '---\n' + importStatement + '\n---\n\n' + content;
1364
+ }
1365
+ }
1366
+
1367
+ // Find the closing </body> tag and add HumanBehavior component before it
1368
+ const bodyCloseIndex = modifiedContent.lastIndexOf('</body>');
1369
+ if (bodyCloseIndex === -1) {
1370
+ // No body tag found, append to end
1371
+ return modifiedContent + '\n\n<HumanBehavior />';
1372
+ }
1373
+
1374
+ // Add component before closing body tag
1375
+ return modifiedContent.slice(0, bodyCloseIndex) + ' <HumanBehavior />\n' + modifiedContent.slice(bodyCloseIndex);
1376
+ }
1377
+
1378
+ private injectNuxtConfig(content: string): string {
1379
+ if (content.includes('humanBehaviorApiKey')) {
1380
+ return content;
1381
+ }
1382
+
1383
+ // Enhanced Nuxt 3 support with version detection
1384
+ const hasNuxt3 = this.framework?.features?.hasNuxt3;
1385
+
1386
+ if (hasNuxt3) {
1387
+ // Nuxt 3 with runtime config
1388
+ return content.replace(
1389
+ /export default defineNuxtConfig\(\{/,
1390
+ `export default defineNuxtConfig({
1391
+ runtimeConfig: {
1392
+ public: {
1393
+ humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY
1394
+ }
1395
+ },`
1396
+ );
1397
+ } else {
1398
+ // Nuxt 2 with env config
1399
+ return content.replace(
1400
+ /export default \{/,
1401
+ `export default {
1402
+ env: {
1403
+ humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY
1404
+ },`
1405
+ );
1406
+ }
1407
+ }
1408
+
1409
+ private injectGatsbyLayout(content: string): string {
1410
+ if (content.includes('HumanBehavior')) {
1411
+ return content;
1412
+ }
1413
+
1414
+ const importStatement = `import HumanBehavior from './HumanBehavior';`;
1415
+ const componentUsage = `<HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />`;
1416
+
1417
+ // Add import at the top
1418
+ let modifiedContent = content.replace(
1419
+ /import.*from.*['"]\./,
1420
+ `${importStatement}\n$&`
1421
+ );
1422
+
1423
+ // Add component before closing body tag
1424
+ modifiedContent = modifiedContent.replace(
1425
+ /(\s*<\/body>)/,
1426
+ `\n ${componentUsage}\n$1`
1427
+ );
1428
+
1429
+ return modifiedContent;
1430
+ }
1431
+
1432
+ private injectGatsbyBrowser(content: string): string {
1433
+ if (content.includes('HumanBehaviorTracker')) {
1434
+ return content;
1435
+ }
1436
+
1437
+ const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;
1438
+ const initCode = `
1439
+ // Initialize HumanBehavior SDK
1440
+ export const onClientEntry = () => {
1441
+ console.log('Gatsby browser entry point loaded');
1442
+ const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;
1443
+ console.log('API Key found:', apiKey ? 'Yes' : 'No');
1444
+ if (apiKey) {
1445
+ const tracker = HumanBehaviorTracker.init(apiKey);
1446
+ console.log('HumanBehavior SDK initialized for Gatsby');
1447
+ } else {
1448
+ console.log('No API key found in environment variables');
1449
+ }
1450
+ };`;
1451
+
1452
+ // If the file already has content, add the import and init code
1453
+ if (content.trim()) {
1454
+ return `${importStatement}${initCode}\n\n${content}`;
1455
+ } else {
1456
+ // If file is empty, just return the new content
1457
+ return `${importStatement}${initCode}`;
1458
+ }
1459
+ }
1460
+
1461
+
1462
+
1463
+ /**
1464
+ * Helper method to find the best environment file for a framework
1465
+ */
1466
+ private findBestEnvFile(framework: FrameworkInfo): { filePath: string; envVarName: string } {
1467
+ const possibleEnvFiles = [
1468
+ '.env.local',
1469
+ '.env.development.local',
1470
+ '.env.development',
1471
+ '.env.local.development',
1472
+ '.env',
1473
+ '.env.production',
1474
+ '.env.staging'
1475
+ ];
1476
+
1477
+ // Framework-specific environment variable names
1478
+ const getEnvVarName = (framework: FrameworkInfo) => {
1479
+ // Handle React+Vite specifically
1480
+ if (framework.type === 'react' && framework.bundler === 'vite') {
1481
+ return 'VITE_HUMANBEHAVIOR_API_KEY';
1482
+ }
1483
+
1484
+ // Framework-specific mappings
1485
+ const envVarNames = {
1486
+ react: 'HUMANBEHAVIOR_API_KEY',
1487
+ nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
1488
+ vue: 'VITE_HUMANBEHAVIOR_API_KEY',
1489
+ svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
1490
+ angular: 'HUMANBEHAVIOR_API_KEY',
1491
+ nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
1492
+ remix: 'HUMANBEHAVIOR_API_KEY',
1493
+ vanilla: 'HUMANBEHAVIOR_API_KEY',
1494
+ astro: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
1495
+ gatsby: 'GATSBY_HUMANBEHAVIOR_API_KEY',
1496
+ node: 'HUMANBEHAVIOR_API_KEY',
1497
+ auto: 'HUMANBEHAVIOR_API_KEY'
1498
+ };
1499
+
1500
+ return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';
1501
+ };
1502
+
1503
+ const envVarName = getEnvVarName(framework);
1504
+
1505
+ // Check for existing files
1506
+ for (const envFile of possibleEnvFiles) {
1507
+ const fullPath = path.join(this.projectRoot, envFile);
1508
+ if (fs.existsSync(fullPath)) {
1509
+ return { filePath: fullPath, envVarName };
1510
+ }
1511
+ }
1512
+
1513
+ // Framework-specific default file creation
1514
+ const defaultFiles = {
1515
+ react: '.env.local',
1516
+ nextjs: '.env.local',
1517
+ vue: '.env.local',
1518
+ svelte: '.env',
1519
+ angular: '.env',
1520
+ nuxt: '.env',
1521
+ remix: '.env.local',
1522
+ vanilla: '.env',
1523
+ astro: '.env',
1524
+ gatsby: '.env.development',
1525
+ node: '.env',
1526
+ auto: '.env'
1527
+ };
1528
+
1529
+ const defaultFile = defaultFiles[framework.type] || '.env';
1530
+ return {
1531
+ filePath: path.join(this.projectRoot, defaultFile),
1532
+ envVarName
1533
+ };
1534
+ }
1535
+
1536
+ /**
1537
+ * Helper method to create or append to environment files
1538
+ */
1539
+ private createEnvironmentModification(framework: FrameworkInfo): CodeModification {
1540
+ const { filePath, envVarName } = this.findBestEnvFile(framework);
1541
+
1542
+ // Clean the API key to prevent formatting issues
1543
+ const cleanApiKey = this.apiKey.trim();
1544
+
1545
+ if (fs.existsSync(filePath)) {
1546
+ // Check if the variable already exists
1547
+ const content = fs.readFileSync(filePath, 'utf8');
1548
+ if (content.includes(envVarName)) {
1549
+ // Variable exists, don't modify
1550
+ return {
1551
+ filePath,
1552
+ action: 'modify',
1553
+ content: content, // No change
1554
+ description: `API key already exists in ${path.basename(filePath)}`
1555
+ };
1556
+ } else {
1557
+ // Append to existing file
1558
+ return {
1559
+ filePath,
1560
+ action: 'append',
1561
+ content: `\n${envVarName}=${cleanApiKey}`,
1562
+ description: `Added API key to existing ${path.basename(filePath)}`
1563
+ };
1564
+ }
1565
+ } else {
1566
+ // Create new file
1567
+ return {
1568
+ filePath,
1569
+ action: 'create',
1570
+ content: `${envVarName}=${cleanApiKey}`,
1571
+ description: `Created ${path.basename(filePath)} with API key`
1572
+ };
1573
+ }
1574
+ }
1575
+ }
1576
+
1577
+ /**
1578
+ * Browser-based auto-installation wizard
1579
+ */
1580
+ export class BrowserAutoInstallationWizard {
1581
+ private apiKey: string;
1582
+
1583
+ constructor(apiKey: string) {
1584
+ this.apiKey = apiKey;
1585
+ }
1586
+
1587
+ async install(): Promise<InstallationResult> {
1588
+ try {
1589
+ // Detect framework in browser
1590
+ const framework = this.detectFramework();
1591
+
1592
+ // Generate installation instructions
1593
+ const modifications = this.generateBrowserModifications(framework);
1594
+
1595
+ return {
1596
+ success: true,
1597
+ framework,
1598
+ modifications,
1599
+ errors: [],
1600
+ nextSteps: [
1601
+ '✅ Framework detected automatically',
1602
+ '📋 Copy the generated code to your project',
1603
+ '🚀 Your app will be ready to track user behavior'
1604
+ ]
1605
+ };
1606
+ } catch (error) {
1607
+ return {
1608
+ success: false,
1609
+ framework: { name: 'unknown', type: 'vanilla' },
1610
+ modifications: [],
1611
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
1612
+ nextSteps: []
1613
+ };
1614
+ }
1615
+ }
1616
+
1617
+ private detectFramework(): FrameworkInfo {
1618
+ if (typeof window !== 'undefined') {
1619
+ if ((window as any).React) {
1620
+ return { name: 'react', type: 'react' };
1621
+ }
1622
+ if ((window as any).Vue) {
1623
+ return { name: 'vue', type: 'vue' };
1624
+ }
1625
+ if ((window as any).angular) {
1626
+ return { name: 'angular', type: 'angular' };
1627
+ }
1628
+ }
1629
+
1630
+ return { name: 'vanilla', type: 'vanilla' };
1631
+ }
1632
+
1633
+ private generateBrowserModifications(framework: FrameworkInfo): CodeModification[] {
1634
+ // Return code snippets for browser environment
1635
+ const modifications: CodeModification[] = [];
1636
+
1637
+ switch (framework.type) {
1638
+ case 'react':
1639
+ modifications.push({
1640
+ filePath: 'App.jsx',
1641
+ action: 'create',
1642
+ content: `import { HumanBehaviorProvider } from 'humanbehavior-js/react';
1643
+
1644
+ function App() {
1645
+ return (
1646
+ <HumanBehaviorProvider apiKey="${this.apiKey}">
1647
+ {/* Your app components */}
1648
+ </HumanBehaviorProvider>
1649
+ );
1650
+ }
1651
+
1652
+ export default App;`,
1653
+ description: 'React component with HumanBehaviorProvider'
1654
+ });
1655
+ break;
1656
+
1657
+ case 'remix':
1658
+ modifications.push({
1659
+ filePath: 'app/root.tsx',
1660
+ action: 'create',
1661
+ content: `import {
1662
+ Links,
1663
+ Meta,
1664
+ Outlet,
1665
+ Scripts,
1666
+ ScrollRestoration,
1667
+ useLoaderData,
1668
+ } from "@remix-run/react";
1669
+ import { HumanBehaviorProvider } from 'humanbehavior-js/react';
1670
+ import type { LoaderFunctionArgs } from "@remix-run/node";
1671
+
1672
+ export async function loader({ request }: LoaderFunctionArgs) {
1673
+ return {
1674
+ ENV: {
1675
+ HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,
1676
+ },
1677
+ };
1678
+ }
1679
+
1680
+ export function Layout({ children }: { children: React.ReactNode }) {
1681
+ return (
1682
+ <html lang="en">
1683
+ <head>
1684
+ <meta charSet="utf-8" />
1685
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1686
+ <Meta />
1687
+ <Links />
1688
+ </head>
1689
+ <body>
1690
+ {children}
1691
+ <ScrollRestoration />
1692
+ <Scripts />
1693
+ </body>
1694
+ </html>
1695
+ );
1696
+ }
1697
+
1698
+ export default function App() {
1699
+ const data = useLoaderData<typeof loader>();
1700
+
1701
+ return (
1702
+ <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
1703
+ <div className="min-h-screen bg-gray-50">
1704
+ {/* Your app content */}
1705
+ <Outlet />
1706
+ </div>
1707
+ </HumanBehaviorProvider>
1708
+ );
1709
+ }`,
1710
+ description: 'Remix root component with HumanBehaviorProvider'
1711
+ });
1712
+ break;
1713
+
1714
+ case 'vue':
1715
+ modifications.push({
1716
+ filePath: 'main.js',
1717
+ action: 'create',
1718
+ content: `import { createApp } from 'vue';
1719
+ import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';
1720
+ import App from './App.vue';
1721
+
1722
+ const app = createApp(App);
1723
+ app.use(HumanBehaviorPlugin, {
1724
+ apiKey: '${this.apiKey}'
1725
+ });
1726
+ app.mount('#app');`,
1727
+ description: 'Vue app with HumanBehaviorPlugin'
1728
+ });
1729
+ break;
1730
+
1731
+ default:
1732
+ modifications.push({
1733
+ filePath: 'humanbehavior-init.js',
1734
+ action: 'create',
1735
+ content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
1736
+
1737
+ const tracker = HumanBehaviorTracker.init('${this.apiKey}');`,
1738
+ description: 'Vanilla JS initialization'
1739
+ });
1740
+ }
1741
+
1742
+ return modifications;
1743
+ }
1744
+ }