humanbehavior-js 0.4.27 → 0.5.0

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 (140) hide show
  1. package/README.md +151 -0
  2. package/package.json +114 -71
  3. package/packages/angular/dist/index.d.ts +46 -0
  4. package/packages/angular/dist/index.d.ts.map +1 -0
  5. package/packages/angular/dist/index.js +2 -0
  6. package/packages/angular/dist/index.js.map +1 -0
  7. package/packages/angular/dist/index.mjs +2 -0
  8. package/packages/angular/dist/index.mjs.map +1 -0
  9. package/packages/browser/dist/index.d.ts +5 -0
  10. package/packages/browser/dist/index.d.ts.map +1 -0
  11. package/packages/browser/dist/index.iife.js +12095 -0
  12. package/packages/browser/dist/index.iife.js.map +1 -0
  13. package/packages/browser/dist/index.js +2 -0
  14. package/packages/browser/dist/index.js.map +1 -0
  15. package/packages/browser/dist/index.min.js +2 -0
  16. package/packages/browser/dist/index.min.js.map +1 -0
  17. package/packages/browser/dist/index.mjs +2 -0
  18. package/packages/browser/dist/index.mjs.map +1 -0
  19. package/packages/react/dist/browser.d.ts +2 -0
  20. package/packages/react/dist/browser.d.ts.map +1 -0
  21. package/packages/react/dist/index.d.ts +48 -0
  22. package/packages/react/dist/index.d.ts.map +1 -0
  23. package/packages/react/dist/index.js +2 -0
  24. package/packages/react/dist/index.js.map +1 -0
  25. package/packages/react/dist/index.mjs +2 -0
  26. package/packages/react/dist/index.mjs.map +1 -0
  27. package/packages/remix/dist/index.d.ts +8 -0
  28. package/packages/remix/dist/index.d.ts.map +1 -0
  29. package/packages/remix/dist/index.js +2 -0
  30. package/packages/remix/dist/index.js.map +1 -0
  31. package/packages/remix/dist/index.mjs +2 -0
  32. package/packages/remix/dist/index.mjs.map +1 -0
  33. package/packages/svelte/dist/index.d.ts +11 -0
  34. package/packages/svelte/dist/index.d.ts.map +1 -0
  35. package/packages/svelte/dist/index.js +2 -0
  36. package/packages/svelte/dist/index.js.map +1 -0
  37. package/packages/svelte/dist/index.mjs +2 -0
  38. package/packages/svelte/dist/index.mjs.map +1 -0
  39. package/{dist/types/vue → packages/vue/dist}/index.d.ts +4 -5
  40. package/packages/vue/dist/index.d.ts.map +1 -0
  41. package/packages/vue/dist/index.js +2 -0
  42. package/packages/vue/dist/index.js.map +1 -0
  43. package/packages/vue/dist/index.mjs +2 -0
  44. package/packages/vue/dist/index.mjs.map +1 -0
  45. package/packages/wizard/dist/ai/ai-install-wizard.d.ts +145 -0
  46. package/packages/wizard/dist/ai/ai-install-wizard.d.ts.map +1 -0
  47. package/packages/wizard/dist/ai/manual-framework-wizard.d.ts +52 -0
  48. package/packages/wizard/dist/ai/manual-framework-wizard.d.ts.map +1 -0
  49. package/packages/wizard/dist/cli/ai-auto-install.d.ts +27 -0
  50. package/packages/wizard/dist/cli/ai-auto-install.d.ts.map +1 -0
  51. package/{dist → packages/wizard/dist}/cli/ai-auto-install.js +821 -905
  52. package/packages/wizard/dist/cli/ai-auto-install.js.map +1 -0
  53. package/packages/wizard/dist/cli/auto-install.d.ts +26 -0
  54. package/packages/wizard/dist/cli/auto-install.d.ts.map +1 -0
  55. package/{dist → packages/wizard/dist}/cli/auto-install.js +821 -905
  56. package/packages/wizard/dist/cli/auto-install.js.map +1 -0
  57. package/{dist/types → packages/wizard/dist/core}/install-wizard.d.ts +6 -8
  58. package/packages/wizard/dist/core/install-wizard.d.ts.map +1 -0
  59. package/packages/wizard/dist/index.d.ts +18 -0
  60. package/packages/wizard/dist/index.d.ts.map +1 -0
  61. package/packages/wizard/dist/index.js +2 -0
  62. package/packages/wizard/dist/index.js.map +1 -0
  63. package/packages/wizard/dist/index.mjs +2 -0
  64. package/packages/wizard/dist/index.mjs.map +1 -0
  65. package/packages/wizard/dist/services/centralized-ai-service.d.ts +159 -0
  66. package/packages/wizard/dist/services/centralized-ai-service.d.ts.map +1 -0
  67. package/packages/wizard/dist/services/remote-ai-service.d.ts +58 -0
  68. package/packages/wizard/dist/services/remote-ai-service.d.ts.map +1 -0
  69. package/WIZARD_USAGE_GUIDE.md +0 -381
  70. package/dist/cjs/angular/index.cjs +0 -14979
  71. package/dist/cjs/angular/index.cjs.map +0 -1
  72. package/dist/cjs/index.cjs +0 -14964
  73. package/dist/cjs/index.cjs.map +0 -1
  74. package/dist/cjs/install-wizard.cjs +0 -1576
  75. package/dist/cjs/install-wizard.cjs.map +0 -1
  76. package/dist/cjs/react/index.cjs +0 -15103
  77. package/dist/cjs/react/index.cjs.map +0 -1
  78. package/dist/cjs/remix/index.cjs +0 -15077
  79. package/dist/cjs/remix/index.cjs.map +0 -1
  80. package/dist/cjs/svelte/index.cjs +0 -14933
  81. package/dist/cjs/svelte/index.cjs.map +0 -1
  82. package/dist/cjs/vue/index.cjs +0 -14942
  83. package/dist/cjs/vue/index.cjs.map +0 -1
  84. package/dist/cjs/wizard/index.cjs +0 -3490
  85. package/dist/cjs/wizard/index.cjs.map +0 -1
  86. package/dist/cli/ai-auto-install.js.map +0 -1
  87. package/dist/cli/auto-install.js.map +0 -1
  88. package/dist/esm/angular/index.js +0 -14975
  89. package/dist/esm/angular/index.js.map +0 -1
  90. package/dist/esm/index.js +0 -14941
  91. package/dist/esm/index.js.map +0 -1
  92. package/dist/esm/install-wizard.js +0 -1553
  93. package/dist/esm/install-wizard.js.map +0 -1
  94. package/dist/esm/react/index.js +0 -15097
  95. package/dist/esm/react/index.js.map +0 -1
  96. package/dist/esm/remix/index.js +0 -15073
  97. package/dist/esm/remix/index.js.map +0 -1
  98. package/dist/esm/svelte/index.js +0 -14931
  99. package/dist/esm/svelte/index.js.map +0 -1
  100. package/dist/esm/vue/index.js +0 -14940
  101. package/dist/esm/vue/index.js.map +0 -1
  102. package/dist/esm/wizard/index.js +0 -3459
  103. package/dist/esm/wizard/index.js.map +0 -1
  104. package/dist/index.min.js +0 -2
  105. package/dist/index.min.js.map +0 -1
  106. package/dist/types/angular/index.d.ts +0 -357
  107. package/dist/types/index.d.ts +0 -644
  108. package/dist/types/react/index.d.ts +0 -345
  109. package/dist/types/remix/index.d.ts +0 -336
  110. package/dist/types/svelte/index.d.ts +0 -322
  111. package/dist/types/wizard/index.d.ts +0 -523
  112. package/readme.md +0 -335
  113. package/rollup.config.js +0 -422
  114. package/simple-spa.html +0 -1000
  115. package/src/angular/index.ts +0 -79
  116. package/src/api.ts +0 -416
  117. package/src/index.ts +0 -35
  118. package/src/react/AutoInstallWizard.tsx +0 -557
  119. package/src/react/browser.ts +0 -8
  120. package/src/react/index.tsx +0 -308
  121. package/src/redact.ts +0 -327
  122. package/src/remix/index.ts +0 -16
  123. package/src/svelte/index.ts +0 -14
  124. package/src/tracker.ts +0 -1587
  125. package/src/types/clack.d.ts +0 -31
  126. package/src/utils/ip-detector.ts +0 -158
  127. package/src/utils/logger.ts +0 -144
  128. package/src/utils/property-detector.ts +0 -345
  129. package/src/utils/property-manager.ts +0 -274
  130. package/src/vue/index.ts +0 -29
  131. package/src/wizard/README.md +0 -114
  132. package/src/wizard/ai/ai-install-wizard.ts +0 -897
  133. package/src/wizard/ai/manual-framework-wizard.ts +0 -238
  134. package/src/wizard/cli/ai-auto-install.ts +0 -241
  135. package/src/wizard/cli/auto-install.ts +0 -224
  136. package/src/wizard/core/install-wizard.ts +0 -1794
  137. package/src/wizard/index.ts +0 -23
  138. package/src/wizard/services/centralized-ai-service.ts +0 -668
  139. package/src/wizard/services/remote-ai-service.ts +0 -240
  140. package/tsconfig.json +0 -24
