humanbehavior-js 0.4.28 → 0.5.1

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