humanbehavior-js 0.4.27 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +151 -0
  2. package/package.json +114 -71
  3. package/packages/angular/dist/index.d.ts +46 -0
  4. package/packages/angular/dist/index.d.ts.map +1 -0
  5. package/packages/angular/dist/index.js +2 -0
  6. package/packages/angular/dist/index.js.map +1 -0
  7. package/packages/angular/dist/index.mjs +2 -0
  8. package/packages/angular/dist/index.mjs.map +1 -0
  9. package/packages/browser/dist/index.d.ts +5 -0
  10. package/packages/browser/dist/index.d.ts.map +1 -0
  11. package/packages/browser/dist/index.iife.js +12095 -0
  12. package/packages/browser/dist/index.iife.js.map +1 -0
  13. package/packages/browser/dist/index.js +2 -0
  14. package/packages/browser/dist/index.js.map +1 -0
  15. package/packages/browser/dist/index.min.js +2 -0
  16. package/packages/browser/dist/index.min.js.map +1 -0
  17. package/packages/browser/dist/index.mjs +2 -0
  18. package/packages/browser/dist/index.mjs.map +1 -0
  19. package/packages/react/dist/browser.d.ts +2 -0
  20. package/packages/react/dist/browser.d.ts.map +1 -0
  21. package/packages/react/dist/index.d.ts +48 -0
  22. package/packages/react/dist/index.d.ts.map +1 -0
  23. package/packages/react/dist/index.js +2 -0
  24. package/packages/react/dist/index.js.map +1 -0
  25. package/packages/react/dist/index.mjs +2 -0
  26. package/packages/react/dist/index.mjs.map +1 -0
  27. package/packages/remix/dist/index.d.ts +8 -0
  28. package/packages/remix/dist/index.d.ts.map +1 -0
  29. package/packages/remix/dist/index.js +2 -0
  30. package/packages/remix/dist/index.js.map +1 -0
  31. package/packages/remix/dist/index.mjs +2 -0
  32. package/packages/remix/dist/index.mjs.map +1 -0
  33. package/packages/svelte/dist/index.d.ts +11 -0
  34. package/packages/svelte/dist/index.d.ts.map +1 -0
  35. package/packages/svelte/dist/index.js +2 -0
  36. package/packages/svelte/dist/index.js.map +1 -0
  37. package/packages/svelte/dist/index.mjs +2 -0
  38. package/packages/svelte/dist/index.mjs.map +1 -0
  39. package/{dist/types/vue → packages/vue/dist}/index.d.ts +4 -5
  40. package/packages/vue/dist/index.d.ts.map +1 -0
  41. package/packages/vue/dist/index.js +2 -0
  42. package/packages/vue/dist/index.js.map +1 -0
  43. package/packages/vue/dist/index.mjs +2 -0
  44. package/packages/vue/dist/index.mjs.map +1 -0
  45. package/packages/wizard/dist/ai/ai-install-wizard.d.ts +145 -0
  46. package/packages/wizard/dist/ai/ai-install-wizard.d.ts.map +1 -0
  47. package/packages/wizard/dist/ai/manual-framework-wizard.d.ts +52 -0
  48. package/packages/wizard/dist/ai/manual-framework-wizard.d.ts.map +1 -0
  49. package/packages/wizard/dist/cli/ai-auto-install.d.ts +27 -0
  50. package/packages/wizard/dist/cli/ai-auto-install.d.ts.map +1 -0
  51. package/{dist → packages/wizard/dist}/cli/ai-auto-install.js +821 -905
  52. package/packages/wizard/dist/cli/ai-auto-install.js.map +1 -0
  53. package/packages/wizard/dist/cli/auto-install.d.ts +26 -0
  54. package/packages/wizard/dist/cli/auto-install.d.ts.map +1 -0
  55. package/{dist → packages/wizard/dist}/cli/auto-install.js +821 -905
  56. package/packages/wizard/dist/cli/auto-install.js.map +1 -0
  57. package/{dist/types → packages/wizard/dist/core}/install-wizard.d.ts +6 -8
  58. package/packages/wizard/dist/core/install-wizard.d.ts.map +1 -0
  59. package/packages/wizard/dist/index.d.ts +18 -0
  60. package/packages/wizard/dist/index.d.ts.map +1 -0
  61. package/packages/wizard/dist/index.js +2 -0
  62. package/packages/wizard/dist/index.js.map +1 -0
  63. package/packages/wizard/dist/index.mjs +2 -0
  64. package/packages/wizard/dist/index.mjs.map +1 -0
  65. package/packages/wizard/dist/services/centralized-ai-service.d.ts +159 -0
  66. package/packages/wizard/dist/services/centralized-ai-service.d.ts.map +1 -0
  67. package/packages/wizard/dist/services/remote-ai-service.d.ts +58 -0
  68. package/packages/wizard/dist/services/remote-ai-service.d.ts.map +1 -0
  69. package/WIZARD_USAGE_GUIDE.md +0 -381
  70. package/dist/cjs/angular/index.cjs +0 -14979
  71. package/dist/cjs/angular/index.cjs.map +0 -1
  72. package/dist/cjs/index.cjs +0 -14964
  73. package/dist/cjs/index.cjs.map +0 -1
  74. package/dist/cjs/install-wizard.cjs +0 -1576
  75. package/dist/cjs/install-wizard.cjs.map +0 -1
  76. package/dist/cjs/react/index.cjs +0 -15103
  77. package/dist/cjs/react/index.cjs.map +0 -1
  78. package/dist/cjs/remix/index.cjs +0 -15077
  79. package/dist/cjs/remix/index.cjs.map +0 -1
  80. package/dist/cjs/svelte/index.cjs +0 -14933
  81. package/dist/cjs/svelte/index.cjs.map +0 -1
  82. package/dist/cjs/vue/index.cjs +0 -14942
  83. package/dist/cjs/vue/index.cjs.map +0 -1
  84. package/dist/cjs/wizard/index.cjs +0 -3490
  85. package/dist/cjs/wizard/index.cjs.map +0 -1
  86. package/dist/cli/ai-auto-install.js.map +0 -1
  87. package/dist/cli/auto-install.js.map +0 -1
  88. package/dist/esm/angular/index.js +0 -14975
  89. package/dist/esm/angular/index.js.map +0 -1
  90. package/dist/esm/index.js +0 -14941
  91. package/dist/esm/index.js.map +0 -1
  92. package/dist/esm/install-wizard.js +0 -1553
  93. package/dist/esm/install-wizard.js.map +0 -1
  94. package/dist/esm/react/index.js +0 -15097
  95. package/dist/esm/react/index.js.map +0 -1
  96. package/dist/esm/remix/index.js +0 -15073
  97. package/dist/esm/remix/index.js.map +0 -1
  98. package/dist/esm/svelte/index.js +0 -14931
  99. package/dist/esm/svelte/index.js.map +0 -1
  100. package/dist/esm/vue/index.js +0 -14940
  101. package/dist/esm/vue/index.js.map +0 -1
  102. package/dist/esm/wizard/index.js +0 -3459
  103. package/dist/esm/wizard/index.js.map +0 -1
  104. package/dist/index.min.js +0 -2
  105. package/dist/index.min.js.map +0 -1
  106. package/dist/types/angular/index.d.ts +0 -357
  107. package/dist/types/index.d.ts +0 -644
  108. package/dist/types/react/index.d.ts +0 -345
  109. package/dist/types/remix/index.d.ts +0 -336
  110. package/dist/types/svelte/index.d.ts +0 -322
  111. package/dist/types/wizard/index.d.ts +0 -523
  112. package/readme.md +0 -335
  113. package/rollup.config.js +0 -422
  114. package/simple-spa.html +0 -1000
  115. package/src/angular/index.ts +0 -79
  116. package/src/api.ts +0 -416
  117. package/src/index.ts +0 -35
  118. package/src/react/AutoInstallWizard.tsx +0 -557
  119. package/src/react/browser.ts +0 -8
  120. package/src/react/index.tsx +0 -308
  121. package/src/redact.ts +0 -327
  122. package/src/remix/index.ts +0 -16
  123. package/src/svelte/index.ts +0 -14
  124. package/src/tracker.ts +0 -1587
  125. package/src/types/clack.d.ts +0 -31
  126. package/src/utils/ip-detector.ts +0 -158
  127. package/src/utils/logger.ts +0 -144
  128. package/src/utils/property-detector.ts +0 -345
  129. package/src/utils/property-manager.ts +0 -274
  130. package/src/vue/index.ts +0 -29
  131. package/src/wizard/README.md +0 -114
  132. package/src/wizard/ai/ai-install-wizard.ts +0 -897
  133. package/src/wizard/ai/manual-framework-wizard.ts +0 -238
  134. package/src/wizard/cli/ai-auto-install.ts +0 -241
  135. package/src/wizard/cli/auto-install.ts +0 -224
  136. package/src/wizard/core/install-wizard.ts +0 -1794
  137. package/src/wizard/index.ts +0 -23
  138. package/src/wizard/services/centralized-ai-service.ts +0 -668
  139. package/src/wizard/services/remote-ai-service.ts +0 -240
  140. package/tsconfig.json +0 -24
