UNPKG

humanbehavior-js

Version:

SDK for HumanBehavior session and event recording

1 lines 63.1 kB
import*as e from"fs";import*as t from"path";import{execSync as n}from"child_process";import*as i from"@clack/prompts";class r{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 n=t.join(this.projectRoot,"package.json");if(!e.existsSync(n))return{name:"vanilla",type:"vanilla",projectRoot:this.projectRoot};const i=JSON.parse(e.readFileSync(n,"utf8")),r={...i.dependencies,...i.devDependencies};let a={name:"vanilla",type:"vanilla",projectRoot:this.projectRoot,features:{}};if(r.nuxt){const e=r.nuxt,t=this.isVersionGte(e,"3.0.0");a={name:"nuxt",type:"nuxt",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript,hasRouter:!0,projectRoot:this.projectRoot,features:{hasNuxt3:t}}}else if(r.next){const e=r.next,t=this.isVersionGte(e,"13.0.0");a={name:"nextjs",type:"nextjs",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["@types/node"],hasRouter:!0,projectRoot:this.projectRoot,features:{hasNextAppRouter:t}}}else if(r["@remix-run/react"]||r["@remix-run/dev"]){const e=r["@remix-run/react"]||r["@remix-run/dev"];a={name:"remix",type:"remix",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(r.react){const e=r.react,t=this.isVersionGte(e,"18.0.0");a={name:"react",type:"react",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["@types/react"],hasRouter:!!r["react-router-dom"]||!!r["react-router"],projectRoot:this.projectRoot,features:{hasReact18:t}}}else if(r.vue){const e=r.vue,t=this.isVersionGte(e,"3.0.0");a={name:"vue",type:"vue",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["@vue/cli-service"],hasRouter:!!r["vue-router"],projectRoot:this.projectRoot,features:{hasVue3:t}}}else if(r["@angular/core"]){const e=r["@angular/core"],t=this.isVersionGte(e,"17.0.0");a={name:"angular",type:"angular",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!0,hasRouter:!0,projectRoot:this.projectRoot,features:{hasAngularStandalone:t}}}else if(r.svelte){const e=r.svelte,t=!!r["@sveltejs/kit"];a={name:"svelte",type:"svelte",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["svelte-check"],hasRouter:!!r["svelte-routing"]||!!r["@sveltejs/kit"],projectRoot:this.projectRoot,features:{hasSvelteKit:t}}}else if(r.astro){const e=r.astro;a={name:"astro",type:"astro",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["@astrojs/ts-plugin"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}else if(r.gatsby){const e=r.gatsby;a={name:"gatsby",type:"gatsby",version:e,majorVersion:this.getMajorVersion(e),hasTypeScript:!!r.typescript||!!r["@types/react"],hasRouter:!0,projectRoot:this.projectRoot,features:{}}}return r.vite?a.bundler="vite":r.webpack?a.bundler="webpack":r.esbuild?a.bundler="esbuild":r.rollup&&(a.bundler="rollup"),e.existsSync(t.join(this.projectRoot,"yarn.lock"))?a.packageManager="yarn":e.existsSync(t.join(this.projectRoot,"pnpm-lock.yaml"))?a.packageManager="pnpm":a.packageManager="npm",a}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(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 t=[],n=this.findReactAppFile();if(n){const i=e.readFileSync(n,"utf8"),r=this.injectReactProvider(i,n);t.push({filePath:n,action:"modify",content:r,description:"Added HumanBehaviorProvider to React app"})}return t.push(this.createEnvironmentModification(this.framework)),t}async generateNextJSModifications(){const n=[],i=t.join(this.projectRoot,"src","app","layout.tsx"),r=t.join(this.projectRoot,"app","layout.tsx"),a=t.join(this.projectRoot,"src","pages","_app.tsx"),o=t.join(this.projectRoot,"pages","_app.tsx");let s=null,c=null;if(e.existsSync(i)?(s=i,c=t.join(this.projectRoot,"src","app","providers.tsx")):e.existsSync(r)&&(s=r,c=t.join(this.projectRoot,"app","providers.tsx")),s){n.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=e.readFileSync(s,"utf8"),i=this.injectNextJSAppRouter(t);n.push({filePath:s,action:"modify",content:i,description:"Added Providers wrapper to Next.js App Router layout"})}else if(e.existsSync(a)||e.existsSync(o)){const i=e.existsSync(a)?a:o,r=e.existsSync(a)?t.join(this.projectRoot,"src","components","providers.tsx"):t.join(this.projectRoot,"components","providers.tsx"),s=e.existsSync(a)?"../components/providers":"./components/providers";n.push({filePath:r,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=e.readFileSync(i,"utf8"),p=this.injectNextJSPagesRouter(c,s);n.push({filePath:i,action:"modify",content:p,description:"Added Providers wrapper to Next.js Pages Router"})}return n.push(this.createEnvironmentModification(this.framework)),n}async generateAstroModifications(){const n=[],i=t.join(this.projectRoot,"src","components","HumanBehavior.astro");n.push({filePath:i,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 r=[t.join(this.projectRoot,"src","layouts","Layout.astro"),t.join(this.projectRoot,"src","layouts","layout.astro"),t.join(this.projectRoot,"src","layouts","BaseLayout.astro")];let a=null;for(const t of r)if(e.existsSync(t)){a=t;break}if(a){const t=e.readFileSync(a,"utf8"),i=this.injectAstroLayout(t);n.push({filePath:a,action:"modify",content:i,description:"Added HumanBehavior component to Astro layout"})}return n.push(this.createEnvironmentModification(this.framework)),n}async generateNuxtModifications(){const e=[],n=t.join(this.projectRoot,"app","plugins","humanbehavior.client.ts");e.push({filePath:n,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 i=t.join(this.projectRoot,"nuxt.config.ts");{const t=this.applyOrNotify(i,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 n=[],i=t.join(this.projectRoot,"app","root.tsx");if(e.existsSync(i)){const t=e.readFileSync(i,"utf8"),r=this.injectRemixProvider(t);n.push({filePath:i,action:"modify",content:r,description:"Added HumanBehaviorProvider to Remix root component"})}return n.push(this.createEnvironmentModification(this.framework)),n}async generateVueModifications(){const n=[],i=this.findVueMainFile(),r=t.join(this.projectRoot,"src","composables"),a=t.join(r,"useHumanBehavior.ts");try{e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(a)||n.push({filePath:a,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(i){const t=e.readFileSync(i,"utf8"),r=this.injectVuePlugin(t);n.push({filePath:i,action:"modify",content:r,description:"Added HumanBehaviorPlugin to Vue app"})}return n.push(this.createEnvironmentModification(this.framework)),n}async generateAngularModifications(){const n=[],i=t.join(this.projectRoot,"src","app","services"),r=t.join(i,"hb.service.ts");e.existsSync(i)||e.mkdirSync(i,{recursive:!0}),e.existsSync(r)||n.push({filePath:r,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 a=t.join(this.projectRoot,"src","environments","environment.ts"),o=t.join(this.projectRoot,"src","environments","environment.prod.ts"),s=t.dirname(a);if(e.existsSync(s)||e.mkdirSync(s,{recursive:!0}),e.existsSync(a)){const t=e.readFileSync(a,"utf8");if(!t.includes("humanBehaviorApiKey")){const e=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);n.push({filePath:a,action:"modify",content:e,description:"Added API key to Angular development environment"})}}else n.push({filePath:a,action:"create",content:`export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular development environment file"});if(e.existsSync(o)){const t=e.readFileSync(o,"utf8");if(!t.includes("humanBehaviorApiKey")){const e=t.replace(/export const environment = {([\s\S]*?)};/,`export const environment = {\n $1,\n humanBehaviorApiKey: '${this.apiKey}'\n};`);n.push({filePath:o,action:"modify",content:e,description:"Added API key to Angular production environment"})}}else n.push({filePath:o,action:"create",content:`export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular production environment file"});const c=t.join(this.projectRoot,"src","app","app.ts");if(e.existsSync(c)){const t=e.readFileSync(c,"utf8");if(!t.includes("HumanBehavior")){let e=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) {}");n.push({action:"modify",filePath:c,content:e,description:"Injected HumanBehavior service into Angular app component"})}}return n}async generateSvelteModifications(){const n=[],i=t.join(this.projectRoot,"svelte.config.js");if(e.existsSync(i)){const i=t.join(this.projectRoot,"src","routes","+layout.svelte");if(e.existsSync(i)){const t=e.readFileSync(i,"utf8"),r=this.injectSvelteKitLayout(t);n.push({filePath:i,action:"modify",content:r,description:"Added HumanBehavior tracker init to SvelteKit layout"})}}else{const t=this.findSvelteMainFile();if(t){const i=e.readFileSync(t,"utf8"),r=this.injectSvelteStore(i);n.push({filePath:t,action:"modify",content:r,description:"Added HumanBehavior tracker init to Svelte app"})}}return n.push(this.createEnvironmentModification(this.framework)),n}async generateVanillaModifications(){const t=[],n=this.findHTMLFile();if(n){const i=e.readFileSync(n,"utf8"),r=this.injectVanillaScript(i);t.push({filePath:n,action:"modify",content:r,description:"Added HumanBehavior CDN script to HTML file"})}return t.push(this.createEnvironmentModification(this.framework)),t}async generateGatsbyModifications(){const n=[],i=t.join(this.projectRoot,"gatsby-browser.js");if(e.existsSync(i)){const t=e.readFileSync(i,"utf8"),r=this.injectGatsbyBrowser(t);n.push({filePath:i,action:"modify",content:r,description:"Added HumanBehavior initialization to Gatsby browser"})}else n.push({filePath:i,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 n.push(this.createEnvironmentModification(this.framework)),n}async applyModifications(n){for(const i of n)try{const n=t.dirname(i.filePath);switch(e.existsSync(n)||e.mkdirSync(n,{recursive:!0}),i.action){case"create":case"modify":e.writeFileSync(i.filePath,i.content);break;case"append":e.appendFileSync(i.filePath,"\n"+i.content)}}catch(e){throw new Error(`Failed to apply modification to ${i.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(n,i,r,a){if(!e.existsSync(n))return this.manualNotes.push(`${a} (file missing: ${t.relative(this.projectRoot,n)})`),null;const o=e.readFileSync(n,"utf8"),s=i(o);return s!==o?{filePath:n,action:"modify",content:s,description:r}:(this.manualNotes.push(a),null)}findReactAppFile(){const n=["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 i of n){const n=t.join(this.projectRoot,i);if(e.existsSync(n))return n}return null}findVueMainFile(){const n=["src/main.js","src/main.ts","src/main.jsx","src/main.tsx"];for(const i of n){const n=t.join(this.projectRoot,i);if(e.existsSync(n))return n}return null}findSvelteMainFile(){const n=["src/main.js","src/main.ts","src/main.svelte"];for(const i of n){const n=t.join(this.projectRoot,i);if(e.existsSync(n))return n}return null}findHTMLFile(){const n=["index.html","public/index.html","dist/index.html"];for(const i of n){const n=t.join(this.projectRoot,i);if(e.existsSync(n))return n}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(n){const i=[".env.local",".env.development.local",".env.development",".env.local.development",".env",".env.production",".env.staging"],r=(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"})(n);for(const n of i){const i=t.join(this.projectRoot,n);if(e.existsSync(i))return{filePath:i,envVarName:r}}const a={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"}[n.type]||".env";return{filePath:t.join(this.projectRoot,a),envVarName:r}}createEnvironmentModification(n){const{filePath:i,envVarName:r}=this.findBestEnvFile(n),a=this.apiKey.trim();if(e.existsSync(i)){const n=e.readFileSync(i,"utf8");return n.includes(r)?{filePath:i,action:"modify",content:n,description:`API key already exists in ${t.basename(i)}`}:{filePath:i,action:"append",content:`\n${r}=${a}`,description:`Added API key to existing ${t.basename(i)}`}}return{filePath:i,action:"create",content:`${r}=${a}`,description:`Created ${t.basename(i)} with API key`}}}class a{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 o extends r{constructor(e,t=process.cwd(),n){super(e,t),this.learningCache=new Map,this.patternDatabase=new Map,this.aiService=n||new a,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 n=[],i=(r,a=0)=>{if(!(a>3))try{const o=e.readdirSync(r);for(const s of o){const o=t.join(r,s),c=e.statSync(o);c.isDirectory()&&!s.startsWith(".")&&"node_modules"!==s?i(o,a+1):c.isFile()&&this.isRelevantFile(s)&&n.push(o)}}catch(e){}};return i(this.projectRoot),n}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(n){const i=[];for(const r of n.slice(0,20))try{const n=e.readFileSync(r,"utf8"),a=t.relative(this.projectRoot,r),o=this.extractCodePatterns(n);o.length>0&&i.push(`File: ${a}\n${o.join("\n")}`)}catch(e){}return i}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+.*\s+from\s+['"]svelte/gi,/from\s+['"]svelte/gi],nextjs:[/import\s+.*\s+from\s+['"]next/gi,/from\s+['"]next/gi,/export\s+default\s+function\s+Page/gi,/export\s+default\s+function\s+Layout/gi,/export\s+default\s+function\s+Loading/gi,/export\s+default\s+function\s+Error/gi,/export\s+default\s+function\s+Not-found/gi,/useRouter\s+from\s+['"]next\/navigation['"]/gi,/useRouter\s+from\s+['"]next\/router['"]/gi,/Link\s+from\s+['"]next\/link['"]/gi,/Image\s+from\s+['"]next\/image['"]/gi,/getServerSideProps/gi,/getStaticProps/gi,/getStaticPaths/gi,/next\.config/gi,/app\/layout\.tsx/gi,/app\/page\.tsx/gi,/pages\/.*\.tsx/gi,/pages\/.*\.jsx/gi,/pages\/.*\.ts/gi,/pages\/.*\.js/gi],nuxt:[/import\s+.*\s+from\s+['"]nuxt/gi,/from\s+['"]nuxt/gi,/export\s+default\s+defineNuxtConfig/gi,/defineNuxtConfig/gi,/nuxt\.config\.ts/gi,/nuxt\.config\.js/gi,/@nuxt\//gi,/#app/gi,/useNuxtApp/gi,/useRuntimeConfig/gi,/useSeoMeta/gi,/useHead/gi,/useLazyFetch/gi,/useFetch/gi,/useAsyncData/gi,/<NuxtLayout/gi,/<NuxtPage/gi,/NuxtLayout/gi,/NuxtPage/gi,/pages\/.*\.vue/gi,/layouts\/.*\.vue/gi,/components\/.*\.vue/gi,/composables\/.*\.ts/gi,/middleware\/.*\.ts/gi,/server\/.*\.ts/gi,/plugins\/.*\.ts/gi,/public\//gi,/assets\//gi,/content\//gi]};for(const[i,r]of Object.entries(n))for(const n of r){const r=e.match(n);r&&(t.push(...r.slice(0,3)),t.push(`${i.toUpperCase()}: ${r.slice(0,3).join(", ")}`))}const i=e.match(/import\s+.*\s+from\s+['"][^'"]+['"]/gi);i&&t.push(`IMPORTS: ${i.slice(0,5).join(", ")}`);const r=e.match(/export\s+.*/gi);return r&&t.push(`EXPORTS: ${r.slice(0,3).join(", ")}`),t}async detectFrameworkWithAI(e){const t=await super.detectFramework();return e.confidence>.8?{...e.framework,bundler:t.bundler,packageManager:t.packageManager,hasTypeScript:t.hasTypeScript,hasRouter:t.hasRouter,projectRoot:this.projectRoot}:{...t,..."vanilla"!==e.framework.type&&{type:e.framework.type,name:e.framework.name}}}async generateAIOptimizedModifications(e){const t=(await super.generateModifications()).map(t=>this.enhanceModificationWithAI(t,e)),n=this.generateAIOptimizations(e);return t.push(...n),t}enhanceModificationWithAI(e,t){let n=e.content;return"legacy"===t.compatibilityMode&&(n=`// HumanBehavior SDK - Legacy Compatibility Mode\n${n}`),"provider"===t.integrationStrategy&&(n=`// HumanBehavior SDK - Provider Pattern (Future-proof)\n${n}`),t.conflicts.length>0&&(n=`// Conflict Resolution: ${t.conflicts.join(", ")}\n${n}`),{...e,content:n,description:`${e.description} (AI-optimized)`}}generateAIOptimizations(e){return[]}async applyModificationsWithAI(e,t){for(const n of e)try{const e=await this.detectConflicts(n);if(e.length>0){const i=await this.aiService.resolveConflicts(e,t.framework),r=await this.resolveConflicts(n,e,i,t);await this.applyModification(r)}else await this.applyModification(n)}catch(e){throw new Error(`Failed to apply AI-optimized modification to ${n.filePath}: ${e}`)}}async detectConflicts(t){const n=[];if(e.existsSync(t.filePath)){const i=e.readFileSync(t.filePath,"utf8");(i.includes("HumanBehavior")||i.includes("humanbehavior"))&&n.push("existing_humanbehavior_code"),t.content.includes("Provider")&&i.includes("Provider")&&n.push("existing_provider"),t.content.includes("import")&&i.includes("require(")&&n.push("module_system_conflict")}return n}async resolveConflicts(e,t,n,i){let r=e.content;for(let i=0;i<t.length;i++){const a=t[i];switch(n[i]){case"update_existing_integration":r=`// Updated HumanBehavior Integration\n${r}`;break;case"merge_providers":r=r.replace(/<HumanBehaviorProvider/g,'<HumanBehaviorProvider key="updated"');break;case"hybrid_module_support":r=`// Hybrid module system support\n${r}`;break;case"skip_conflict":return{...e,content:"",description:`${e.description} (skipped due to conflict)`};default:r=`// Conflict resolved: ${a}\n${r}`}}return{...e,content:r,description:`${e.description} (conflict-resolved)`}}async applyModification(n){if(!n.content)return;const i=t.dirname(n.filePath);switch(e.existsSync(i)||e.mkdirSync(i,{recursive:!0}),n.action){case"create":case"modify":e.writeFileSync(n.filePath,n.content);break;case"append":e.appendFileSync(n.filePath,"\n"+n.content)}}generateAINextSteps(e){const t=["✅ AI-optimized SDK installation completed!",`🎯 Framework detected: ${e.framework.name} (confidence: ${Math.round(100*e.confidence)}%)`,`🔧 Integration strategy: ${e.integrationStrategy}`,`🔄 Compatibility mode: ${e.compatibilityMode}`,"🚀 Your app is now tracking user behavior with AI-optimized configuration"];return e.recommendations.length>0&&(t.push("💡 AI Recommendations:"),e.recommendations.forEach(e=>t.push(` • ${e}`))),t}async learnFromInstallation(e,t){const n={timestamp:(new Date).toISOString(),framework:e.framework.name,patterns:e.patterns,integrationStrategy:e.integrationStrategy,compatibilityMode:e.compatibilityMode,modifications:t.length,success:!0};this.learningCache.set(`${e.framework.name}_${Date.now()}`,n),this.patternDatabase.has(e.framework.name)||this.patternDatabase.set(e.framework.name,[]),this.patternDatabase.get(e.framework.name).push(n),await this.saveLearningData()}loadLearningData(){}async saveLearningData(){}getAIInsights(e){return this.patternDatabase.get(e)||[]}getLearningStats(){const e={totalInstallations:this.learningCache.size,frameworks:{},patterns:{}};for(const[t,n]of this.patternDatabase.entries())e.frameworks[t]=n.length;return e}}class s{constructor(e,t){this.apiKey=e,this.aiService=t||new a}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}}class c{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 p extends r{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 c({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 r(this.apiKey,this.projectRoot);return await e.detectFramework()}}async scanProjectFiles(){const n=[],i=(r,a=0)=>{if(!(a>3))try{const o=e.readdirSync(r);for(const s of o){const o=t.join(r,s),c=e.statSync(o);c.isDirectory()&&!s.startsWith(".")&&"node_modules"!==s?i(o,a+1):c.isFile()&&this.isRelevantFile(s)&&n.push(o)}}catch(e){}};return i(this.projectRoot),n}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(n){const i=[];for(const r of n.slice(0,20))try{const n=e.readFileSync(r,"utf8"),a=t.relative(this.projectRoot,r);i.push(`File: ${a}\n${n.substring(0,1e3)}`)}catch(e){}return i}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 u{constructor(e){this.options=e}async run(){i.intro("🤖 AI-Enhanced HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(i.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd(),n=await this.chooseFramework();if(n||(i.cancel("Installation cancelled."),process.exit(0)),!this.options.yes){await this.confirmInstallation(t,n)||(i.cancel("Installation cancelled."),process.exit(0))}const r=i.spinner();r.start("🔍 Analyzing your project with AI...");const a=new p(e,t,n),o=await a.install();r.stop("Analysis complete!"),this.displayResults(o,n)}catch(e){i.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await i.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 i.confirm({message:`Ready to install HumanBehavior SDK in ${e} for ${t}?`})}async chooseFramework(){return await i.select({message:"Select your framework:",options:[{label:"React",value:"react"},{label:"Next.js",value:"nextjs"}