humanbehavior-js 0.4.15 → 0.4.17

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