@@ -0,0 +1,2 @@
1
+ import*as e from"fs";import*as t from"path";import*as n from"@clack/prompts";class i{constructor(e,t=process.cwd()){this.framework=null,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(){const{execSync:e}=await import("child_process");let t="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&&(t+=" --legacy-peer-deps");try{e(t,{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,"src","pages","_app.tsx");if(e.existsSync(i)){n.push({filePath:t.join(this.projectRoot,"src","app","providers.tsx"),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 r=e.readFileSync(i,"utf8"),a=this.injectNextJSAppRouter(r);n.push({filePath:i,action:"modify",content:a,description:"Added Providers wrapper to Next.js App Router layout"})}else if(e.existsSync(r)){n.push({filePath:t.join(this.projectRoot,"src","components","providers.tsx"),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 i=e.readFileSync(r,"utf8"),a=this.injectNextJSPagesRouter(i);n.push({filePath:r,action:"modify",content:a,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 \n // Get API key from environment variable\n const apiKey = import.meta.env.PUBLIC_HUMANBEHAVIOR_API_KEY;\n \n console.log('HumanBehavior: API key found:', apiKey ? 'Yes' : 'No');\n \n if (apiKey) {\n try {\n const tracker = HumanBehaviorTracker.init(apiKey);\n console.log('HumanBehavior: Tracker initialized successfully');\n \n // Test event to verify tracking is working\n setTimeout(() => {\n tracker.customEvent('astro_page_view', {\n page: window.location.pathname,\n framework: 'astro'\n }).then(() => {\n console.log('HumanBehavior: Test event sent successfully');\n }).catch((error) => {\n console.error('HumanBehavior: Failed to send test event:', error);\n });\n }, 1000);\n \n } catch (error) {\n console.error('HumanBehavior: Failed to initialize tracker:', error);\n }\n } else {\n console.error('HumanBehavior: No API key found');\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 n=[],i=t.join(this.projectRoot,"app","plugins","humanbehavior.client.ts");n.push({filePath:i,action:"create",content:"import { HumanBehaviorTracker } from 'humanbehavior-js';\n\nexport default defineNuxtPlugin(() => {\n const config = useRuntimeConfig();\n \n // Initialize HumanBehavior SDK (client-side only)\n if (typeof window !== 'undefined') {\n const apiKey = config.public.humanBehaviorApiKey;\n console.log('HumanBehavior: API key:', apiKey ? 'present' : 'missing');\n \n if (apiKey) {\n try {\n const tracker = HumanBehaviorTracker.init(apiKey);\n console.log('HumanBehavior: Tracker initialized successfully');\n } catch (error) {\n console.error('HumanBehavior: Failed to initialize tracker:', error);\n }\n } else {\n console.error('HumanBehavior: No API key found in runtime config');\n }\n }\n});",description:"Created Nuxt plugin for HumanBehavior SDK in app directory"});const r=t.join(this.projectRoot,"nuxt.config.ts");if(e.existsSync(r)){const t=e.readFileSync(r,"utf8"),i=this.injectNuxtConfig(t);n.push({filePath:r,action:"modify",content:i,description:"Added HumanBehavior runtime config to Nuxt config"})}return n.push(this.createEnvironmentModification(this.framework)),n}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 t=[],n=this.findVueMainFile();if(n){const i=e.readFileSync(n,"utf8"),r=this.injectVuePlugin(i);t.push({filePath:n,action:"modify",content:r,description:"Added HumanBehaviorPlugin to Vue app"})}return t.push(this.createEnvironmentModification(this.framework)),t}async generateAngularModifications(){const n=[],i=t.join(this.projectRoot,"src","app","app.module.ts"),r=t.join(this.projectRoot,"src","app","app.ts"),a=t.join(this.projectRoot,"src","main.ts");if(e.existsSync(r)&&!e.existsSync(i)){if(e.existsSync(a)){const t=e.readFileSync(a,"utf8"),i=this.injectAngularStandaloneInit(t);n.push({filePath:a,action:"modify",content:i,description:"Added HumanBehavior initialization to Angular main.ts"})}}else if(e.existsSync(i)){const t=e.readFileSync(i,"utf8"),r=this.injectAngularModule(t);n.push({filePath:i,action:"modify",content:r,description:"Added HumanBehaviorModule to Angular app"})}const o=t.join(this.projectRoot,"src","environments","environment.ts"),s=t.join(this.projectRoot,"src","environments","environment.prod.ts"),c=t.dirname(o);if(e.existsSync(c)||e.mkdirSync(c,{recursive:!0}),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 development environment"})}}else n.push({filePath:o,action:"create",content:`export const environment = {\n production: false,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular development environment file"});if(e.existsSync(s)){const t=e.readFileSync(s,"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:s,action:"modify",content:e,description:"Added API key to Angular production environment"})}}else n.push({filePath:s,action:"create",content:`export const environment = {\n production: true,\n humanBehaviorApiKey: '${this.apiKey}'\n};`,description:"Created Angular production environment file"});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 store 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 store 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 console.log('Gatsby browser entry point loaded');\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n console.log('API Key found:', apiKey ? 'Yes' : 'No');\n if (apiKey) {\n const tracker = HumanBehaviorTracker.init(apiKey);\n console.log('HumanBehavior SDK initialized for Gatsby');\n } else {\n console.log('No API key found in environment variables');\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"),e}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.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){if(e.includes("Providers"))return e;return e.replace(/function MyApp/,"import { Providers } from '../components/providers';\n\nfunction MyApp").replace(/return \(([\s\S]*?)\);/,"return (\n <Providers>\n $1\n </Providers>\n );")}injectRemixProvider(e){if(e.includes("HumanBehaviorProvider"))return e;const t="import { HumanBehaviorProvider, createHumanBehaviorLoader } from 'humanbehavior-js/remix';",n='import { useLoaderData } from "@remix-run/react";';let i=e;if(!e.includes("HumanBehaviorProvider")){const e=i.lastIndexOf("import");if(-1!==e){const n=i.indexOf("\n",e);i=-1!==n?i.slice(0,n+1)+t+"\n"+i.slice(n+1):i+"\n"+t}else i=t+"\n"+i}if(!e.includes("useLoaderData")){const e=i.lastIndexOf("import");if(-1!==e){const t=i.indexOf("\n",e);i=-1!==t?i.slice(0,t+1)+n+"\n"+i.slice(t+1):i+"\n"+n}else i=n+"\n"+i}return e.includes("export const loader")||(i=i.replace(/export default function App\(\)/,"export const loader = createHumanBehaviorLoader();\n\nexport default function App()")),i=i.replace(/export default function App\(\) \{[\s\S]*?return \(([\s\S]*?)\);[\s\S]*?\}/,"export default function App() {\n const data = useLoaderData<typeof loader>();\n \n return (\n <HumanBehaviorProvider apiKey={data.ENV.HUMANBEHAVIOR_API_KEY}>\n $1\n </HumanBehaviorProvider>\n );\n}"),i}injectVuePlugin(e){if(e.includes("HumanBehaviorPlugin"))return e;const t="import { HumanBehaviorPlugin } from 'humanbehavior-js/vue';",n=this.framework?.features?.hasVue3;if(n){const n="app.use(HumanBehaviorPlugin, {\n apiKey: import.meta.env.VITE_HUMANBEHAVIOR_API_KEY\n});";let i=e;return e.includes(t)||(i=e.replace(/(import.*?from.*?['"]vue['"];?)/,`$1\n${t}`),i.includes(t)||(i=`${t}\n\n${i}`)),e.includes("createApp")&&(i=i.replace(/(app\.mount\(.*?\))/,`${n}\n\n$1`)),i}{const n="Vue.use(HumanBehaviorPlugin, {\n apiKey: process.env.VUE_APP_HUMANBEHAVIOR_API_KEY\n});";let i=e;return e.includes(t)||(i=e.replace(/(import.*?from.*?['"]vue['"];?)/,`$1\n${t}`),i.includes(t)||(i=`${t}\n\n${i}`)),e.includes("new Vue")&&(i=i.replace(/(new Vue\(.*?\))/,`${n}\n\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("humanBehaviorStore"))return e;return`import { humanBehaviorStore } from 'humanbehavior-js/svelte';\nhumanBehaviorStore.init(process.env.PUBLIC_HUMANBEHAVIOR_API_KEY || '');\n\n${e}`}injectSvelteKitLayout(e){if(e.includes("humanBehaviorStore"))return e;const t="import { humanBehaviorStore } from 'humanbehavior-js/svelte';",n="import { PUBLIC_HUMANBEHAVIOR_API_KEY } from '$env/static/public';",i="humanBehaviorStore.init(PUBLIC_HUMANBEHAVIOR_API_KEY || '');";return e.includes('<script lang="ts">')?e.replace(/<script lang="ts">/,`<script lang="ts">\n\t${n}\n\t${t}\n\t${i}`):e.includes("<script>")?e.replace(/<script>/,`<script>\n\t${n}\n\t${t}\n\t${i}`):e.includes('<script context="module">')?e.replace(/<script\s+context="module">/,`<script context="module">\n\t${n}\n\t${t}\n\t${i}`):e.replace(/<svelte:head>/,`<script lang="ts">\n\t${n}\n\t${t}\n\t${i}\n<\/script>\n\n<svelte:head>`)}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;return t?e.replace(/export default defineNuxtConfig\(\{/,"export default defineNuxtConfig({\n runtimeConfig: {\n public: {\n humanBehaviorApiKey: process.env.NUXT_PUBLIC_HUMANBEHAVIOR_API_KEY\n }\n },"):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){if(e.includes("HumanBehaviorTracker"))return e;const t="import { HumanBehaviorTracker } from 'humanbehavior-js';",n="\n// Initialize HumanBehavior SDK\nexport const onClientEntry = () => {\n console.log('Gatsby browser entry point loaded');\n const apiKey = process.env.GATSBY_HUMANBEHAVIOR_API_KEY;\n console.log('API Key found:', apiKey ? 'Yes' : 'No');\n if (apiKey) {\n const tracker = HumanBehaviorTracker.init(apiKey);\n console.log('HumanBehavior SDK initialized for Gatsby');\n } else {\n console.log('No API key found in environment variables');\n }\n};";return e.trim()?`${t}${n}\n\n${e}`:`${t}${n}`}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:"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 r{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 a extends i{constructor(e,t=process.cwd(),n){super(e,t),this.learningCache=new Map,this.patternDatabase=new Map,this.aiService=n||new r,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 o{constructor(e,t){this.apiKey=e,this.aiService=t||new r}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 s{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 c extends i{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 s({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 i(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 l{constructor(e){this.options=e}async run(){n.intro("🤖 AI-Enhanced HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(n.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd(),i=await this.chooseFramework();if(i||(n.cancel("Installation cancelled."),process.exit(0)),!this.options.yes){await this.confirmInstallation(t,i)||(n.cancel("Installation cancelled."),process.exit(0))}const r=n.spinner();r.start("🔍 Analyzing your project with AI...");const a=new c(e,t,i),o=await a.install();r.stop("Analysis complete!"),this.displayResults(o,i)}catch(e){n.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await n.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 n.confirm({message:`Ready to install HumanBehavior SDK in ${e} for ${t}?`})}async chooseFramework(){return await n.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(n.outro("🎉 Installation completed successfully!"),n.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}`);n.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&n.note(e.nextSteps.join("\n"),"Next Steps"),e.aiAnalysis&&(n.note(`Confidence: ${Math.round(100*e.aiAnalysis.confidence)}%`,"AI Analysis"),e.aiAnalysis.recommendations&&e.aiAnalysis.recommendations.length>0&&n.note(e.aiAnalysis.recommendations.join("\n"),"AI Recommendations"))}else n.cancel("Installation failed"),e.errors&&e.errors.length>0&&n.note(e.errors.join("\n"),"Errors")}}function u(){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 l(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":u(),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=>{n.cancel(`Unexpected error: ${e.message}`),process.exit(1)});class p{constructor(e){this.options=e}async run(){n.intro("🚀 HumanBehavior SDK Auto-Installation");try{const e=await this.getApiKey();e||(n.cancel("API key is required"),process.exit(1));const t=this.options.projectPath||process.cwd(),i=await this.chooseFramework();if(i||(n.cancel("Installation cancelled."),process.exit(0)),!this.options.yes){await this.confirmInstallation(t,i)||(n.cancel("Installation cancelled."),process.exit(0))}const r=n.spinner();r.start("🔍 Analyzing your project...");const a=new c(e,t,i),o=await a.install();r.stop("Detection complete!"),this.displayResults(o)}catch(e){n.cancel(`Error: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async getApiKey(){if(this.options.apiKey)return this.options.apiKey;return await n.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 chooseFramework(){return await n.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"}]})}async confirmInstallation(e,t){return await n.confirm({message:`Ready to install HumanBehavior SDK in ${e} for ${t}?`})}displayResults(e){if(e.success){if(n.outro("🎉 Installation completed successfully!"),n.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}`);n.note(t.join("\n"),"Files Modified")}e.nextSteps&&e.nextSteps.length>0&&n.note(e.nextSteps.join("\n"),"Next Steps")}else n.cancel("Installation failed"),e.errors&&e.errors.length>0&&n.note(e.errors.join("\n"),"Errors")}}function m(){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(import.meta.url===`file://${process.argv[1]}`){new p(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":m(),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=>{n.cancel(`Unexpected error: ${e.message}`),process.exit(1)})}class d{constructor(e){this.cache=new Map,this.config={openaiModel:"gpt-4",maxTokens:2e3,temperature:.3,enableCaching:!0,cacheTTL:3600,...e},this.initializeOpenAI()}initializeOpenAI(){try{const{OpenAI:e}=require("openai");this.openai=new e({apiKey:this.config.openaiApiKey})}catch(e){console.warn("OpenAI not available, falling back to heuristic analysis"),this.openai=null}}async analyzeCodePatterns(e){const t={codeSamples:e,timestamp:(new Date).toISOString()},n=this.generateCacheKey(t);if(this.config.enableCaching){const e=this.cache.get(n);if(e&&this.isCacheValid(e.timestamp))return e.analysis}const i=await this.performAIAnalysis(t);return this.config.enableCaching&&this.cache.set(n,{analysis:i,timestamp:Date.now()}),i}async resolveConflicts(e,t){const n={conflicts:e,framework:t,codeContext:"HumanBehavior SDK integration"};if(!this.openai)return this.resolveConflictsHeuristic(e,t);try{const e=this.buildConflictResolutionPrompt(n),t=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at resolving code integration conflicts. Provide specific resolution strategies."},{role:"user",content:e}],max_tokens:this.config.maxTokens,temperature:this.config.temperature}),i=t.choices[0]?.message?.content;return i&&"string"==typeof i?this.parseConflictResolutions(i):[]}catch(e){console.warn("AI conflict resolution failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.resolveConflictsHeuristic(e,t)}async generateOptimizations(e,t){const n={framework:e,patterns:t,projectContext:"HumanBehavior SDK integration"};if(!this.openai)return this.generateOptimizationsHeuristic(e,t);try{const e=this.buildOptimizationPrompt(n),t=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at optimizing code integration. Provide specific, actionable recommendations."},{role:"user",content:e}],max_tokens:this.config.maxTokens,temperature:this.config.temperature}),i=t.choices[0]?.message?.content;if(i)return this.parseOptimizations(i)}catch(e){console.warn("AI optimization generation failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.generateOptimizationsHeuristic(e,t)}async performAIAnalysis(e){if(!this.openai)return this.performHeuristicAnalysis(e);try{const t=this.buildAnalysisPrompt(e),n=await this.openai.chat.completions.create({model:this.config.openaiModel,messages:[{role:"system",content:"You are an expert at analyzing code patterns and determining optimal integration strategies. Provide detailed analysis in JSON format."},{role:"user",content:t}],max_tokens:this.config.maxTokens,temperature:this.config.temperature,response_format:{type:"json_object"}}),i=n.choices[0]?.message?.content;if(i)return this.parseAnalysisResult(i)}catch(e){console.warn("AI analysis failed, using heuristic approach:",e instanceof Error?e.message:"Unknown error")}return this.performHeuristicAnalysis(e)}buildAnalysisPrompt(e){return`Analyze these code samples to determine the framework and integration strategy:\n\n${e.codeSamples.join("\n\n")}\n\nProvide analysis in JSON format with:\n- framework: { name, type, confidence (0-1) }\n- patterns: array of detected patterns\n- conflicts: array of potential conflicts\n- recommendations: array of integration recommendations\n- integrationStrategy: "provider" | "plugin" | "module" | "script" | "standalone"\n- compatibilityMode: "modern" | "legacy" | "hybrid"\n\nFocus on:\n1. Framework detection beyond package.json\n2. Code patterns and architecture\n3. Integration compatibility\n4. Future-proof strategies\n5. Backward compatibility needs\n\nRespond with valid JSON only.`}buildConflictResolutionPrompt(e){return`Resolve these integration conflicts for ${e.framework.name}:\n\nConflicts: ${e.conflicts.join(", ")}\n\nFramework: ${e.framework.name} (${e.framework.type})\nContext: ${e.codeContext}\n\nProvide specific resolution strategies for each conflict. Options:\n- update_existing_integration: Update existing code\n- merge_providers: Merge multiple providers\n- hybrid_module_support: Support both module systems\n- skip_conflict: Skip the modification\n- custom_resolution: Custom resolution strategy\n\nRespond with a JSON array of resolution strategies.`}buildOptimizationPrompt(e){return`Generate optimizations for ${e.framework.name} integration:\n\nFramework: ${e.framework.name} (${e.framework.type})\nPatterns: ${e.patterns.join(", ")}\nContext: ${e.projectContext}\n\nProvide specific, actionable optimization recommendations for:\n1. Performance improvements\n2. Error handling\n3. Code organization\n4. Future-proofing\n5. Backward compatibility\n\nRespond with a JSON array of optimization recommendations.`}parseAnalysisResult(e){try{const t=JSON.parse(e);return{framework:t.framework||{name:"vanilla",type:"vanilla"},confidence:t.confidence||.5,patterns:t.patterns||[],conflicts:t.conflicts||[],recommendations:t.recommendations||[],integrationStrategy:t.integrationStrategy||"script",compatibilityMode:t.compatibilityMode||"modern"}}catch(e){return console.warn("Failed to parse AI analysis result:",e),this.getDefaultAnalysis()}}parseConflictResolutions(e){try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("Failed to parse conflict resolutions:",e),[]}}parseOptimizations(e){try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(e){return console.warn("Failed to parse optimizations:",e),[]}}performHeuristicAnalysis(e){const t=e.codeSamples.join(" ").toLowerCase();let n={name:"vanilla",type:"vanilla"},i=.5;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("next")?(n={name:"nextjs",type:"nextjs"},i=.9):t.includes("nuxt")&&(n={name:"nuxt",type:"nuxt"},i=.9);let r="script";"react"===n.type||"nextjs"===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.codeSamples,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}generateCacheKey(e){const t=JSON.stringify(e);return Buffer.from(t).toString("base64").substring(0,32)}isCacheValid(e){return Date.now()-e<1e3*(this.config.cacheTTL||3600)}getDefaultAnalysis(){return{framework:{name:"vanilla",type:"vanilla"},confidence:.5,patterns:[],conflicts:[],recommendations:[],integrationStrategy:"script",compatibilityMode:"modern"}}getStats(){return{cacheSize:this.cache.size,config:{model:this.config.openaiModel,maxTokens:this.config.maxTokens,temperature:this.config.temperature,caching:this.config.enableCaching},openaiAvailable:!!this.openai}}clearCache(){this.cache.clear()}}export{l as AIAutoInstallCLI,o as AIBrowserInstallationWizard,a as AIEnhancedInstallationWizard,p as AutoInstallCLI,i as AutoInstallationWizard,d as CentralizedAIService,i as InstallWizard,s as RemoteAIService};
2
+ //# sourceMappingURL=index.mjs.map