humanbehavior-js
Version:
SDK for HumanBehavior session and event recording
1 lines ⢠63.6 kB
JavaScript
"use strict";var e=require("fs"),t=require("path"),n=require("child_process"),i=require("@clack/prompts"),r="undefined"!=typeof document?document.currentScript:null;function a(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var o=a(e),s=a(t),c=a(i);class u{constructor(e,t=process.cwd()){this.framework=null,this.manualNotes=[],this.apiKey=e,this.projectRoot=t}compareVersions(e,t){const n=e.split(".").map(Number),i=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,i.length);e++){const t=n[e]||0,r=i[e]||0;if(t>r)return 1;if(t<r)return-1}return 0}isVersionGte(e,t){return this.compareVersions(e,t)>=0}getMajorVersion(e){return parseInt(e.split(".")[0])||0}async install(){try{this.framework=await this.detectFramework(),await this.installPackage();const e=await this.generateModifications();await this.applyModifications(e);const t=this.generateNextSteps();return{success:!0,framework:this.framework,modifications:e,errors:[],nextSteps:t}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[]}}}async detectFramework(){const e=s.join(this.projectRoot,"package.json");if(!o.existsSync(e))return{name:"vanilla",type:"vanilla",projectRoot:this.projectRoot};const t=JSON.parse(o.readFileSync(e,"utf8")),n={...t.dependencies,...t.devDependencies};let i={name:"vanilla",type:"vanilla",projectRoot:this.projectRoot,features:{}};if(n.nuxt){const e=n.nuxt,t=this.isVersionGte(e,"3.0.0");i={name:"nuxt",type:"nuxt",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript,hasRouter:!0,projectRoot:this.projectRoot,features:{hasNuxt3:t}}}else if(n.next){const e=n.next,t=this.isVersionGte(e,"13.0.0");i={name:"nextjs",type:"nextjs",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/node"],hasRouter:!0,projectRoot:this.projectRoot,features:{hasNextAppRouter:t}}}else if(n["@remix-run/react"]||n["@remix-run/dev"]){const e=n["@remix-run/react"]||n["@remix-run/dev"];i={name:"remix",type:"remix",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(n.react){const e=n.react,t=this.isVersionGte(e,"18.0.0");i={name:"react",type:"react",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!!n["react-router-dom"]||!!n["react-router"],projectRoot:this.projectRoot,features:{hasReact18:t}}}else if(n.vue){const e=n.vue,t=this.isVersionGte(e,"3.0.0");i={name:"vue",type:"vue",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@vue/cli-service"],hasRouter:!!n["vue-router"],projectRoot:this.projectRoot,features:{hasVue3:t}}}else if(n["@angular/core"]){const e=n["@angular/core"],t=this.isVersionGte(e,"17.0.0");i={name:"angular",type:"angular",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!0,hasRouter:!0,projectRoot:this.projectRoot,features:{hasAngularStandalone:t}}}else if(n.svelte){const e=n.svelte,t=!!n["@sveltejs/kit"];i={name:"svelte",type:"svelte",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["svelte-check"],hasRouter:!!n["svelte-routing"]||!!n["@sveltejs/kit"],projectRoot:this.projectRoot,features:{hasSvelteKit:t}}}else if(n.astro){const e=n.astro;i={name:"astro",type:"astro",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@astrojs/ts-plugin"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(n.gatsby){const e=n.gatsby;i={name:"gatsby",type:"gatsby",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!n.typescript||!!n["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}return n.vite?i.bundler="vite":n.webpack?i.bundler="webpack":n.esbuild?i.bundler="esbuild":n.rollup&&(i.bundler="rollup"),o.existsSync(s.join(this.projectRoot,"yarn.lock"))?i.packageManager="yarn":o.existsSync(s.join(this.projectRoot,"pnpm-lock.yaml"))?i.packageManager="pnpm":i.packageManager="npm",i}async installPackage(){let e="yarn"===this.framework?.packageManager?"yarn add humanbehavior-js@latest":"pnpm"===this.framework?.packageManager?"pnpm add humanbehavior-js@latest":"npm install humanbehavior-js@latest";"yarn"!==this.framework?.packageManager&&"pnpm"!==this.framework?.packageManager&&(e+=" --legacy-peer-deps");try{n.execSync(e,{cwd:this.projectRoot,stdio:"inherit"})}catch(e){throw new Error(`Failed to install humanbehavior-js: ${e}`)}}async generateModifications(){const e=[];switch(this.framework?.type){case"react":e.push(...await this.generateReactModifications());break;case"nextjs":e.push(...await this.generateNextJSModifications());break;case"nuxt":e.push(...await this.generateNuxtModifications());break;case"astro":e.push(...await this.generateAstroModifications());break;case"gatsby":e.push(...await this.generateGatsbyModifications());break;case"remix":e.push(...await this.generateRemixModifications());break;case"vue":e.push(...await this.generateVueModifications());break;case"angular":e.push(...await this.generateAngularModifications());break;case"svelte":e.push(...await this.generateSvelteModifications());break;default:e.push(...await this.generateVanillaModifications())}return e}async generateReactModifications(){const e=[],t=this.findReactAppFile();if(t){const n=o.readFileSync(t,"utf8"),i=this.injectReactProvider(n,t);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorProvider to React app"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateNextJSModifications(){const e=[],t=s.join(this.projectRoot,"src","app","layout.tsx"),n=s.join(this.projectRoot,"app","layout.tsx"),i=s.join(this.projectRoot,"src","pages","_app.tsx"),r=s.join(this.projectRoot,"pages","_app.tsx");let a=null,c=null;if(o.existsSync(t)?(a=t,c=s.join(this.projectRoot,"src","app","providers.tsx")):o.existsSync(n)&&(a=n,c=s.join(this.projectRoot,"app","providers.tsx")),a){e.push({filePath:c,action:"create",content:"'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nexport function Providers({ children }: { children: React.ReactNode }) {\n return (\n <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>\n {children}\n </HumanBehaviorProvider>\n );\n}",description:"Created providers.tsx file for Next.js App Router"});const t=o.readFileSync(a,"utf8"),n=this.injectNextJSAppRouter(t);e.push({filePath:a,action:"modify",content:n,description:"Added Providers wrapper to Next.js App Router layout"})}else if(o.existsSync(i)||o.existsSync(r)){const t=o.existsSync(i)?i:r,n=o.existsSync(i)?s.join(this.projectRoot,"src","components","providers.tsx"):s.join(this.projectRoot,"components","providers.tsx"),a=o.existsSync(i)?"../components/providers":"./components/providers";e.push({filePath:n,action:"create",content:"'use client';\n\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nexport function Providers({ children }: { children: React.ReactNode }) {\n return (\n <HumanBehaviorProvider apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}>\n {children}\n </HumanBehaviorProvider>\n );\n}",description:"Created providers.tsx file for Pages Router"});const c=o.readFileSync(t,"utf8"),u=this.injectNextJSPagesRouter(c,a);e.push({filePath:t,action:"modify",content:u,description:"Added Providers wrapper to Next.js Pages Router"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateAstroModifications(){const e=[],t=s.join(this.projectRoot,"src","components","HumanBehavior.astro");e.push({filePath:t,action:"create",content:"---\n// This component will only run on the client side\n---\n\n<script>\n import { HumanBehaviorTracker } from 'humanbehavior-js';\n const apiKey = import.meta.env.PUBLIC_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n<\/script>",description:"Created Astro component for HumanBehavior SDK"});const n=[s.join(this.projectRoot,"src","layouts","Layout.astro"),s.join(this.projectRoot,"src","layouts","layout.astro"),s.join(this.projectRoot,"src","layouts","BaseLayout.astro")];let i=null;for(const e of n)if(o.existsSync(e)){i=e;break}if(i){const t=o.readFileSync(i,"utf8"),n=this.injectAstroLayout(t);e.push({filePath:i,action:"modify",content:n,description:"Added HumanBehavior component to Astro layout"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateNuxtModifications(){const e=[],t=s.join(this.projectRoot,"app","plugins","humanbehavior.client.ts");e.push({filePath:t,action:"create",content:"import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport default defineNuxtPlugin(() => {\n const config = useRuntimeConfig();\n if (typeof window !== 'undefined') {\n const apiKey = config.public.humanBehaviorApiKey;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n }\n});",description:"Created Nuxt plugin for HumanBehavior SDK in app directory"});const n=s.join(this.projectRoot,"nuxt.config.ts");{const t=this.applyOrNotify(n,e=>this.injectNuxtConfig(e),"Added HumanBehavior runtime config to Nuxt config","Nuxt: Add inside defineNuxtConfig({ ⦠}):\nruntimeConfig: { public: { humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY } },");t&&e.push(t)}return e.push(this.createEnvironmentModification(this.framework)),e}async generateRemixModifications(){const e=[],t=s.join(this.projectRoot,"app","root.tsx");if(o.existsSync(t)){const n=o.readFileSync(t,"utf8"),i=this.injectRemixProvider(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorProvider to Remix root component"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateVueModifications(){const e=[],t=this.findVueMainFile(),n=s.join(this.projectRoot,"src","composables"),i=s.join(n,"useHumanBehavior.ts");try{o.existsSync(n)||o.mkdirSync(n,{recursive:!0}),o.existsSync(i)||e.push({filePath:i,action:"create",content:"import { HumanBehaviorTracker } from 'humanbehavior-js'\n\nexport function useHumanBehavior() {\n const apiKey = import.meta.env.VITE_HUMANBEHAVIOR_API_KEY\n \n if (apiKey) {\n const tracker = HumanBehaviorTracker.init(apiKey);\n \n return { tracker }\n }\n \n return { tracker: null }\n}\n",description:"Created Vue composable useHumanBehavior"})}catch{}if(t){const n=o.readFileSync(t,"utf8"),i=this.injectVuePlugin(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehaviorPlugin to Vue app"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateAngularModifications(){const e=[],t=s.join(this.projectRoot,"src","app","services"),n=s.join(t,"hb.service.ts");o.existsSync(t)||o.mkdirSync(t,{recursive:!0}),o.existsSync(n)||e.push({filePath:n,action:"create",content:"import { Injectable, NgZone, Inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\nimport { environment } from '../../environments/environment';\n\n@Injectable({ providedIn: 'root' })\nexport class HumanBehavior {\n private tracker: ReturnType<typeof HumanBehaviorTracker.init> | null = null;\n\n constructor(private ngZone: NgZone, @Inject(PLATFORM_ID) private platformId: Object) {\n if (isPlatformBrowser(this.platformId)) {\n this.ngZone.runOutsideAngular(() => {\n this.tracker = HumanBehaviorTracker.init(environment.humanBehaviorApiKey);\n });\n }\n }\n\n capture(event: string, props?: Record<string, any>) {\n this.tracker?.customEvent(event, props);\n }\n\n identify(user: Record<string, any>) {\n this.tracker?.identifyUser({ userProperties: user });\n }\n\n trackPageView(path?: string) {\n this.tracker?.trackPageView(path);\n }\n}\n",description:"Created Angular HumanBehavior service (singleton)"});const i=s.join(this.projectRoot,"src","environments","environment.ts"),r=s.join(this.projectRoot,"src","environments","environment.prod.ts"),a=s.dirname(i);if(o.existsSync(a)||o.mkdirSync(a,{recursive:!0}),o.existsSync(i)){const t=o.readFileSync(i,"utf8");if(!t.includes("humanBehaviorApiKey")){const n=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);e.push({filePath:i,action:"modify",content:n,description:"Added API key to Angular development environment"})}}else e.push({filePath:i,action:"create",content:`export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular development environment file"});if(o.existsSync(r)){const t=o.readFileSync(r,"utf8");if(!t.includes("humanBehaviorApiKey")){const n=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);e.push({filePath:r,action:"modify",content:n,description:"Added API key to Angular production environment"})}}else e.push({filePath:r,action:"create",content:`export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular production environment file"});const c=s.join(this.projectRoot,"src","app","app.ts");if(o.existsSync(c)){const t=o.readFileSync(c,"utf8");if(!t.includes("HumanBehavior")){let n=t.replace(/import { Component } from '@angular\/core';/,"import { Component } from '@angular/core';\nimport { HumanBehavior } from './services/hb.service';").replace(/export class App {/,"export class App {\n constructor(private readonly humanBehavior: HumanBehavior) {}");e.push({action:"modify",filePath:c,content:n,description:"Injected HumanBehavior service into Angular app component"})}}return e}async generateSvelteModifications(){const e=[],t=s.join(this.projectRoot,"svelte.config.js");if(o.existsSync(t)){const t=s.join(this.projectRoot,"src","routes","+layout.svelte");if(o.existsSync(t)){const n=o.readFileSync(t,"utf8"),i=this.injectSvelteKitLayout(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior tracker init to SvelteKit layout"})}}else{const t=this.findSvelteMainFile();if(t){const n=o.readFileSync(t,"utf8"),i=this.injectSvelteStore(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior tracker init to Svelte app"})}}return e.push(this.createEnvironmentModification(this.framework)),e}async generateVanillaModifications(){const e=[],t=this.findHTMLFile();if(t){const n=o.readFileSync(t,"utf8"),i=this.injectVanillaScript(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior CDN script to HTML file"})}return e.push(this.createEnvironmentModification(this.framework)),e}async generateGatsbyModifications(){const e=[],t=s.join(this.projectRoot,"gatsby-browser.js");if(o.existsSync(t)){const n=o.readFileSync(t,"utf8"),i=this.injectGatsbyBrowser(n);e.push({filePath:t,action:"modify",content:i,description:"Added HumanBehavior initialization to Gatsby browser"})}else e.push({filePath:t,action:"create",content:"import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport const onClientEntry = () => {\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n};",description:"Created gatsby-browser.js with HumanBehavior initialization"});return e.push(this.createEnvironmentModification(this.framework)),e}async applyModifications(e){for(const t of e)try{const e=s.dirname(t.filePath);switch(o.existsSync(e)||o.mkdirSync(e,{recursive:!0}),t.action){case"create":case"modify":o.writeFileSync(t.filePath,t.content);break;case"append":o.appendFileSync(t.filePath,"\n"+t.content)}}catch(e){throw new Error(`Failed to apply modification to ${t.filePath}: ${e}`)}}generateNextSteps(){const e=["ā
SDK installed and configured automatically!","š Your app is now tracking user behavior","š View sessions in your HumanBehavior dashboard","š§ Customize tracking in your code as needed"];return"react"!==this.framework?.type&&"nextjs"!==this.framework?.type||e.push("š” Use the useHumanBehavior() hook to track custom events"),this.manualNotes.length&&e.push(...this.manualNotes.map(e=>`ā ļø ${e}`)),e}applyOrNotify(e,t,n,i){if(!o.existsSync(e))return this.manualNotes.push(`${i} (file missing: ${s.relative(this.projectRoot,e)})`),null;const r=o.readFileSync(e,"utf8"),a=t(r);return a!==r?{filePath:e,action:"modify",content:a,description:n}:(this.manualNotes.push(i),null)}findReactAppFile(){const e=["src/App.jsx","src/App.js","src/App.tsx","src/App.ts","src/index.js","src/index.tsx","src/main.js","src/main.tsx"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}findVueMainFile(){const e=["src/main.js","src/main.ts","src/main.jsx","src/main.tsx"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}findSvelteMainFile(){const e=["src/main.js","src/main.ts","src/main.svelte"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}findHTMLFile(){const e=["index.html","public/index.html","dist/index.html"];for(const t of e){const e=s.join(this.projectRoot,t);if(o.existsSync(e))return e}return null}injectReactProvider(e,t){if(t.endsWith(".tsx")||t.endsWith(".ts"),e.includes("HumanBehaviorProvider"))return e;const n="vite"===this.framework?.bundler?"import.meta.env.VITE_HUMANBEHAVIOR_API_KEY!":"process.env.REACT_APP_HUMANBEHAVIOR_API_KEY!",i="import { HumanBehaviorProvider } from 'humanbehavior-js/react';",r=this.framework?.features?.hasReact18;if(e.includes("function App()")||e.includes("const App =")){let t=e.replace(/(import.*?from.*?['"]react['"];?)/,`$1\n${i}`);return t.includes(i)||(t=`${i}\n\n${t}`),t=t.replace(/return\s*\(([\s\S]*?)\)\s*;/,`return (\n <HumanBehaviorProvider apiKey={${n}}>\n $1\n </HumanBehaviorProvider>\n );`),t}if(r&&e.includes("createRoot")){let t=e.replace(/(import.*?from.*?['"]react['"];?)/,`$1\n${i}`);return t.includes(i)||(t=`${i}\n\n${t}`),t=t.replace(/(root\.render\s*\([\s\S]*?\)\s*;)/,`root.render(\n <HumanBehaviorProvider apiKey={${n}}>\n $1\n </HumanBehaviorProvider>\n );`),t}return`${i}\n\n${e}`}injectNextJSAppRouter(e){if(e.includes("Providers"))return e;let t=e.replace(/export default function RootLayout/,"import { Providers } from './providers';\n\nexport default function RootLayout");return t=t.replace(/<body([^>]*)>([\s\S]*?)<\/body>/,(e,t,n)=>`<body${t}>\n <Providers>\n ${n.trim()}\n </Providers>\n </body>`),t}injectNextJSPagesRouter(e,t="../components/providers"){if(e.includes("Providers"))return e;const n=`import { Providers } from '${t}';`;return e.replace(/function MyApp/,`${n}\n\nfunction MyApp`).replace(/return \(([\s\S]*?)\);/,"return (\n <Providers>\n $1\n </Providers>\n );")}injectRemixProvider(e){if(e.includes("HumanBehaviorProvider"))return e;let t=e;return e.includes("useLoaderData")||(t=t.replace(/(} from ['"]@remix-run\/react['"];?\s*)/,"$1import { useLoaderData } from '@remix-run/react';\n")),e.includes("HumanBehaviorProvider")||(t=t.replace(/(} from ['"]@remix-run\/react['"];?\s*)/,"$1import { HumanBehaviorProvider } from 'humanbehavior-js/react';\n")),e.includes("LoaderFunctionArgs")||(t=t.replace(/(} from ['"]@remix-run\/node['"];?\s*)/,"$1import type { LoaderFunctionArgs } from '@remix-run/node';\n")),e.includes("export const loader")||(t=t.replace(/(export function Layout)/,"export const loader = async ({ request }: LoaderFunctionArgs) => {\n return {\n ENV: {\n HUMANBEHAVIOR_API_KEY: process.env.HUMANBEHAVIOR_API_KEY,\n },\n };\n};\n\n$1")),e.includes("const data = useLoaderData")||(t=t.replace(/(export default function App\(\) \{\s*)(return \(\s*<div[^>]*>[\s\S]*?<\/div>\s*\);\s*\})/,'$1const data = useLoaderData<typeof loader>();\n \n return (\n <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>\n <div className="min-h-screen bg-gray-50">\n <Navigation />\n <Outlet />\n </div>\n </HumanBehaviorProvider>\n );\n}')),t}injectVuePlugin(e){if(e.includes("useHumanBehavior"))return e;const t=this.framework?.features?.hasVue3,n=e.includes("createApp")||e.includes("import { createApp }");let i=e.replace(/import\s*\{\s*HumanBehaviorPlugin\s*\}\s*from\s*['\"]humanbehavior-js\/vue['\"];?/g,"").replace(/app\.use\(\s*HumanBehaviorPlugin[\s\S]*?\);?/g,"");if(t||n){const e="import { useHumanBehavior } from './composables/useHumanBehavior';";if(!i.includes(e)){const t=i.lastIndexOf("import");if(-1!==t){const n=i.indexOf("\n",t);i=-1!==n?i.slice(0,n+1)+e+"\n"+i.slice(n+1):i+"\n"+e}else i=e+"\n"+i}return i.includes("createApp")&&(i=i.replace(/(const\s+app\s*=\s*createApp\([^)]*\))/,"$1\nconst { tracker } = useHumanBehavior();")),i}{const e="import { HumanBehaviorTracker } from 'humanbehavior-js';";return i.includes(e)||(i=`${e}\n${i}`),i.includes("new Vue")&&(i=i.replace(/(new\s+Vue\s*\()/,"HumanBehaviorTracker.init(process.env.VUE_APP_HUMANBEHAVIOR_API_KEY || import.meta?.env?.VITE_HUMANBEHAVIOR_API_KEY);\n$1")),i}}injectAngularModule(e){if(e.includes("HumanBehaviorModule"))return e;let t=e;return e.includes("environment")||(t=e.replace(/import.*from.*['"]@angular/,"import { environment } from '../environments/environment';\n$&")),t.replace(/imports:\s*\[([\s\S]*?)\]/,"imports: [\n $1,\n HumanBehaviorModule.forRoot({\n apiKey: environment.humanBehaviorApiKey\n })\n ]").replace(/import.*from.*['"]@angular/,"$&\nimport { HumanBehaviorModule } from 'humanbehavior-js/angular';")}injectAngularStandaloneInit(e){if(e.includes("initializeHumanBehavior"))return e;let t=e.replace(/import.*from.*['"]@angular/,"import { initializeHumanBehavior } from 'humanbehavior-js/angular';\nimport { environment } from './environments/environment';\n$&");return t=t.replace(/(bootstrapApplication\([^}]+\}?\)(?:\s*\.catch[^;]+;)?)/,"$1\n\n// Initialize HumanBehavior SDK (client-side only)\nif (typeof window !== 'undefined') {\n const tracker = initializeHumanBehavior(environment.humanBehaviorApiKey);\n}"),t}injectSvelteStore(e){if(e.includes("HumanBehaviorTracker.init"))return e;return`import { HumanBehaviorTracker } from 'humanbehavior-js';\n// Initialize HumanBehavior SDK\nHumanBehaviorTracker.init(import.meta.env?.VITE_HUMANBEHAVIOR_API_KEY || process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');\n\n${e}`}injectSvelteKitLayout(e){if(e.includes("HumanBehaviorTracker.init"))return e;const t="import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';",n="import { HumanBehaviorTracker } from 'humanbehavior-js';",i="import { browser } from '$app/environment';",r="if (browser) {\n const apiKey = PUBLIC_HUMANBEHAVIOR_API_KEY || import.meta.env.VITE_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n}";return e.includes('<script lang="ts">')?e.replace(/<script lang="ts">/,`<script lang="ts">\n\t${i}\n\t${t}\n\t${n}\n\t${r}`):e.includes("<script>")?e.replace(/<script>/,`<script>\n\t${i}\n\t${t}\n\t${n}\n\t${r}`):`<script lang="ts">\n${i}\n${t}\n${n}\n${r}\n<\/script>\n\n${e}`}injectVanillaScript(e){if(e.includes("humanbehavior-js"))return e;const t=`<script>\n // Initialize HumanBehavior SDK\n // Note: For vanilla HTML, the API key must be hardcoded since env vars aren't available\n const tracker = HumanBehaviorTracker.init('${this.apiKey}');\n<\/script>`;return e.replace(/<\/head>/,` <script src="https://unpkg.com/humanbehavior-js@latest/dist/index.min.js"><\/script>\n ${t}\n</head>`)}injectAstroLayout(e){if(e.includes("HumanBehavior")||e.includes("humanbehavior-js"))return e;let t=e;if(!e.includes("import HumanBehavior")){const n="import HumanBehavior from '../components/HumanBehavior.astro';",i=e.indexOf("---",3);t=-1!==i?e.slice(0,i)+"\n"+n+"\n"+e.slice(i):"---\n"+n+"\n---\n\n"+e}const n=t.lastIndexOf("</body>");return-1===n?t+"\n\n<HumanBehavior />":t.slice(0,n)+" <HumanBehavior />\n"+t.slice(n)}injectNuxtConfig(e){if(e.includes("humanBehaviorApiKey"))return e;const t=this.framework?.features?.hasNuxt3;if(t){const t=/export\s+default\s+defineNuxtConfig\s*\(\s*\{/;if(t.test(e)){const n=e.replace(t,"export default defineNuxtConfig({\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },");if(n!==e)return n}const n=e.indexOf("defineNuxtConfig(");if(-1!==n){const t=e.indexOf("{",n);if(-1!==t){const n="\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },";return`${e.slice(0,t+1)}${n}${e.slice(t+1)}`}}return e}return e.replace(/export default \{/,"export default {\n env: {\n humanBehaviorApiKey: process.env.HUMANBEHAVIOR_API_KEY\n },")}injectGatsbyLayout(e){if(e.includes("HumanBehavior"))return e;let t=e.replace(/import.*from.*['"]\./,"import HumanBehavior from './HumanBehavior';\n$&");return t=t.replace(/(\s*<\/body>)/,"\n <HumanBehavior apiKey={process.env.GATSBY_HUMANBEHAVIOR_API_KEY || ''} />\n$1"),t}injectGatsbyBrowser(e){const t="import { HumanBehaviorTracker } from 'humanbehavior-js';";if(/export\s+const\s+onClientEntry\s*=\s*\(/.test(e)){let n=e;return n.includes("from 'humanbehavior-js'")||(n=`${t}\n${n}`),n.includes("HumanBehaviorTracker.init(")?n:(n=n.replace(/(export\s+const\s+onClientEntry\s*=\s*\([^)]*\)\s*=>\s*\{)/,"$1\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n"),n)}return`${e.trim(),`${t}\n`}export const onClientEntry = () => {\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n if (apiKey) {\n HumanBehaviorTracker.init(apiKey);\n }\n};${e.trim()?`\n\n${e}`:""}`}findBestEnvFile(e){const t=[".env.local",".env.development.local",".env.development",".env.local.development",".env",".env.production",".env.staging"],n=(e=>{if("react"===e.type&&"vite"===e.bundler)return"VITE_HUMANBEHAVIOR_API_KEY";return{react:"REACT_APP_HUMANBEHAVIOR_API_KEY",nextjs:"NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY",vue:"VITE_HUMANBEHAVIOR_API_KEY",svelte:"PUBLIC_HUMANBEHAVIOR_API_KEY",angular:"HUMANBEHAVIOR_API_KEY",nuxt:"NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY",remix:"HUMANBEHAVIOR_API_KEY",vanilla:"HUMANBEHAVIOR_API_KEY",astro:"PUBLIC_HUMANBEHAVIOR_API_KEY",gatsby:"GATSBY_HUMANBEHAVIOR_API_KEY",node:"HUMANBEHAVIOR_API_KEY",auto:"HUMANBEHAVIOR_API_KEY"}[e.type]||"HUMANBEHAVIOR_API_KEY"})(e);for(const e of t){const t=s.join(this.projectRoot,e);if(o.existsSync(t))return{filePath:t,envVarName:n}}const i={react:".env.local",nextjs:".env.local",vue:".env.local",svelte:".env",angular:".env",nuxt:".env",remix:".env.local",vanilla:".env",astro:".env",gatsby:".env.development",node:".env",auto:".env"}[e.type]||".env";return{filePath:s.join(this.projectRoot,i),envVarName:n}}createEnvironmentModification(e){const{filePath:t,envVarName:n}=this.findBestEnvFile(e),i=this.apiKey.trim();if(o.existsSync(t)){const e=o.readFileSync(t,"utf8");return e.includes(n)?{filePath:t,action:"modify",content:e,description:`API key already exists in ${s.basename(t)}`}:{filePath:t,action:"append",content:`\n${n}=${i}`,description:`Added API key to existing ${s.basename(t)}`}}return{filePath:t,action:"create",content:`${n}=${i}`,description:`Created ${s.basename(t)} with API key`}}}class p{async analyzeCodePatterns(e){return this.analyzeWithHeuristics(e)}async resolveConflicts(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}async generateOptimizations(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}analyzeWithHeuristics(e){const t=e.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("nuxt")||t.includes("nuxtjs")||t.includes("defineNuxtConfig")||t.includes("nuxt.config")||t.includes("@nuxt/")||t.includes("useNuxtApp")||t.includes("useRuntimeConfig")||t.includes("useSeoMeta")||t.includes("useHead")||t.includes("useLazyFetch")||t.includes("useFetch")||t.includes("useAsyncData")||t.includes("#app")?(n={name:"nuxt",type:"nuxt"},i=.95):t.includes("next")||t.includes("nextjs")||t.includes("next/link")||t.includes("next/image")||t.includes("next/navigation")||t.includes("next/router")||t.includes("getserverSideProps")||t.includes("getstaticProps")||t.includes("getstaticPaths")||t.includes("app/layout")||t.includes("app/page")||t.includes("pages/")?(n={name:"nextjs",type:"nextjs"},i=.95):t.includes("gatsby")||t.includes("gatsby-browser")||t.includes("gatsby-ssr")||t.includes("gatsby-node")||t.includes("gatsby-config")||t.includes("useStaticQuery")||t.includes("graphql")?(n={name:"gatsby",type:"gatsby"},i=.95):t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")&&(n={name:"svelte",type:"svelte"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type||"gatsby"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}}class l{constructor(e){this.config={timeout:1e4,...e}}async analyzeCodePatterns(e){try{const t=await fetch(`${this.config.apiEndpoint}/analyze`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({codeSamples:e}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!t.ok)throw new Error(`AI service returned ${t.status}: ${t.statusText}`);return(await t.json()).analysis}catch(t){return console.warn("Remote AI service failed, falling back to heuristic analysis:",t),this.performHeuristicAnalysis(e)}}async resolveConflicts(e,t){try{const n=await fetch(`${this.config.apiEndpoint}/resolve-conflicts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conflicts:e,framework:t}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!n.ok)throw new Error(`AI service returned ${n.status}: ${n.statusText}`);return(await n.json()).resolutions||[]}catch(n){return console.warn("Remote AI conflict resolution failed, using heuristic approach:",n),this.resolveConflictsHeuristic(e,t)}}async generateOptimizations(e,t){try{const n=await fetch(`${this.config.apiEndpoint}/optimize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({framework:e,patterns:t}),signal:AbortSignal.timeout(this.config.timeout||1e4)});if(!n.ok)throw new Error(`AI service returned ${n.status}: ${n.statusText}`);return(await n.json()).optimizations||[]}catch(n){return console.warn("Remote AI optimization generation failed, using heuristic approach:",n),this.generateOptimizationsHeuristic(e,t)}}performHeuristicAnalysis(e){const t=e.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;t.includes("nuxt")||t.includes("nuxtjs")||t.includes("defineNuxtConfig")||t.includes("nuxt.config")||t.includes("@nuxt/")||t.includes("useNuxtApp")||t.includes("useRuntimeConfig")||t.includes("useSeoMeta")||t.includes("useHead")||t.includes("useLazyFetch")||t.includes("useFetch")||t.includes("useAsyncData")||t.includes("#app")?(n={name:"nuxt",type:"nuxt"},i=.95):t.includes("next")||t.includes("nextjs")||t.includes("next/link")||t.includes("next/image")||t.includes("next/navigation")||t.includes("next/router")||t.includes("getserverSideProps")||t.includes("getstaticProps")||t.includes("getstaticPaths")||t.includes("app/layout")||t.includes("app/page")||t.includes("pages/")?(n={name:"nextjs",type:"nextjs"},i=.95):t.includes("gatsby")||t.includes("gatsby-browser")||t.includes("gatsby-ssr")||t.includes("gatsby-node")||t.includes("gatsby-config")||t.includes("useStaticQuery")||t.includes("graphql")?(n={name:"gatsby",type:"gatsby"},i=.95):t.includes("react")?(n={name:"react",type:"react"},i=.9):t.includes("vue")?(n={name:"vue",type:"vue"},i=.9):t.includes("angular")?(n={name:"angular",type:"angular"},i=.9):t.includes("svelte")?(n={name:"svelte",type:"svelte"},i=.9):t.includes("astro")&&(n={name:"astro",type:"astro"},i=.9);let r="script";"react"===n.type||"nextjs"===n.type||"gatsby"===n.type?r="provider":"vue"===n.type?r="plugin":"angular"===n.type&&(r="module");let a="modern";return(t.includes("require(")||t.includes("var "))&&(a="legacy"),{framework:n,confidence:i,patterns:e,conflicts:[],recommendations:[],integrationStrategy:r,compatibilityMode:a}}resolveConflictsHeuristic(e,t){const n=[];for(const t of e)switch(t){case"existing_humanbehavior_code":n.push("update_existing_integration");break;case"existing_provider":n.push("merge_providers");break;case"module_system_conflict":n.push("hybrid_module_support");break;default:n.push("skip_conflict")}return n}generateOptimizationsHeuristic(e,t){const n=[];switch(e.type){case"react":n.push("Use React.memo for performance optimization"),n.push("Implement error boundaries for better error tracking"),n.push("Consider using React.lazy for code splitting");break;case"vue":n.push("Use Vue 3 Composition API for better performance"),n.push("Implement proper error handling in components"),n.push("Consider using Vue Router for navigation tracking");break;case"angular":n.push("Use Angular standalone components for better tree-shaking"),n.push("Implement proper error handling with ErrorHandler"),n.push("Consider using Angular signals for state management");break;default:n.push("Enable performance tracking"),n.push("Implement error tracking"),n.push("Consider progressive enhancement")}return n}}class m extends u{constructor(e,t=process.cwd(),n){super(e,t),this.selectedFramework=n.toLowerCase(),this.framework=this.createFrameworkInfo(this.selectedFramework)}async install(){try{if("auto"===this.selectedFramework)this.framework=await this.runFullDetection();else{this.framework=this.createFrameworkInfo(this.selectedFramework),this.framework||(this.framework={name:"unknown",type:"vanilla"});const e=await this.runFullDetection();this.framework={...e,name:this.framework.name,type:this.framework.type}}await this.installPackage();const e=await this.generateModifications();await this.applyModifications(e);const t=this.generateManualNextSteps();return{success:!0,framework:this.framework,modifications:e,errors:[],nextSteps:t,selectedFramework:this.selectedFramework,manualMode:!0}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],selectedFramework:this.selectedFramework,manualMode:!0}}}async runFullDetection(){if("auto"===this.selectedFramework){const e=new l({apiEndpoint:"https://ik3zxh4790.execute-api.us-east-1.amazonaws.com/prod"}),t=await this.scanProjectFiles(),n=await this.extractCodeSamples(t);return(await e.analyzeCodePatterns(n)).framework}{const e=new u(this.apiKey,this.projectRoot);return await e.detectFramework()}}async scanProjectFiles(){const e=[],t=(n,i=0)=>{if(!(i>3))try{const r=o.readdirSync(n);for(const a of r){const r=s.join(n,a),c=o.statSync(r);c.isDirectory()&&!a.startsWith(".")&&"node_modules"!==a?t(r,i+1):c.isFile()&&this.isRelevantFile(a)&&e.push(r)}}catch(e){}};return t(this.projectRoot),e}isRelevantFile(e){return[".js",".jsx",".ts",".tsx",".vue",".svelte",".html",".json",".config.js",".config.ts",".babelrc",".eslintrc"].some(t=>e.endsWith(t))||["package.json","tsconfig.json","vite.config","webpack.config","next.config","nuxt.config","angular.json","svelte.config"].some(t=>e.includes(t))}async extractCodeSamples(e){const t=[];for(const n of e.slice(0,20))try{const e=o.readFileSync(n,"utf8"),i=s.relative(this.projectRoot,n);t.push(`File: ${i}\n${e.substring(0,1e3)}`)}catch(e){}return t}createFrameworkInfo(e){return{react:{name:"react",type:"react"},nextjs:{name:"nextjs",type:"nextjs"},next:{name:"nextjs",type:"nextjs"},vue:{name:"vue",type:"vue"},nuxt:{name:"nuxt",type:"nuxt"},nuxtjs:{name:"nuxt",type:"nuxt"},angular:{name:"angular",type:"angular"},svelte:{name:"svelte",type:"svelte"},sveltekit:{name:"svelte",type:"svelte"},remix:{name:"remix",type:"remix"},astro:{name:"astro",type:"astro"},gatsby:{name:"gatsby",type:"gatsby"},vanilla:{name:"vanilla",type:"vanilla"},node:{name:"node",type:"node"},auto:{name:"auto-detected",type:"auto"}}[e]||{name:e,type:"vanilla"}}async detectFramework(){return this.framework||{name:"unknown",type:"vanilla"}}generateManualNextSteps(){return["ā
Manual framework installation completed!",`šÆ Selected framework: ${this.framework?.name||"unknown"}`,`š§ Integration strategy: ${this.getIntegrationStrategy()}`,"š Your app is now ready to track user behavior","š View sessions in your HumanBehavior dashboard"]}getIntegrationStrategy(){if(!this.framework?.type)return"script";switch(this.framework.type){case"react":case"nextjs":return"provider";case"vue":return"plugin";case"angular":return"module";default:return"script"}}}class h{constructor(e){this.options=e}async run(){c.intro("š¤ AI-Enhanced HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(c.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd(),n=await this.chooseFramework();if(n||(c.cancel("Installation cancelled."),process.exit(0)),!this.options.yes){await this.confirmInstallation(t,n)||(c.cancel("Installation cancelled."),process.exit(0))}const i=c.spinner();i.start("š Analyzing your project with AI...");const r=new m(e,t,n),a=await r.install();i.stop("Analysis complete!"),this.displayResults(a,n)}catch(e){c.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await c.text({message:"Enter your HumanBehavior API key:",placeholder:"hb_...",validate:e=>e?e.startsWith("hb_")?void 0:'API key should start with "hb_"':"API key is required"})}async confirmInstallation(e,t){return await c.confirm({message:`Ready to install HumanBehavior SDK in ${e} for ${t}?`})}async chooseFramework(){return await c.select({message:"Select your framework:",options:[{label:"React",value:"react"},{label:"Next.js",value:"nextjs"},{label:"Vue",value:"vue"},{label:"Angular",value:"angular"},{label:"Svelte",value:"svelte"},{label:"Nuxt.js",value:"nuxt"},{label:"Remix",value:"remix"},{label:"Astro",value:"astro"},{label:"Gatsby",value:"gatsby"},{label:"Vanilla JS/TS",value:"vanilla"}]})}displayResults(e,t){if(e.success){if(c.outro("š Installation completed successfully!"),c.note(`Framework detected: ${e.framework.name} (${e.framework.type})`,"Framework Info"),e.modifications&&e.modifications.length>0){const t=e.modifications.map(e=>`${e.action}: ${e.filePath} - ${e.description}`);c.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&c.note(e.nextSteps.join("\n"),"Next Steps"),e.aiAnalysis&&(c.note(`Confidence: ${Math.round(100*e.aiAnalysis.confidence)}%`,"AI Analysis"),e.aiAnalysis.recommendations&&e.aiAnalysis.recommendations.length>0&&c.note(e.aiAnalysis.recommendations.join("\n"),"AI Recommendations"))}else c.cancel("Installation failed"),e.errors&&e.errors.length>0&&c.note(e.errors.join("\n"),"Errors")}}function d(){console.log("\nš¤ HumanBehavior SDK AI Auto-Installation\n\nUsage: npx humanbehavior-js ai-auto-install [api-key] [options]\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip all prompts and use defaults\n --dry-run Show what would be changed without making changes\n\n -p, --project <path> Specify project directory\n -f, --framework <name> Specify framework manually\n\nExamples:\n npx humanbehavior-js ai-auto-install\n npx humanbehavior-js ai-auto-install hb_your_api_key_here\n npx humanbehavior-js ai-auto-install --project ./my-app --ai\n npx humanbehavior-js ai-auto-install --framework react --yes\n")}new h(function(){const e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++){const i=e[n];switch(i){case"--help":case"-h":d(),process.exit(0);break;case"--yes":case"-y":t.yes=!0;break;case"--dry-run":t.dryRun=!0;break;case"--project":case"-p":t.projectPath=e[++n];break;case"--framework":case"-f":t.framework=e[++n];break;default:t.apiKey||i.startsWith("-")||(t.apiKey=i)}}return t}()).run().catch(e=>{c.cancel(`Unexpected error: ${e.message}`),process.exit(1)});class f{constructor(e){this.options=e}async run(){c.intro("š HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(c.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd();if(!this.options.yes){await this.confirmInstallation(t)||(c.cancel("Installation cancelled."),process.exit(0))}const n=c.spinner();n.start("š Detecting framework and applying integration...");const i=new u(e,t),r=await i.install();n.stop("Installation complete!"),this.displayResults(r)}catch(e){c.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await c.text({message:"Enter your HumanBehavior API key:",placeholder:"hb_...",validate:e=>e?e.startsWith("hb_")?void 0:'API key should start with "hb_"':"API key is required"})}async confirmInstallation(e){return await c.confirm({message:`Ready to install HumanBehavior SDK in ${e}?`})}displayResults(e){if(e.success){if(c.outro("š Installation completed successfully!"),c.note(`Framework detected: ${e.framework.name} (${e.framework.type})`,"Framework Info"),e.modifications&&e.modifications.length>0){const t=e.modifications.map(e=>`${e.action}: ${e.filePath} - ${e.description}`);c.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&c.note(e.nextSteps.join("\n"),"Next Steps")}else c.cancel("Installation failed"),e.errors&&e.errors.length>0&&c.note(e.errors.join("\n"),"Errors")}}function y(){console.log("\nš HumanBehavior SDK Auto-Installation\n\nUsage: npx humanbehavior-js auto-install [api-key] [options]\n\nThis tool automatically detects your framework and integrates the HumanBehavior SDK.\n\nOptions:\n -h, --help Show this help message\n -y, --yes Skip all prompts and use defaults\n --dry-run Show what would be changed without making changes\n -p, --project <path> Specify project directory\n\nExamples:\n npx humanbehavior-js auto-install\n npx humanbehavior-js auto-install hb_your_api_key_here\n npx humanbehavior-js auto-install --project ./my-app --yes\n")}if(("undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index.js",document.baseURI).href)===`file://${process.argv[1]}`){new f(function(){const e=process.argv.slice(2),t={};for(let n=0;n<e.length;n++){const i=e[n];switch(i){case"--help":case"-h":y(),process.exit(0);break;case"--yes":case"-y":t.yes=!0;break;case"--dry-run":t.dryRun=!0;break;case"--project":case"-p":t.projectPath=e[++n];break;default:t.apiKey||i.startsWith("-")||(t.apiKey=i)}}return t}()).run().catch(e=>{c.cancel(`Unexpected error: ${e.message}`),process.exit(1)})}exports.AIAutoInstallCLI=h,exports.AIBrowserInstallationWizard=class{constructor(e,t){this.apiKey=e,this.aiService=t||new p}async install(){try{const e=await this.performBrowserAIAnalysis(),t=this.generateAIBrowserModifications(e);return{success:!0,framework:e.framework,modifications:t,errors:[],nextSteps:["ā
AI-optimized browser integration ready!",`šÆ Framework detected: ${e.framework.name}`,`š§ Integration strategy: ${e.integrationStrategy}`,"š Copy the generated code to your project","š Your app will be ready to track user behavior"],aiAnalysis:e,learningData:{patterns:e.patterns,framework:e.framework.name,success:!0}}}catch(e){return{success:!1,framework:{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],aiAnalysis:{framework:{name:"unknown",type:"vanilla"},confidence:0,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"legacy"},learningData:{patterns:[],framework:"unknown",success:!1}}}}async performBrowserAIAnalysis(){this.detectBrowserFramework();const e=[`Browser Environment: ${this.analyzeBrowserPatterns().join(", ")}`];return await this.aiService.analyzeCodePatterns(e)}detectBrowserFramework(){if("undefined"!=typeof window){if(window.React)return{name:"react",type:"react"};if(window.Vue)return{name:"vue",type:"vue"};if(window.angular)return{name:"angular",type:"angular"}}return{name:"vanilla",type:"vanilla"}}analyzeBrowserPatterns(){const e=[];if("undefined"!=typeof window){window.React&&e.push("React global detected"),window.Vue&&e.push("Vue global detected"),window.angular&&e.push("Angular global detected"),document.querySelector("[data-reactroot]")&&e.push("React DOM detected"),document.querySelector("[data-vue]")&&e.push("Vue DOM detected");document.querySelectorAll("script").forEach(t=>{t.src.includes("react")&&e.push("React script detected"),t.src.includes("vue")&&e.push("Vue script detected")})}return e}generateAIBrowserModifications(e){const t=[];if("react"===e.framework.type)t.push({filePath:"App.jsx",action:"create",content:`// AI-Optimized React Integration\nimport { HumanBehaviorProvider } from 'humanbehavior-js/react';\n\nfunction App() {\n return (\n <HumanBehaviorProvider \n apiKey="${this.apiKey}"\n config={{\n // AI-generated optimizations\n enablePerformanceTracking: true,\n enableErrorTracking: true,\n framework: '${e.framework.name}',\n integrationStrategy: '${e.integrationStrategy}'\n }}\n >\n {/* Your app components */}\n </HumanBehaviorProvider>\n );\n}\n\nexport default App;`,description:"AI-optimized React component with HumanBehaviorProvider"});else t.push({filePath:"humanbehavior-init.js",action:"create",content:`// AI-Optimized Vanilla JS Integration\nimport { HumanBehaviorTracker } from 'humanbehavior-js';\n\nconst tracker = HumanBehaviorTracker.init('${this.apiKey}', {\n // AI-generated configuration\n framework: '${e.framework.name}',\n integrationStrategy: '${e.integrationStrategy}',\n compatibilityMode: '${e.compatibilityMode}',\n enablePerformanceTracking: true,\n enableErrorTracking: true\n});`,description:"AI-optimized vanilla JS initialization"});return t}},exports.AIEnhancedInstallationWizard=class extends u{constructor(e,t=process.cwd(),n){super(e,t),this.learningCache=new Map,this.patternDatabase=new Map,this.aiService=n||new p,this.loadLearningData()}async install(){try{const e=await this.performAICodeAnalysis();this.framework=await this.detectFrameworkWithAI(e);const t=await this.generateAIOptimizedModifications(e);await this.applyModificationsWithAI(t,e);const n=this.generateAINextSteps(e);return await this.learnFromInstallation(e,t),{success:!0,framework:this.framework,modifications:t,errors:[],nextSteps:n,aiAnalysis:e,learningData:{patterns:e.patterns,framework:this.framework.name,success:!0}}}catch(e){return{success:!1,framework:this.framework||{name:"unknown",type:"vanilla"},modifications:[],errors:[e instanceof Error?e.message:"Unknown error"],nextSteps:[],aiAnalysis:{framework:{name:"unknown",type:"vanilla"},confidence:0,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"legacy"},learningData:{patterns:[],framework:"unknown",success:!1}}}}async performAICodeAnalysis(){const e=await this.scanProjectFiles(),t=await this.extractCodeSamples(e);return await this.aiService.analyzeCodePatterns(t)}async scanProjectFiles(){const e=[],t=(n,i=0)=>{if(!(i>3))try{const r=o.readdirSync(n);for(const a of r){const r=s.join(n,a),c=o.statSync(r);c.isDirectory()&&!a.startsWith(".")&&"node_modules"!==a?t(r,i+1):c.isFile()&&this.isRelevantFile(a)&&e.push(r)}}catch(e){}};return t(this.projectRoot),e}isRelevantFile(e){return[".js",".jsx",".ts",".tsx",".vue",".svelte",".html",".json",".config.js",".config.ts",".babelrc",".eslintrc"].some(t=>e.endsWith(t))||["package.json","tsconfig.json","vite.config","webpack.config","next.config","nuxt.config","angular.json","svelte.config","app/layout","app/page","pages/index","pages/_app","pages/_document"].some(t=>e.includes(t))}async extractCodeSamples(e){const t=[];for(const n of e.slice(0,20))try{const e=o.readFileSync(n,"utf8"),i=s.relative(this.projectRoot,n),r=this.extractCodePatterns(e);r.length>0&&t.push(`File: ${i}\n${r.join("\n")}`)}catch(e){}return t}extractCodePatterns(e){const t=[],n={react:[/import\s+React\s+from\s+['"]react['"]/gi,/from\s+['"]react['"]/gi,/function\s+\w+\s*\(\s*\)\s*{/gi,/const\s+\w+\s*=\s*\(\s*\)\s*=>\s*{/gi],vue:[/import\s+{\s*createApp\s*}\s+from\s+['"]vue['"]/gi,/from\s+['"]vue['"]/gi,/<template>/gi,/<script\s+setup>/gi],angular:[/import\s+{\s*Component\s*}\s+from\s+['"]@angular\/core['"]/gi,/@Component\s*\(\s*{/gi,/from\s+['"]@angular/gi],svelte:[/<script>/gi,/import\s+.*