@@ -1,1553 +0,0 @@
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 with latest version range
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 with latest version range
295
- let command = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.packageManager) === 'yarn'
296
- ? 'yarn add humanbehavior-js@latest'
297
- : ((_b = this.framework) === null || _b === void 0 ? void 0 : _b.packageManager) === 'pnpm'
298
- ? 'pnpm add humanbehavior-js@latest'
299
- : 'npm install humanbehavior-js@latest';
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 files (proper Angular way)
658
- const envFile = path.join(this.projectRoot, 'src', 'environments', 'environment.ts');
659
- const envProdFile = path.join(this.projectRoot, 'src', 'environments', 'environment.prod.ts');
660
- // Create environments directory if it doesn't exist
661
- const envDir = path.dirname(envFile);
662
- if (!fs.existsSync(envDir)) {
663
- fs.mkdirSync(envDir, { recursive: true });
664
- }
665
- // Create or update development environment
666
- if (fs.existsSync(envFile)) {
667
- const content = fs.readFileSync(envFile, 'utf8');
668
- if (!content.includes('humanBehaviorApiKey')) {
669
- const modifiedContent = content.replace(/export const environment = {([\s\S]*?)};/, `export const environment = {
670
- $1,
671
- humanBehaviorApiKey: '${this.apiKey}'
672
- };`);
673
- modifications.push({
674
- filePath: envFile,
675
- action: 'modify',
676
- content: modifiedContent,
677
- description: 'Added API key to Angular development environment'
678
- });
679
- }
680
- }
681
- else {
682
- // Create new development environment file
683
- modifications.push({
684
- filePath: envFile,
685
- action: 'create',
686
- content: `export const environment = {
687
- production: false,
688
- humanBehaviorApiKey: '${this.apiKey}'
689
- };`,
690
- description: 'Created Angular development environment file'
691
- });
692
- }
693
- // Create or update production environment
694
- if (fs.existsSync(envProdFile)) {
695
- const content = fs.readFileSync(envProdFile, 'utf8');
696
- if (!content.includes('humanBehaviorApiKey')) {
697
- const modifiedContent = content.replace(/export const environment = {([\s\S]*?)};/, `export const environment = {
698
- $1,
699
- humanBehaviorApiKey: '${this.apiKey}'
700
- };`);
701
- modifications.push({
702
- filePath: envProdFile,
703
- action: 'modify',
704
- content: modifiedContent,
705
- description: 'Added API key to Angular production environment'
706
- });
707
- }
708
- }
709
- else {
710
- // Create new production environment file
711
- modifications.push({
712
- filePath: envProdFile,
713
- action: 'create',
714
- content: `export const environment = {
715
- production: true,
716
- humanBehaviorApiKey: '${this.apiKey}'
717
- };`,
718
- description: 'Created Angular production environment file'
719
- });
720
- }
721
- // For Angular, we don't need .env files since we use environment.ts
722
- // The environment files are already created above
723
- return modifications;
724
- });
725
- }
726
- /**
727
- * Generate Svelte-specific modifications
728
- */
729
- generateSvelteModifications() {
730
- return __awaiter(this, void 0, void 0, function* () {
731
- const modifications = [];
732
- // Check for SvelteKit
733
- const svelteConfigFile = path.join(this.projectRoot, 'svelte.config.js');
734
- const isSvelteKit = fs.existsSync(svelteConfigFile);
735
- if (isSvelteKit) {
736
- // SvelteKit - create layout file
737
- const layoutFile = path.join(this.projectRoot, 'src', 'routes', '+layout.svelte');
738
- if (fs.existsSync(layoutFile)) {
739
- const content = fs.readFileSync(layoutFile, 'utf8');
740
- const modifiedContent = this.injectSvelteKitLayout(content);
741
- modifications.push({
742
- filePath: layoutFile,
743
- action: 'modify',
744
- content: modifiedContent,
745
- description: 'Added HumanBehavior store to SvelteKit layout'
746
- });
747
- }
748
- }
749
- else {
750
- // Regular Svelte - modify main file
751
- const mainFile = this.findSvelteMainFile();
752
- if (mainFile) {
753
- const content = fs.readFileSync(mainFile, 'utf8');
754
- const modifiedContent = this.injectSvelteStore(content);
755
- modifications.push({
756
- filePath: mainFile,
757
- action: 'modify',
758
- content: modifiedContent,
759
- description: 'Added HumanBehavior store to Svelte app'
760
- });
761
- }
762
- }
763
- // Create or append to environment file
764
- modifications.push(this.createEnvironmentModification(this.framework));
765
- return modifications;
766
- });
767
- }
768
- /**
769
- * Generate vanilla JS/TS modifications
770
- */
771
- generateVanillaModifications() {
772
- return __awaiter(this, void 0, void 0, function* () {
773
- const modifications = [];
774
- // Find HTML file to inject script
775
- const htmlFile = this.findHTMLFile();
776
- if (htmlFile) {
777
- const content = fs.readFileSync(htmlFile, 'utf8');
778
- const modifiedContent = this.injectVanillaScript(content);
779
- modifications.push({
780
- filePath: htmlFile,
781
- action: 'modify',
782
- content: modifiedContent,
783
- description: 'Added HumanBehavior CDN script to HTML file'
784
- });
785
- }
786
- // Create or append to environment file
787
- modifications.push(this.createEnvironmentModification(this.framework));
788
- return modifications;
789
- });
790
- }
791
- /**
792
- * Generate Gatsby-specific modifications
793
- */
794
- generateGatsbyModifications() {
795
- return __awaiter(this, void 0, void 0, function* () {
796
- const modifications = [];
797
- // Modify or create gatsby-browser.js for Gatsby
798
- const gatsbyBrowserFile = path.join(this.projectRoot, 'gatsby-browser.js');
799
- if (fs.existsSync(gatsbyBrowserFile)) {
800
- const content = fs.readFileSync(gatsbyBrowserFile, 'utf8');
801
- const modifiedContent = this.injectGatsbyBrowser(content);
802
- modifications.push({
803
- filePath: gatsbyBrowserFile,
804
- action: 'modify',
805
- content: modifiedContent,
806
- description: 'Added HumanBehavior initialization to Gatsby browser'
807
- });
808
- }
809
- else {
810
- // Create gatsby-browser.js if it doesn't exist
811
- modifications.push({
812
- filePath: gatsbyBrowserFile,
813
- action: 'create',
814
- content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
815
-
816
- export const onClientEntry = () => {
817
- console.log('Gatsby browser entry point loaded');
818
- const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;
819
- console.log('API Key found:', apiKey ? 'Yes' : 'No');
820
- if (apiKey) {
821
- const tracker = HumanBehaviorTracker.init(apiKey);
822
- console.log('HumanBehavior SDK initialized for Gatsby');
823
- } else {
824
- console.log('No API key found in environment variables');
825
- }
826
- };`,
827
- description: 'Created gatsby-browser.js with HumanBehavior initialization'
828
- });
829
- }
830
- // Create or append to environment file
831
- modifications.push(this.createEnvironmentModification(this.framework));
832
- return modifications;
833
- });
834
- }
835
- /**
836
- * Apply modifications to the codebase
837
- */
838
- applyModifications(modifications) {
839
- return __awaiter(this, void 0, void 0, function* () {
840
- for (const modification of modifications) {
841
- try {
842
- const dir = path.dirname(modification.filePath);
843
- if (!fs.existsSync(dir)) {
844
- fs.mkdirSync(dir, { recursive: true });
845
- }
846
- switch (modification.action) {
847
- case 'create':
848
- fs.writeFileSync(modification.filePath, modification.content);
849
- break;
850
- case 'modify':
851
- fs.writeFileSync(modification.filePath, modification.content);
852
- break;
853
- case 'append':
854
- fs.appendFileSync(modification.filePath, '\n' + modification.content);
855
- break;
856
- }
857
- }
858
- catch (error) {
859
- throw new Error(`Failed to apply modification to ${modification.filePath}: ${error}`);
860
- }
861
- }
862
- });
863
- }
864
- /**
865
- * Generate next steps for the user
866
- */
867
- generateNextSteps() {
868
- var _a, _b;
869
- const steps = [
870
- '✅ SDK installed and configured automatically!',
871
- '🚀 Your app is now tracking user behavior',
872
- '📊 View sessions in your HumanBehavior dashboard',
873
- '🔧 Customize tracking in your code as needed'
874
- ];
875
- 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') {
876
- steps.push('💡 Use the useHumanBehavior() hook to track custom events');
877
- }
878
- return steps;
879
- }
880
- // Helper methods for file detection and content injection
881
- findReactAppFile() {
882
- const possibleFiles = [
883
- 'src/App.jsx', 'src/App.js', 'src/App.tsx', 'src/App.ts',
884
- 'src/index.js', 'src/index.tsx', 'src/main.js', 'src/main.tsx'
885
- ];
886
- for (const file of possibleFiles) {
887
- const fullPath = path.join(this.projectRoot, file);
888
- if (fs.existsSync(fullPath)) {
889
- return fullPath;
890
- }
891
- }
892
- return null;
893
- }
894
- findVueMainFile() {
895
- const possibleFiles = [
896
- 'src/main.js', 'src/main.ts', 'src/main.jsx', 'src/main.tsx'
897
- ];
898
- for (const file of possibleFiles) {
899
- const fullPath = path.join(this.projectRoot, file);
900
- if (fs.existsSync(fullPath)) {
901
- return fullPath;
902
- }
903
- }
904
- return null;
905
- }
906
- findSvelteMainFile() {
907
- const possibleFiles = [
908
- 'src/main.js', 'src/main.ts', 'src/main.svelte'
909
- ];
910
- for (const file of possibleFiles) {
911
- const fullPath = path.join(this.projectRoot, file);
912
- if (fs.existsSync(fullPath)) {
913
- return fullPath;
914
- }
915
- }
916
- return null;
917
- }
918
- findHTMLFile() {
919
- const possibleFiles = ['index.html', 'public/index.html', 'dist/index.html'];
920
- for (const file of possibleFiles) {
921
- const fullPath = path.join(this.projectRoot, file);
922
- if (fs.existsSync(fullPath)) {
923
- return fullPath;
924
- }
925
- }
926
- return null;
927
- }
928
- injectReactProvider(content, filePath) {
929
- var _a, _b, _c;
930
- filePath.endsWith('.tsx') || filePath.endsWith('.ts');
931
- // Check if already has HumanBehaviorProvider
932
- if (content.includes('HumanBehaviorProvider')) {
933
- return content;
934
- }
935
- // Determine the correct environment variable syntax based on bundler
936
- const isVite = ((_a = this.framework) === null || _a === void 0 ? void 0 : _a.bundler) === 'vite';
937
- const envVar = isVite
938
- ? 'import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!'
939
- : 'process.env.HUMANBEHAVIOR_API_KEY!';
940
- const importStatement = `import { HumanBehaviorProvider } from 'humanbehavior-js/react';`;
941
- // Enhanced parsing for React 18+ features
942
- const hasReact18 = (_c = (_b = this.framework) === null || _b === void 0 ? void 0 : _b.features) === null || _c === void 0 ? void 0 : _c.hasReact18;
943
- // Handle different React patterns
944
- if (content.includes('function App()') || content.includes('const App =')) {
945
- // Add import statement
946
- let modifiedContent = content.replace(/(import.*?from.*?['"]react['"];?)/, `$1\n${importStatement}`);
947
- // If no React import found, add it at the top
948
- if (!modifiedContent.includes(importStatement)) {
949
- modifiedContent = `${importStatement}\n\n${modifiedContent}`;
950
- }
951
- // Wrap the App component return with HumanBehaviorProvider
952
- modifiedContent = modifiedContent.replace(/(return\s*\([\s\S]*?\)\s*;)/, `return (
953
- <HumanBehaviorProvider apiKey={${envVar}}>
954
- $1
955
- </HumanBehaviorProvider>
956
- );`);
957
- return modifiedContent;
958
- }
959
- // Handle React 18+ createRoot pattern
960
- if (hasReact18 && content.includes('createRoot')) {
961
- let modifiedContent = content.replace(/(import.*?from.*?['"]react['"];?)/, `$1\n${importStatement}`);
962
- if (!modifiedContent.includes(importStatement)) {
963
- modifiedContent = `${importStatement}\n\n${modifiedContent}`;
964
- }
965
- // Wrap the root render with HumanBehaviorProvider
966
- modifiedContent = modifiedContent.replace(/(root\.render\s*\([\s\S]*?\)\s*;)/, `root.render(
967
- <HumanBehaviorProvider apiKey={${envVar}}>
968
- $1
969
- </HumanBehaviorProvider>
970
- );`);
971
- return modifiedContent;
972
- }
973
- // Fallback: simple injection
974
- return `${importStatement}\n\n${content}`;
975
- }
976
- injectNextJSAppRouter(content) {
977
- if (content.includes('Providers')) {
978
- return content;
979
- }
980
- const importStatement = `import { Providers } from './providers';`;
981
- // First, add the import statement
982
- let modifiedContent = content.replace(/export default function RootLayout/, `${importStatement}\n\nexport default function RootLayout`);
983
- // Then wrap the body content with Providers
984
- // Use a more specific approach to handle the body content
985
- modifiedContent = modifiedContent.replace(/<body([^>]*)>([\s\S]*?)<\/body>/, (match, bodyAttrs, bodyContent) => {
986
- // Trim whitespace and newlines from bodyContent
987
- const trimmedContent = bodyContent.trim();
988
- return `<body${bodyAttrs}>
989
- <Providers>
990
- ${trimmedContent}
991
- </Providers>
992
- </body>`;
993
- });
994
- return modifiedContent;
995
- }
996
- injectNextJSPagesRouter(content) {
997
- if (content.includes('Providers')) {
998
- return content;
999
- }
1000
- const importStatement = `import { Providers } from '../components/providers';`;
1001
- return content.replace(/function MyApp/, `${importStatement}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/, `return (
1002
- <Providers>
1003
- $1
1004
- </Providers>
1005
- );`);
1006
- }
1007
- injectRemixProvider(content) {
1008
- if (content.includes('HumanBehaviorProvider')) {
1009
- return content;
1010
- }
1011
- const importStatement = `import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';`;
1012
- const useLoaderDataImport = `import { useLoaderData } from "@remix-run/react";`;
1013
- // Add imports more robustly
1014
- let modifiedContent = content;
1015
- // Add HumanBehaviorProvider import - find the last import and add after it
1016
- if (!content.includes('HumanBehaviorProvider')) {
1017
- const lastImportIndex = modifiedContent.lastIndexOf('import');
1018
- if (lastImportIndex !== -1) {
1019
- const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
1020
- if (nextLineIndex !== -1) {
1021
- modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
1022
- importStatement + '\n' +
1023
- modifiedContent.slice(nextLineIndex + 1);
1024
- }
1025
- else {
1026
- modifiedContent = modifiedContent + '\n' + importStatement;
1027
- }
1028
- }
1029
- else {
1030
- modifiedContent = importStatement + '\n' + modifiedContent;
1031
- }
1032
- }
1033
- // Add useLoaderData import - find the last import and add after it
1034
- if (!content.includes('useLoaderData')) {
1035
- const lastImportIndex = modifiedContent.lastIndexOf('import');
1036
- if (lastImportIndex !== -1) {
1037
- const nextLineIndex = modifiedContent.indexOf('\n', lastImportIndex);
1038
- if (nextLineIndex !== -1) {
1039
- modifiedContent = modifiedContent.slice(0, nextLineIndex + 1) +
1040
- useLoaderDataImport + '\n' +
1041
- modifiedContent.slice(nextLineIndex + 1);
1042
- }
1043
- else {
1044
- modifiedContent = modifiedContent + '\n' + useLoaderDataImport;
1045
- }
1046
- }
1047
- else {
1048
- modifiedContent = useLoaderDataImport + '\n' + modifiedContent;
1049
- }
1050
- }
1051
- // Add loader function before the App component
1052
- if (!content.includes('export const loader')) {
1053
- modifiedContent = modifiedContent.replace(/export default function App\(\)/, `export const loader = createHumanBehaviorLoader();
1054
-
1055
- export default function App()`);
1056
- }
1057
- // Wrap the App component content with HumanBehaviorProvider
1058
- modifiedContent = modifiedContent.replace(/export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/, `export default function App() {
1059
- const data = useLoaderData<typeof loader>();
1060
-
1061
- return (
1062
- <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
1063
- $1
1064
- </HumanBehaviorProvider>
1065
- );
1066
- }`);
1067
- return modifiedContent;
1068
- }
1069
- injectVuePlugin(content) {
1070
- var _a, _b;
1071
- if (content.includes('HumanBehaviorPlugin')) {
1072
- return content;
1073
- }
1074
- const importStatement = `import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';`;
1075
- // Enhanced Vue 3 support with version detection
1076
- const hasVue3 = (_b = (_a = this.framework) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.hasVue3;
1077
- if (hasVue3) {
1078
- // Vue 3 with Composition API
1079
- const pluginUsage = `app.use(HumanBehaviorPlugin, {
1080
- apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY
1081
- });`;
1082
- let modifiedContent = content;
1083
- // Add import statement
1084
- if (!content.includes(importStatement)) {
1085
- modifiedContent = content.replace(/(import.*?from.*?['"]vue['"];?)/, `$1\n${importStatement}`);
1086
- // If no Vue import found, add it at the top
1087
- if (!modifiedContent.includes(importStatement)) {
1088
- modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1089
- }
1090
- }
1091
- // Handle createApp pattern
1092
- if (content.includes('createApp')) {
1093
- modifiedContent = modifiedContent.replace(/(app\.mount\(.*?\))/, `${pluginUsage}\n\n$1`);
1094
- }
1095
- return modifiedContent;
1096
- }
1097
- else {
1098
- // Vue 2 with Options API
1099
- const pluginUsage = `Vue.use(HumanBehaviorPlugin, {
1100
- apiKey: process.env.VUE_APP_HUMANBEHAVIOR_API_KEY
1101
- });`;
1102
- let modifiedContent = content;
1103
- // Add import statement
1104
- if (!content.includes(importStatement)) {
1105
- modifiedContent = content.replace(/(import.*?from.*?['"]vue['"];?)/, `$1\n${importStatement}`);
1106
- if (!modifiedContent.includes(importStatement)) {
1107
- modifiedContent = `${importStatement}\n\n${modifiedContent}`;
1108
- }
1109
- }
1110
- // Handle new Vue pattern
1111
- if (content.includes('new Vue')) {
1112
- modifiedContent = modifiedContent.replace(/(new Vue\(.*?\))/, `${pluginUsage}\n\n$1`);
1113
- }
1114
- return modifiedContent;
1115
- }
1116
- }
1117
- injectAngularModule(content) {
1118
- if (content.includes('HumanBehaviorModule')) {
1119
- return content;
1120
- }
1121
- const importStatement = `import { HumanBehaviorModule } from 'humanbehavior-js/angular';`;
1122
- const environmentImport = `import { environment } from '../environments/environment';`;
1123
- // Add environment import if not present
1124
- let modifiedContent = content;
1125
- if (!content.includes('environment')) {
1126
- modifiedContent = content.replace(/import.*from.*['"]@angular/, `${environmentImport}\n$&`);
1127
- }
1128
- return modifiedContent.replace(/imports:\s*\[([\s\S]*?)\]/, `imports: [
1129
- $1,
1130
- HumanBehaviorModule.forRoot({
1131
- apiKey: environment.humanBehaviorApiKey
1132
- })
1133
- ]`).replace(/import.*from.*['"]@angular/, `$&\n${importStatement}`);
1134
- }
1135
- injectAngularStandaloneInit(content) {
1136
- if (content.includes('initializeHumanBehavior')) {
1137
- return content;
1138
- }
1139
- const importStatement = `import { initializeHumanBehavior } from 'humanbehavior-js/angular';`;
1140
- const environmentImport = `import { environment } from './environments/environment';`;
1141
- // Add imports at the top
1142
- let modifiedContent = content.replace(/import.*from.*['"]@angular/, `${importStatement}\n${environmentImport}\n$&`);
1143
- // Add initialization after bootstrapApplication
1144
- modifiedContent = modifiedContent.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/, `$1
1145
-
1146
- // Initialize HumanBehavior SDK (client-side only)
1147
- if (typeof window !== 'undefined') {
1148
- const tracker = initializeHumanBehavior(environment.humanBehaviorApiKey);
1149
- }`);
1150
- return modifiedContent;
1151
- }
1152
- injectSvelteStore(content) {
1153
- if (content.includes('humanBehaviorStore')) {
1154
- return content;
1155
- }
1156
- const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
1157
- const initCode = `humanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
1158
- return `${importStatement}\n${initCode}\n\n${content}`;
1159
- }
1160
- injectSvelteKitLayout(content) {
1161
- if (content.includes('humanBehaviorStore')) {
1162
- return content;
1163
- }
1164
- const importStatement = `import { humanBehaviorStore } from 'humanbehavior-js/svelte';`;
1165
- const envImport = `import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';`;
1166
- const initCode = `humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');`;
1167
- // Add to script section - handle different script tag patterns
1168
- if (content.includes('<script lang="ts">')) {
1169
- return content.replace(/<script lang="ts">/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
1170
- }
1171
- else if (content.includes('<script>')) {
1172
- return content.replace(/<script>/, `<script>\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
1173
- }
1174
- else if (content.includes('<script context="module">')) {
1175
- return content.replace(/<script\s+context="module">/, `<script context="module">\n\t${envImport}\n\t${importStatement}\n\t${initCode}`);
1176
- }
1177
- else {
1178
- // If no script tag found, add one at the beginning
1179
- return content.replace(/<svelte:head>/, `<script lang="ts">\n\t${envImport}\n\t${importStatement}\n\t${initCode}\n</script>\n\n<svelte:head>`);
1180
- }
1181
- }
1182
- injectVanillaScript(content) {
1183
- if (content.includes('humanbehavior-js')) {
1184
- return content;
1185
- }
1186
- const cdnScript = `<script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"></script>`;
1187
- const initScript = `<script>
1188
- // Initialize HumanBehavior SDK
1189
- // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available
1190
- const tracker = HumanBehaviorTracker.init('${this.apiKey}');
1191
- </script>`;
1192
- return content.replace(/<\/head>/, ` ${cdnScript}\n ${initScript}\n</head>`);
1193
- }
1194
- /**
1195
- * Inject Astro layout with HumanBehavior component
1196
- */
1197
- injectAstroLayout(content) {
1198
- // Check if HumanBehavior component is already imported
1199
- if (content.includes('HumanBehavior') || content.includes('humanbehavior-js')) {
1200
- return content; // Already has HumanBehavior
1201
- }
1202
- // Add import inside frontmatter if not present
1203
- let modifiedContent = content;
1204
- if (!content.includes('import HumanBehavior')) {
1205
- const importStatement = 'import HumanBehavior from \'../components/HumanBehavior.astro\';';
1206
- const frontmatterEndIndex = content.indexOf('---', 3);
1207
- if (frontmatterEndIndex !== -1) {
1208
- // Insert import inside frontmatter, before the closing ---
1209
- modifiedContent = content.slice(0, frontmatterEndIndex) + '\n' + importStatement + '\n' + content.slice(frontmatterEndIndex);
1210
- }
1211
- else {
1212
- // No frontmatter, add at the very beginning
1213
- modifiedContent = '---\n' + importStatement + '\n---\n\n' + content;
1214
- }
1215
- }
1216
- // Find the closing </body> tag and add HumanBehavior component before it
1217
- const bodyCloseIndex = modifiedContent.lastIndexOf('</body>');
1218
- if (bodyCloseIndex === -1) {
1219
- // No body tag found, append to end
1220
- return modifiedContent + '\n\n<HumanBehavior />';
1221
- }
1222
- // Add component before closing body tag
1223
- return modifiedContent.slice(0, bodyCloseIndex) + ' <HumanBehavior />\n' + modifiedContent.slice(bodyCloseIndex);
1224
- }
1225
- injectNuxtConfig(content) {
1226
- var _a, _b;
1227
- if (content.includes('humanBehaviorApiKey')) {
1228
- return content;
1229
- }
1230
- // Enhanced Nuxt 3 support with version detection
1231
- const hasNuxt3 = (_b = (_a = this.framework) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.hasNuxt3;
1232
- if (hasNuxt3) {
1233
- // Nuxt 3 with runtime config
1234
- return content.replace(/export default defineNuxtConfig\(\{/, `export default defineNuxtConfig({
1235
- runtimeConfig: {
1236
- public: {
1237
- humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY
1238
- }
1239
- },`);
1240
- }
1241
- else {
1242
- // Nuxt 2 with env config
1243
- return content.replace(/export default \{/, `export default {
1244
- env: {
1245
- humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY
1246
- },`);
1247
- }
1248
- }
1249
- injectGatsbyLayout(content) {
1250
- if (content.includes('HumanBehavior')) {
1251
- return content;
1252
- }
1253
- const importStatement = `import HumanBehavior from './HumanBehavior';`;
1254
- const componentUsage = `<HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />`;
1255
- // Add import at the top
1256
- let modifiedContent = content.replace(/import.*from.*['"]\./, `${importStatement}\n$&`);
1257
- // Add component before closing body tag
1258
- modifiedContent = modifiedContent.replace(/(\s*<\/body>)/, `\n ${componentUsage}\n$1`);
1259
- return modifiedContent;
1260
- }
1261
- injectGatsbyBrowser(content) {
1262
- if (content.includes('HumanBehaviorTracker')) {
1263
- return content;
1264
- }
1265
- const importStatement = `import { HumanBehaviorTracker } from 'humanbehavior-js';`;
1266
- const initCode = `
1267
- // Initialize HumanBehavior SDK
1268
- export const onClientEntry = () => {
1269
- console.log('Gatsby browser entry point loaded');
1270
- const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;
1271
- console.log('API Key found:', apiKey ? 'Yes' : 'No');
1272
- if (apiKey) {
1273
- const tracker = HumanBehaviorTracker.init(apiKey);
1274
- console.log('HumanBehavior SDK initialized for Gatsby');
1275
- } else {
1276
- console.log('No API key found in environment variables');
1277
- }
1278
- };`;
1279
- // If the file already has content, add the import and init code
1280
- if (content.trim()) {
1281
- return `${importStatement}${initCode}\n\n${content}`;
1282
- }
1283
- else {
1284
- // If file is empty, just return the new content
1285
- return `${importStatement}${initCode}`;
1286
- }
1287
- }
1288
- /**
1289
- * Helper method to find the best environment file for a framework
1290
- */
1291
- findBestEnvFile(framework) {
1292
- const possibleEnvFiles = [
1293
- '.env.local',
1294
- '.env.development.local',
1295
- '.env.development',
1296
- '.env.local.development',
1297
- '.env',
1298
- '.env.production',
1299
- '.env.staging'
1300
- ];
1301
- // Framework-specific environment variable names
1302
- const getEnvVarName = (framework) => {
1303
- // Handle React+Vite specifically
1304
- if (framework.type === 'react' && framework.bundler === 'vite') {
1305
- return 'VITE_HUMANBEHAVIOR_API_KEY';
1306
- }
1307
- // Framework-specific mappings
1308
- const envVarNames = {
1309
- react: 'HUMANBEHAVIOR_API_KEY',
1310
- nextjs: 'NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
1311
- vue: 'VITE_HUMANBEHAVIOR_API_KEY',
1312
- svelte: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
1313
- angular: 'HUMANBEHAVIOR_API_KEY',
1314
- nuxt: 'NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY',
1315
- remix: 'HUMANBEHAVIOR_API_KEY',
1316
- vanilla: 'HUMANBEHAVIOR_API_KEY',
1317
- astro: 'PUBLIC_HUMANBEHAVIOR_API_KEY',
1318
- gatsby: 'GATSBY_HUMANBEHAVIOR_API_KEY',
1319
- node: 'HUMANBEHAVIOR_API_KEY',
1320
- auto: 'HUMANBEHAVIOR_API_KEY'
1321
- };
1322
- return envVarNames[framework.type] || 'HUMANBEHAVIOR_API_KEY';
1323
- };
1324
- const envVarName = getEnvVarName(framework);
1325
- // Check for existing files
1326
- for (const envFile of possibleEnvFiles) {
1327
- const fullPath = path.join(this.projectRoot, envFile);
1328
- if (fs.existsSync(fullPath)) {
1329
- return { filePath: fullPath, envVarName };
1330
- }
1331
- }
1332
- // Framework-specific default file creation
1333
- const defaultFiles = {
1334
- react: '.env.local',
1335
- nextjs: '.env.local',
1336
- vue: '.env.local',
1337
- svelte: '.env',
1338
- angular: '.env',
1339
- nuxt: '.env',
1340
- remix: '.env.local',
1341
- vanilla: '.env',
1342
- astro: '.env',
1343
- gatsby: '.env.development',
1344
- node: '.env',
1345
- auto: '.env'
1346
- };
1347
- const defaultFile = defaultFiles[framework.type] || '.env';
1348
- return {
1349
- filePath: path.join(this.projectRoot, defaultFile),
1350
- envVarName
1351
- };
1352
- }
1353
- /**
1354
- * Helper method to create or append to environment files
1355
- */
1356
- createEnvironmentModification(framework) {
1357
- const { filePath, envVarName } = this.findBestEnvFile(framework);
1358
- // Clean the API key to prevent formatting issues
1359
- const cleanApiKey = this.apiKey.trim();
1360
- if (fs.existsSync(filePath)) {
1361
- // Check if the variable already exists
1362
- const content = fs.readFileSync(filePath, 'utf8');
1363
- if (content.includes(envVarName)) {
1364
- // Variable exists, don't modify
1365
- return {
1366
- filePath,
1367
- action: 'modify',
1368
- content: content, // No change
1369
- description: `API key already exists in ${path.basename(filePath)}`
1370
- };
1371
- }
1372
- else {
1373
- // Append to existing file
1374
- return {
1375
- filePath,
1376
- action: 'append',
1377
- content: `\n${envVarName}=${cleanApiKey}`,
1378
- description: `Added API key to existing ${path.basename(filePath)}`
1379
- };
1380
- }
1381
- }
1382
- else {
1383
- // Create new file
1384
- return {
1385
- filePath,
1386
- action: 'create',
1387
- content: `${envVarName}=${cleanApiKey}`,
1388
- description: `Created ${path.basename(filePath)} with API key`
1389
- };
1390
- }
1391
- }
1392
- }
1393
- /**
1394
- * Browser-based auto-installation wizard
1395
- */
1396
- class BrowserAutoInstallationWizard {
1397
- constructor(apiKey) {
1398
- this.apiKey = apiKey;
1399
- }
1400
- install() {
1401
- return __awaiter(this, void 0, void 0, function* () {
1402
- try {
1403
- // Detect framework in browser
1404
- const framework = this.detectFramework();
1405
- // Generate installation instructions
1406
- const modifications = this.generateBrowserModifications(framework);
1407
- return {
1408
- success: true,
1409
- framework,
1410
- modifications,
1411
- errors: [],
1412
- nextSteps: [
1413
- '✅ Framework detected automatically',
1414
- '📋 Copy the generated code to your project',
1415
- '🚀 Your app will be ready to track user behavior'
1416
- ]
1417
- };
1418
- }
1419
- catch (error) {
1420
- return {
1421
- success: false,
1422
- framework: { name: 'unknown', type: 'vanilla' },
1423
- modifications: [],
1424
- errors: [error instanceof Error ? error.message : 'Unknown error'],
1425
- nextSteps: []
1426
- };
1427
- }
1428
- });
1429
- }
1430
- detectFramework() {
1431
- if (typeof window !== 'undefined') {
1432
- if (window.React) {
1433
- return { name: 'react', type: 'react' };
1434
- }
1435
- if (window.Vue) {
1436
- return { name: 'vue', type: 'vue' };
1437
- }
1438
- if (window.angular) {
1439
- return { name: 'angular', type: 'angular' };
1440
- }
1441
- }
1442
- return { name: 'vanilla', type: 'vanilla' };
1443
- }
1444
- generateBrowserModifications(framework) {
1445
- // Return code snippets for browser environment
1446
- const modifications = [];
1447
- switch (framework.type) {
1448
- case 'react':
1449
- modifications.push({
1450
- filePath: 'App.jsx',
1451
- action: 'create',
1452
- content: `import { HumanBehaviorProvider } from 'humanbehavior-js/react';
1453
-
1454
- function App() {
1455
- return (
1456
- <HumanBehaviorProvider apiKey="${this.apiKey}">
1457
- {/* Your app components */}
1458
- </HumanBehaviorProvider>
1459
- );
1460
- }
1461
-
1462
- export default App;`,
1463
- description: 'React component with HumanBehaviorProvider'
1464
- });
1465
- break;
1466
- case 'remix':
1467
- modifications.push({
1468
- filePath: 'app/root.tsx',
1469
- action: 'create',
1470
- content: `import {
1471
- Links,
1472
- Meta,
1473
- Outlet,
1474
- Scripts,
1475
- ScrollRestoration,
1476
- useLoaderData,
1477
- } from "@remix-run/react";
1478
- import { HumanBehaviorProvider } from 'humanbehavior-js/react';
1479
- import type { LoaderFunctionArgs } from "@remix-run/node";
1480
-
1481
- export async function loader({ request }: LoaderFunctionArgs) {
1482
- return {
1483
- ENV: {
1484
- HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,
1485
- },
1486
- };
1487
- }
1488
-
1489
- export function Layout({ children }: { children: React.ReactNode }) {
1490
- return (
1491
- <html lang="en">
1492
- <head>
1493
- <meta charSet="utf-8" />
1494
- <meta name="viewport" content="width=device-width, initial-scale=1" />
1495
- <Meta />
1496
- <Links />
1497
- </head>
1498
- <body>
1499
- {children}
1500
- <ScrollRestoration />
1501
- <Scripts />
1502
- </body>
1503
- </html>
1504
- );
1505
- }
1506
-
1507
- export default function App() {
1508
- const data = useLoaderData<typeof loader>();
1509
-
1510
- return (
1511
- <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>
1512
- <div className="min-h-screen bg-gray-50">
1513
- {/* Your app content */}
1514
- <Outlet />
1515
- </div>
1516
- </HumanBehaviorProvider>
1517
- );
1518
- }`,
1519
- description: 'Remix root component with HumanBehaviorProvider'
1520
- });
1521
- break;
1522
- case 'vue':
1523
- modifications.push({
1524
- filePath: 'main.js',
1525
- action: 'create',
1526
- content: `import { createApp } from 'vue';
1527
- import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';
1528
- import App from './App.vue';
1529
-
1530
- const app = createApp(App);
1531
- app.use(HumanBehaviorPlugin, {
1532
- apiKey: '${this.apiKey}'
1533
- });
1534
- app.mount('#app');`,
1535
- description: 'Vue app with HumanBehaviorPlugin'
1536
- });
1537
- break;
1538
- default:
1539
- modifications.push({
1540
- filePath: 'humanbehavior-init.js',
1541
- action: 'create',
1542
- content: `import { HumanBehaviorTracker } from 'humanbehavior-js';
1543
-
1544
- const tracker = HumanBehaviorTracker.init('${this.apiKey}');`,
1545
- description: 'Vanilla JS initialization'
1546
- });
1547
- }
1548
- return modifications;
1549
- }
1550
- }
1551
-
1552
- export { AutoInstallationWizard, BrowserAutoInstallationWizard };
1553
- //# sourceMappingURL=install-wizard.js.map