@houtini/lm 1.0.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 (260) hide show
  1. package/CHANGELOG.md +273 -0
  2. package/LICENSE +21 -0
  3. package/README.md +203 -0
  4. package/dist/cache/analysis-cache.d.ts +33 -0
  5. package/dist/cache/analysis-cache.d.ts.map +1 -0
  6. package/dist/cache/analysis-cache.js +56 -0
  7. package/dist/cache/analysis-cache.js.map +1 -0
  8. package/dist/cache/cache-manager.d.ts +29 -0
  9. package/dist/cache/cache-manager.d.ts.map +1 -0
  10. package/dist/cache/cache-manager.js +85 -0
  11. package/dist/cache/cache-manager.js.map +1 -0
  12. package/dist/cache/index.d.ts +16 -0
  13. package/dist/cache/index.d.ts.map +1 -0
  14. package/dist/cache/index.js +17 -0
  15. package/dist/cache/index.js.map +1 -0
  16. package/dist/cache/prompt-cache.d.ts +33 -0
  17. package/dist/cache/prompt-cache.d.ts.map +1 -0
  18. package/dist/cache/prompt-cache.js +61 -0
  19. package/dist/cache/prompt-cache.js.map +1 -0
  20. package/dist/config.d.ts +43 -0
  21. package/dist/config.d.ts.map +1 -0
  22. package/dist/config.js +70 -0
  23. package/dist/config.js.map +1 -0
  24. package/dist/core/ThreeStagePromptManager.d.ts +39 -0
  25. package/dist/core/ThreeStagePromptManager.d.ts.map +1 -0
  26. package/dist/core/ThreeStagePromptManager.js +176 -0
  27. package/dist/core/ThreeStagePromptManager.js.map +1 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +230 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/plugins/base-plugin.d.ts +47 -0
  33. package/dist/plugins/base-plugin.d.ts.map +1 -0
  34. package/dist/plugins/base-plugin.js +90 -0
  35. package/dist/plugins/base-plugin.js.map +1 -0
  36. package/dist/plugins/index.d.ts +58 -0
  37. package/dist/plugins/index.d.ts.map +1 -0
  38. package/dist/plugins/index.js +161 -0
  39. package/dist/plugins/index.js.map +1 -0
  40. package/dist/plugins/types.d.ts +5 -0
  41. package/dist/plugins/types.d.ts.map +1 -0
  42. package/dist/plugins/types.js +5 -0
  43. package/dist/plugins/types.js.map +1 -0
  44. package/dist/prompts/analyze/code-quality.d.ts +116 -0
  45. package/dist/prompts/analyze/code-quality.d.ts.map +1 -0
  46. package/dist/prompts/analyze/code-quality.js +433 -0
  47. package/dist/prompts/analyze/code-quality.js.map +1 -0
  48. package/dist/prompts/analyze/compare-integration.d.ts +130 -0
  49. package/dist/prompts/analyze/compare-integration.d.ts.map +1 -0
  50. package/dist/prompts/analyze/compare-integration.js +543 -0
  51. package/dist/prompts/analyze/compare-integration.js.map +1 -0
  52. package/dist/prompts/analyze/count-files.d.ts +109 -0
  53. package/dist/prompts/analyze/count-files.d.ts.map +1 -0
  54. package/dist/prompts/analyze/count-files.js +399 -0
  55. package/dist/prompts/analyze/count-files.js.map +1 -0
  56. package/dist/prompts/analyze/database-queries.d.ts +156 -0
  57. package/dist/prompts/analyze/database-queries.d.ts.map +1 -0
  58. package/dist/prompts/analyze/database-queries.js +759 -0
  59. package/dist/prompts/analyze/database-queries.js.map +1 -0
  60. package/dist/prompts/analyze/dependencies.d.ts +97 -0
  61. package/dist/prompts/analyze/dependencies.d.ts.map +1 -0
  62. package/dist/prompts/analyze/dependencies.js +333 -0
  63. package/dist/prompts/analyze/dependencies.js.map +1 -0
  64. package/dist/prompts/analyze/diff-signatures.d.ts +139 -0
  65. package/dist/prompts/analyze/diff-signatures.d.ts.map +1 -0
  66. package/dist/prompts/analyze/diff-signatures.js +702 -0
  67. package/dist/prompts/analyze/diff-signatures.js.map +1 -0
  68. package/dist/prompts/analyze/find-patterns.d.ts +128 -0
  69. package/dist/prompts/analyze/find-patterns.d.ts.map +1 -0
  70. package/dist/prompts/analyze/find-patterns.js +520 -0
  71. package/dist/prompts/analyze/find-patterns.js.map +1 -0
  72. package/dist/prompts/analyze/find-unused-css.d.ts +151 -0
  73. package/dist/prompts/analyze/find-unused-css.d.ts.map +1 -0
  74. package/dist/prompts/analyze/find-unused-css.js +754 -0
  75. package/dist/prompts/analyze/find-unused-css.js.map +1 -0
  76. package/dist/prompts/analyze/n8n-workflow.d.ts +137 -0
  77. package/dist/prompts/analyze/n8n-workflow.d.ts.map +1 -0
  78. package/dist/prompts/analyze/n8n-workflow.js +529 -0
  79. package/dist/prompts/analyze/n8n-workflow.js.map +1 -0
  80. package/dist/prompts/analyze/project-structure.d.ts +126 -0
  81. package/dist/prompts/analyze/project-structure.d.ts.map +1 -0
  82. package/dist/prompts/analyze/project-structure.js +569 -0
  83. package/dist/prompts/analyze/project-structure.js.map +1 -0
  84. package/dist/prompts/analyze/security-audit.d.ts +142 -0
  85. package/dist/prompts/analyze/security-audit.d.ts.map +1 -0
  86. package/dist/prompts/analyze/security-audit.js +637 -0
  87. package/dist/prompts/analyze/security-audit.js.map +1 -0
  88. package/dist/prompts/analyze/single-file.d.ts +162 -0
  89. package/dist/prompts/analyze/single-file.d.ts.map +1 -0
  90. package/dist/prompts/analyze/single-file.js +665 -0
  91. package/dist/prompts/analyze/single-file.js.map +1 -0
  92. package/dist/prompts/analyze/trace-execution.d.ts +126 -0
  93. package/dist/prompts/analyze/trace-execution.d.ts.map +1 -0
  94. package/dist/prompts/analyze/trace-execution.js +609 -0
  95. package/dist/prompts/analyze/trace-execution.js.map +1 -0
  96. package/dist/prompts/analyze/wordpress-plugin-audit.d.ts +116 -0
  97. package/dist/prompts/analyze/wordpress-plugin-audit.d.ts.map +1 -0
  98. package/dist/prompts/analyze/wordpress-plugin-audit.js +454 -0
  99. package/dist/prompts/analyze/wordpress-plugin-audit.js.map +1 -0
  100. package/dist/prompts/analyze/wordpress-security.d.ts +146 -0
  101. package/dist/prompts/analyze/wordpress-security.d.ts.map +1 -0
  102. package/dist/prompts/analyze/wordpress-security.js +698 -0
  103. package/dist/prompts/analyze/wordpress-security.js.map +1 -0
  104. package/dist/prompts/analyze/wordpress-theme-audit.d.ts +114 -0
  105. package/dist/prompts/analyze/wordpress-theme-audit.d.ts.map +1 -0
  106. package/dist/prompts/analyze/wordpress-theme-audit.js +538 -0
  107. package/dist/prompts/analyze/wordpress-theme-audit.js.map +1 -0
  108. package/dist/prompts/custom/custom-prompt.d.ts +135 -0
  109. package/dist/prompts/custom/custom-prompt.d.ts.map +1 -0
  110. package/dist/prompts/custom/custom-prompt.js +419 -0
  111. package/dist/prompts/custom/custom-prompt.js.map +1 -0
  112. package/dist/prompts/fun/arcade-game.d.ts +152 -0
  113. package/dist/prompts/fun/arcade-game.d.ts.map +1 -0
  114. package/dist/prompts/fun/arcade-game.js +653 -0
  115. package/dist/prompts/fun/arcade-game.js.map +1 -0
  116. package/dist/prompts/fun/create_text_adventure.d.ts +100 -0
  117. package/dist/prompts/fun/create_text_adventure.d.ts.map +1 -0
  118. package/dist/prompts/fun/create_text_adventure.js +397 -0
  119. package/dist/prompts/fun/create_text_adventure.js.map +1 -0
  120. package/dist/prompts/fun/css-art-generator.d.ts +168 -0
  121. package/dist/prompts/fun/css-art-generator.d.ts.map +1 -0
  122. package/dist/prompts/fun/css-art-generator.js +827 -0
  123. package/dist/prompts/fun/css-art-generator.js.map +1 -0
  124. package/dist/prompts/generate/project-documentation.d.ts +137 -0
  125. package/dist/prompts/generate/project-documentation.d.ts.map +1 -0
  126. package/dist/prompts/generate/project-documentation.js +666 -0
  127. package/dist/prompts/generate/project-documentation.js.map +1 -0
  128. package/dist/prompts/generate/refactoring.d.ts +164 -0
  129. package/dist/prompts/generate/refactoring.d.ts.map +1 -0
  130. package/dist/prompts/generate/refactoring.js +621 -0
  131. package/dist/prompts/generate/refactoring.js.map +1 -0
  132. package/dist/prompts/generate/responsive-component.d.ts +147 -0
  133. package/dist/prompts/generate/responsive-component.d.ts.map +1 -0
  134. package/dist/prompts/generate/responsive-component.js +955 -0
  135. package/dist/prompts/generate/responsive-component.js.map +1 -0
  136. package/dist/prompts/generate/typescript-conversion.d.ts +144 -0
  137. package/dist/prompts/generate/typescript-conversion.d.ts.map +1 -0
  138. package/dist/prompts/generate/typescript-conversion.js +527 -0
  139. package/dist/prompts/generate/typescript-conversion.js.map +1 -0
  140. package/dist/prompts/generate/unit-tests.d.ts +139 -0
  141. package/dist/prompts/generate/unit-tests.d.ts.map +1 -0
  142. package/dist/prompts/generate/unit-tests.js +578 -0
  143. package/dist/prompts/generate/unit-tests.js.map +1 -0
  144. package/dist/prompts/generate/wordpress-plugin.d.ts +179 -0
  145. package/dist/prompts/generate/wordpress-plugin.d.ts.map +1 -0
  146. package/dist/prompts/generate/wordpress-plugin.js +763 -0
  147. package/dist/prompts/generate/wordpress-plugin.js.map +1 -0
  148. package/dist/prompts/generate/wordpress-theme-from-static.d.ts +177 -0
  149. package/dist/prompts/generate/wordpress-theme-from-static.d.ts.map +1 -0
  150. package/dist/prompts/generate/wordpress-theme-from-static.js +695 -0
  151. package/dist/prompts/generate/wordpress-theme-from-static.js.map +1 -0
  152. package/dist/prompts/shared/cache-manager.d.ts +45 -0
  153. package/dist/prompts/shared/cache-manager.d.ts.map +1 -0
  154. package/dist/prompts/shared/cache-manager.js +129 -0
  155. package/dist/prompts/shared/cache-manager.js.map +1 -0
  156. package/dist/prompts/shared/helpers.d.ts +39 -0
  157. package/dist/prompts/shared/helpers.d.ts.map +1 -0
  158. package/dist/prompts/shared/helpers.js +151 -0
  159. package/dist/prompts/shared/helpers.js.map +1 -0
  160. package/dist/prompts/shared/templates.d.ts +35 -0
  161. package/dist/prompts/shared/templates.d.ts.map +1 -0
  162. package/dist/prompts/shared/templates.js +77 -0
  163. package/dist/prompts/shared/templates.js.map +1 -0
  164. package/dist/prompts/shared/types.d.ts +112 -0
  165. package/dist/prompts/shared/types.d.ts.map +1 -0
  166. package/dist/prompts/shared/types.js +5 -0
  167. package/dist/prompts/shared/types.js.map +1 -0
  168. package/dist/prompts/system/find-unused-files.d.ts +106 -0
  169. package/dist/prompts/system/find-unused-files.d.ts.map +1 -0
  170. package/dist/prompts/system/find-unused-files.js +353 -0
  171. package/dist/prompts/system/find-unused-files.js.map +1 -0
  172. package/dist/security/index.d.ts +39 -0
  173. package/dist/security/index.d.ts.map +1 -0
  174. package/dist/security/index.js +46 -0
  175. package/dist/security/index.js.map +1 -0
  176. package/dist/security/integration-helpers.d.ts +121 -0
  177. package/dist/security/integration-helpers.d.ts.map +1 -0
  178. package/dist/security/integration-helpers.js +190 -0
  179. package/dist/security/integration-helpers.js.map +1 -0
  180. package/dist/security/output-encoder.d.ts +94 -0
  181. package/dist/security/output-encoder.d.ts.map +1 -0
  182. package/dist/security/output-encoder.js +295 -0
  183. package/dist/security/output-encoder.js.map +1 -0
  184. package/dist/security/prompt-injection-guard.d.ts +59 -0
  185. package/dist/security/prompt-injection-guard.d.ts.map +1 -0
  186. package/dist/security/prompt-injection-guard.js +249 -0
  187. package/dist/security/prompt-injection-guard.js.map +1 -0
  188. package/dist/security/sanitisation.d.ts +67 -0
  189. package/dist/security/sanitisation.d.ts.map +1 -0
  190. package/dist/security/sanitisation.js +398 -0
  191. package/dist/security/sanitisation.js.map +1 -0
  192. package/dist/security/security-service.d.ts +103 -0
  193. package/dist/security/security-service.d.ts.map +1 -0
  194. package/dist/security/security-service.js +303 -0
  195. package/dist/security/security-service.js.map +1 -0
  196. package/dist/security-config.d.ts +45 -0
  197. package/dist/security-config.d.ts.map +1 -0
  198. package/dist/security-config.js +63 -0
  199. package/dist/security-config.js.map +1 -0
  200. package/dist/system/function-list.d.ts +61 -0
  201. package/dist/system/function-list.d.ts.map +1 -0
  202. package/dist/system/function-list.js +111 -0
  203. package/dist/system/function-list.js.map +1 -0
  204. package/dist/system/function-registry.d.ts +23 -0
  205. package/dist/system/function-registry.d.ts.map +1 -0
  206. package/dist/system/function-registry.js +136 -0
  207. package/dist/system/function-registry.js.map +1 -0
  208. package/dist/system/health-check.d.ts +33 -0
  209. package/dist/system/health-check.d.ts.map +1 -0
  210. package/dist/system/health-check.js +98 -0
  211. package/dist/system/health-check.js.map +1 -0
  212. package/dist/system/path-resolver.d.ts +55 -0
  213. package/dist/system/path-resolver.d.ts.map +1 -0
  214. package/dist/system/path-resolver.js +90 -0
  215. package/dist/system/path-resolver.js.map +1 -0
  216. package/dist/templates/plugin-template.d.ts +121 -0
  217. package/dist/templates/plugin-template.d.ts.map +1 -0
  218. package/dist/templates/plugin-template.js +450 -0
  219. package/dist/templates/plugin-template.js.map +1 -0
  220. package/dist/types/chunking-types.d.ts +88 -0
  221. package/dist/types/chunking-types.d.ts.map +1 -0
  222. package/dist/types/chunking-types.js +18 -0
  223. package/dist/types/chunking-types.js.map +1 -0
  224. package/dist/types/prompt-stages.d.ts +42 -0
  225. package/dist/types/prompt-stages.d.ts.map +1 -0
  226. package/dist/types/prompt-stages.js +6 -0
  227. package/dist/types/prompt-stages.js.map +1 -0
  228. package/dist/types.d.ts +46 -0
  229. package/dist/types.d.ts.map +1 -0
  230. package/dist/types.js +6 -0
  231. package/dist/types.js.map +1 -0
  232. package/dist/utils/css-parser.d.ts +26 -0
  233. package/dist/utils/css-parser.d.ts.map +1 -0
  234. package/dist/utils/css-parser.js +117 -0
  235. package/dist/utils/css-parser.js.map +1 -0
  236. package/dist/utils/path-resolver.d.ts +13 -0
  237. package/dist/utils/path-resolver.d.ts.map +1 -0
  238. package/dist/utils/path-resolver.js +78 -0
  239. package/dist/utils/path-resolver.js.map +1 -0
  240. package/dist/utils/plugin-utilities.d.ts +171 -0
  241. package/dist/utils/plugin-utilities.d.ts.map +1 -0
  242. package/dist/utils/plugin-utilities.js +221 -0
  243. package/dist/utils/plugin-utilities.js.map +1 -0
  244. package/dist/utils/streamHandler.d.ts +3 -0
  245. package/dist/utils/streamHandler.d.ts.map +1 -0
  246. package/dist/utils/streamHandler.js +137 -0
  247. package/dist/utils/streamHandler.js.map +1 -0
  248. package/dist/validation/output-validator.d.ts +136 -0
  249. package/dist/validation/output-validator.d.ts.map +1 -0
  250. package/dist/validation/output-validator.js +262 -0
  251. package/dist/validation/output-validator.js.map +1 -0
  252. package/dist/validation/response-factory.d.ts +44 -0
  253. package/dist/validation/response-factory.d.ts.map +1 -0
  254. package/dist/validation/response-factory.js +202 -0
  255. package/dist/validation/response-factory.js.map +1 -0
  256. package/dist/validation/schemas.d.ts +519 -0
  257. package/dist/validation/schemas.d.ts.map +1 -0
  258. package/dist/validation/schemas.js +6 -0
  259. package/dist/validation/schemas.js.map +1 -0
  260. package/package.json +72 -0
@@ -0,0 +1,665 @@
1
+ /**
2
+ * Plugin Template - Modern v4.2 (Single Source of Truth)
3
+ *
4
+ * Universal template that intelligently handles both single-file and multi-file analysis
5
+ * Automatically detects analysis type based on provided parameters
6
+ *
7
+ * Copy this template for creating any new plugin - it adapts to your needs
8
+ */
9
+ import { BasePlugin } from '../../plugins/base-plugin.js';
10
+ import { ThreeStagePromptManager } from '../../core/ThreeStagePromptManager.js';
11
+ import { withSecurity } from '../../security/integration-helpers.js';
12
+ import { readFileContent } from '../shared/helpers.js';
13
+ import { ModelSetup, ResponseProcessor, ParameterValidator, ErrorHandler, MultiFileAnalysis } from '../../utils/plugin-utilities.js';
14
+ import { getAnalysisCache } from '../../cache/index.js';
15
+ // Common Node.js modules - Use these instead of require()
16
+ import { basename, extname, relative } from 'path';
17
+ import { readFile, stat } from 'fs/promises';
18
+ export class CodeStructureAnalyzer extends BasePlugin {
19
+ constructor() {
20
+ super();
21
+ this.name = 'analyze_single_file';
22
+ this.category = 'analyze';
23
+ this.description = 'Analyze code structure, quality, patterns, and provide actionable recommendations for individual files or entire projects';
24
+ // Universal parameter set - supports both single and multi-file scenarios
25
+ this.parameters = {
26
+ // Single-file parameters
27
+ code: {
28
+ type: 'string',
29
+ description: 'The code to analyze (for single-file analysis)',
30
+ required: false
31
+ },
32
+ filePath: {
33
+ type: 'string',
34
+ description: 'Path to single file to analyze',
35
+ required: false
36
+ },
37
+ // Multi-file parameters
38
+ projectPath: {
39
+ type: 'string',
40
+ description: 'Path to project root (for multi-file analysis)',
41
+ required: false
42
+ },
43
+ files: {
44
+ type: 'array',
45
+ description: 'Array of specific file paths (for multi-file analysis)',
46
+ required: false,
47
+ items: { type: 'string' }
48
+ },
49
+ maxDepth: {
50
+ type: 'number',
51
+ description: 'Maximum directory depth for multi-file discovery (1-5)',
52
+ required: false,
53
+ default: 3
54
+ },
55
+ // Universal parameters
56
+ language: {
57
+ type: 'string',
58
+ description: 'Programming language',
59
+ required: false,
60
+ default: 'javascript'
61
+ },
62
+ analysisDepth: {
63
+ type: 'string',
64
+ description: 'Level of analysis detail',
65
+ enum: ['basic', 'detailed', 'comprehensive'],
66
+ default: 'detailed',
67
+ required: false
68
+ },
69
+ analysisType: {
70
+ type: 'string',
71
+ description: 'Type of analysis to perform',
72
+ enum: ['structure', 'quality', 'security', 'performance', 'comprehensive'],
73
+ default: 'comprehensive',
74
+ required: false
75
+ },
76
+ // Enhanced context parameter
77
+ context: {
78
+ type: 'object',
79
+ description: 'Optional context for framework-specific analysis',
80
+ required: false,
81
+ properties: {
82
+ projectType: {
83
+ type: 'string',
84
+ enum: ['wordpress-plugin', 'wordpress-theme', 'react-app', 'react-component', 'n8n-node', 'node-api', 'html-component', 'generic'],
85
+ description: 'Type of project for specialized analysis'
86
+ },
87
+ framework: {
88
+ type: 'string',
89
+ description: 'Framework being used (e.g., WordPress, React, Express)'
90
+ },
91
+ frameworkVersion: {
92
+ type: 'string',
93
+ description: 'Framework version for version-specific recommendations'
94
+ },
95
+ standards: {
96
+ type: 'array',
97
+ items: { type: 'string' },
98
+ description: 'Coding standards to validate against'
99
+ },
100
+ environment: {
101
+ type: 'string',
102
+ enum: ['browser', 'node', 'wordpress', 'hybrid'],
103
+ description: 'Runtime environment for context-aware analysis'
104
+ }
105
+ }
106
+ }
107
+ };
108
+ this.analysisCache = getAnalysisCache();
109
+ this.multiFileAnalysis = new MultiFileAnalysis();
110
+ // Cache and analysis utilities are initialized above
111
+ }
112
+ async execute(params, llmClient) {
113
+ return await withSecurity(this, params, llmClient, async (secureParams) => {
114
+ try {
115
+ // 1. Auto-detect analysis mode based on parameters
116
+ const analysisMode = this.detectAnalysisMode(secureParams);
117
+ // 2. Validate parameters based on detected mode
118
+ this.validateParameters(secureParams, analysisMode);
119
+ // 3. Setup model
120
+ const { model, contextLength } = await ModelSetup.getReadyModel(llmClient);
121
+ // 4. Route to appropriate analysis method
122
+ if (analysisMode === 'single-file') {
123
+ return await this.executeSingleFileAnalysis(secureParams, model, contextLength);
124
+ }
125
+ else {
126
+ return await this.executeMultiFileAnalysis(secureParams, model, contextLength);
127
+ }
128
+ }
129
+ catch (error) {
130
+ return ErrorHandler.createExecutionError('analyze_single_file', error);
131
+ }
132
+ });
133
+ }
134
+ /**
135
+ * Auto-detect whether this is single-file or multi-file analysis
136
+ *
137
+ * DETECTION GUIDE:
138
+ * Single-file: code, filePath provided → analyze individual file
139
+ * Multi-file: projectPath, files provided → analyze project/multiple files
140
+ * Default: single-file (this plugin's primary use case)
141
+ */
142
+ detectAnalysisMode(params) {
143
+ // Single-file indicators take priority (avoids default parameter issues)
144
+ if (params.code || params.filePath) {
145
+ return 'single-file';
146
+ }
147
+ // Multi-file indicators
148
+ if (params.projectPath || params.files) {
149
+ return 'multi-file';
150
+ }
151
+ // Default to single-file for code analysis
152
+ return 'single-file';
153
+ }
154
+ /**
155
+ * Validate parameters based on detected analysis mode
156
+ */
157
+ validateParameters(params, mode) {
158
+ if (mode === 'single-file') {
159
+ ParameterValidator.validateCodeOrFile(params);
160
+ }
161
+ else {
162
+ ParameterValidator.validateProjectPath(params);
163
+ ParameterValidator.validateDepth(params);
164
+ }
165
+ // Universal validations
166
+ ParameterValidator.validateEnum(params, 'analysisType', ['structure', 'quality', 'security', 'performance', 'comprehensive']);
167
+ ParameterValidator.validateEnum(params, 'analysisDepth', ['basic', 'detailed', 'comprehensive']);
168
+ }
169
+ /**
170
+ * Execute single-file analysis
171
+ */
172
+ async executeSingleFileAnalysis(params, model, contextLength) {
173
+ // Process single file input
174
+ let codeToAnalyze = params.code;
175
+ if (params.filePath) {
176
+ codeToAnalyze = await readFileContent(params.filePath);
177
+ }
178
+ // Generate prompt stages for single file
179
+ const promptStages = this.getSingleFilePromptStages({
180
+ ...params,
181
+ code: codeToAnalyze
182
+ });
183
+ // Execute with appropriate method
184
+ const promptManager = new ThreeStagePromptManager(contextLength);
185
+ const needsChunking = promptManager.needsChunking(promptStages);
186
+ if (needsChunking) {
187
+ const conversation = promptManager.createChunkedConversation(promptStages);
188
+ const messages = [
189
+ conversation.systemMessage,
190
+ ...conversation.dataMessages,
191
+ conversation.analysisMessage
192
+ ];
193
+ return await ResponseProcessor.executeChunked(messages, model, contextLength, 'analyze_single_file', 'single');
194
+ }
195
+ else {
196
+ return await ResponseProcessor.executeDirect(promptStages, model, contextLength, 'analyze_single_file');
197
+ }
198
+ }
199
+ /**
200
+ * Execute multi-file analysis
201
+ */
202
+ async executeMultiFileAnalysis(params, model, contextLength) {
203
+ // Discover files
204
+ let filesToAnalyze = params.files ||
205
+ await this.discoverRelevantFiles(params.projectPath, params.maxDepth, params.analysisType);
206
+ // Perform multi-file analysis with caching
207
+ const analysisResult = await this.performMultiFileAnalysis(filesToAnalyze, params, model, contextLength);
208
+ // Generate prompt stages for multi-file
209
+ const promptStages = this.getMultiFilePromptStages({
210
+ ...params,
211
+ analysisResult,
212
+ fileCount: filesToAnalyze.length
213
+ });
214
+ // Always use chunking for multi-file
215
+ const promptManager = new ThreeStagePromptManager(contextLength);
216
+ const conversation = promptManager.createChunkedConversation(promptStages);
217
+ const messages = [
218
+ conversation.systemMessage,
219
+ ...conversation.dataMessages,
220
+ conversation.analysisMessage
221
+ ];
222
+ return await ResponseProcessor.executeChunked(messages, model, contextLength, 'analyze_single_file', 'multifile');
223
+ }
224
+ /**
225
+ * Implement single-file prompt stages - OPTIMIZED FOR POWERFUL CODE ANALYSIS
226
+ */
227
+ getSingleFilePromptStages(params) {
228
+ const { code, language, analysisDepth, analysisType, filePath, context = {} } = params;
229
+ const projectType = context.projectType || 'generic';
230
+ const framework = context.framework || 'none specified';
231
+ const standards = context.standards?.join(', ') || 'clean code principles';
232
+ const systemAndContext = `You are a world-class senior software architect and code quality expert with deep expertise in ${language} and ${analysisDepth} code analysis.
233
+
234
+ **ANALYSIS CONTEXT:**
235
+ - Programming Language: ${language}
236
+ - Analysis Depth: ${analysisDepth}
237
+ - Analysis Type: ${analysisType}
238
+ - Project Type: ${projectType}
239
+ - Framework: ${framework} ${context.frameworkVersion ? `v${context.frameworkVersion}` : ''}
240
+ - Coding Standards: ${standards}
241
+ - Runtime Environment: ${context.environment || 'not specified'}
242
+ - File: ${filePath ? basename(filePath) : 'inline code'}
243
+
244
+ **YOUR EXPERTISE:**
245
+ You have 20+ years of experience in software development, code review, and architectural design. You understand:
246
+ - Design patterns and anti-patterns
247
+ - Performance optimization techniques
248
+ - Security vulnerabilities and best practices
249
+ - Framework-specific conventions and idioms
250
+ - Code maintainability and testability principles
251
+ - Industry best practices for ${language} development
252
+
253
+ ${this.getProjectSpecificInstructions(projectType)}
254
+
255
+ **ANALYSIS APPROACH:**
256
+ 1. **Structure Analysis**: Examine code organization, modularity, and architectural patterns
257
+ 2. **Quality Assessment**: Evaluate maintainability, readability, and adherence to best practices
258
+ 3. **Security Review**: Identify potential vulnerabilities and security concerns
259
+ 4. **Performance Analysis**: Spot performance bottlenecks and optimization opportunities
260
+ 5. **Actionable Recommendations**: Provide specific, implementable improvements with examples
261
+
262
+ You are thorough, insightful, and provide actionable feedback that helps developers grow and improve their code quality.`;
263
+ const dataPayload = `**CODE TO ANALYZE:**
264
+
265
+ \`\`\`${language}
266
+ ${code}
267
+ \`\`\`
268
+
269
+ ${filePath ? `\n**File Path:** ${filePath}` : ''}`;
270
+ const outputInstructions = `Provide a comprehensive code analysis covering all aspects of the ${language} code:
271
+
272
+ **Code Overview & Purpose:**
273
+ Provide a 2-3 sentence summary of what this code does, its overall quality level, and the main areas that need attention.
274
+
275
+ **Structural Analysis:**
276
+ - **Architecture**: Describe the code's architectural approach and organization
277
+ - **Components**: List key classes, functions, modules, and their roles
278
+ - **Dependencies**: Identify imports, exports, and external dependencies
279
+ - **Design Patterns**: Note any design patterns or architectural patterns used
280
+
281
+ **Quality Assessment:**
282
+ - **Lines of Code**: Estimate total lines and assess if appropriate for functionality
283
+ - **Complexity**: Evaluate cyclomatic complexity (low/medium/high) and maintainability
284
+ - **Code Quality**: Rate maintainability, testability, and reusability (high/medium/low)
285
+ - **Standards Adherence**: How well it follows ${language} and ${framework} best practices
286
+
287
+ **Issues & Findings:**
288
+ For each issue found, provide:
289
+ - **Type**: issue, improvement, security concern, or performance problem
290
+ - **Severity**: critical, high, medium, or low priority
291
+ - **Location**: Specific line numbers where possible
292
+ - **Description**: Clear explanation of the problem
293
+ - **Impact**: How this affects the code's functionality or quality
294
+ - **Recommendation**: Specific steps to fix or improve
295
+ - **Code Example**: Show before/after code where helpful
296
+
297
+ **Security Assessment:**
298
+ - **Vulnerability Analysis**: Identify potential security issues
299
+ - **Risk Level**: Overall security risk (critical/high/medium/low/none)
300
+ - **Security Recommendations**: Specific security improvements needed
301
+ - **Best Practices**: Security practices being followed or missing
302
+
303
+ **Performance Analysis:**
304
+ - **Bottlenecks**: Identify performance issues or inefficiencies
305
+ - **Optimization Opportunities**: Suggest specific performance improvements
306
+ - **Impact Assessment**: Estimate the performance impact of suggested changes
307
+
308
+ **Actionable Recommendations:**
309
+ Organize suggestions by priority:
310
+ - **Immediate Actions**: Critical fixes needed right away
311
+ - **Short-term Improvements**: Quality enhancements for next iteration
312
+ - **Long-term Enhancements**: Architectural or major structural improvements
313
+
314
+ **Code Examples:**
315
+ Where applicable, provide before/after code examples showing:
316
+ - Current problematic code
317
+ - Improved version with fix applied
318
+ - Clear explanation of why the improvement helps
319
+
320
+ **Best Practices Assessment:**
321
+ - Highlight coding practices being done well
322
+ - Identify areas where ${language}/${framework} best practices should be adopted
323
+ - Consider ${projectType} specific requirements and conventions
324
+
325
+ **Implementation Guidance:**
326
+ - Prioritize recommendations by impact and effort required
327
+ - Provide specific, actionable steps that can be implemented immediately
328
+ - Consider the existing codebase context and constraints
329
+ - Balance perfectionism with practical improvement steps
330
+
331
+ Focus on being constructive, specific, and actionable. Include line numbers where possible, and ensure all recommendations are implementable within the project's context.`;
332
+ return { systemAndContext, dataPayload, outputInstructions };
333
+ }
334
+ /**
335
+ * Implement multi-file prompt stages for project-wide analysis
336
+ */
337
+ getMultiFilePromptStages(params) {
338
+ const { analysisResult, analysisType, analysisDepth, fileCount, context = {} } = params;
339
+ const projectType = context.projectType || 'generic';
340
+ const systemAndContext = `You are a senior software architect specializing in ${analysisDepth} multi-file project analysis.
341
+
342
+ **PROJECT ANALYSIS CONTEXT:**
343
+ - Analysis Type: ${analysisType}
344
+ - Analysis Depth: ${analysisDepth}
345
+ - Files Analyzed: ${fileCount}
346
+ - Project Type: ${projectType}
347
+ - Mode: Multi-File Architecture Analysis
348
+
349
+ **YOUR EXPERTISE:**
350
+ You excel at identifying cross-file patterns, architectural issues, and system-wide improvements. You understand how files interact, dependencies flow, and architectural patterns emerge across codebases.
351
+
352
+ **FOCUS AREAS:**
353
+ - Cross-file dependencies and coupling
354
+ - Architectural patterns and violations
355
+ - Code duplication and reuse opportunities
356
+ - Consistency across modules
357
+ - System-wide security and performance concerns`;
358
+ const dataPayload = `**PROJECT ANALYSIS RESULTS:**
359
+
360
+ ${JSON.stringify(analysisResult, null, 2)}`;
361
+ const outputInstructions = `**PROVIDE PROJECT-WIDE ANALYSIS:**
362
+
363
+ ## Executive Summary
364
+ Overall architectural assessment and key findings across the entire project.
365
+
366
+ ## Architecture Analysis
367
+ - **Architectural Patterns**: Patterns identified across the codebase
368
+ - **Architecture Violations**: Areas where architectural principles are violated
369
+ - **Architectural Strengths**: What the project does well architecturally
370
+ - **Architectural Weaknesses**: Areas needing architectural improvement
371
+
372
+ ## Cross-File Analysis
373
+ For each cross-file issue identified:
374
+ - **Issue Type**: Duplication, coupling, inconsistency, security, or performance
375
+ - **Severity Level**: Critical, high, medium, or low impact
376
+ - **Issue Title**: Descriptive name for the cross-file issue
377
+ - **Description**: Detailed explanation of the cross-file problem
378
+ - **Affected Files**: List of files involved in this issue
379
+ - **System Impact**: How this affects the overall system
380
+ - **Resolution Strategy**: Specific steps to resolve across files
381
+
382
+ ## Dependency Analysis
383
+ - **Coupling Assessment**: Overall coupling level (high/medium/low)
384
+ - **Circular Dependencies**: Any circular dependency issues found
385
+ - **Unused Dependencies**: Dependencies that can be removed
386
+ - **Dependency Recommendations**: Improvements to dependency management
387
+
388
+ ## Code Consistency Analysis
389
+ - **Naming Conventions**: Consistency assessment (consistent/inconsistent/mixed)
390
+ - **Code Style**: Style consistency across files (consistent/inconsistent/mixed)
391
+ - **Pattern Usage**: Pattern consistency across the codebase
392
+ - **Consistency Improvements**: Recommendations for better consistency
393
+
394
+ ## System-Wide Recommendations
395
+ - **Architectural Improvements**: High-level architectural enhancements needed for better system design
396
+ - **Refactoring Opportunities**: Major refactoring opportunities across files to improve maintainability
397
+ - **Development Standards**: Coding standards and best practices that should be adopted project-wide
398
+ - **Tooling Recommendations**: Development tools and automation that would benefit the project
399
+ - **Quality Improvements**: Long-term quality enhancement strategies for sustainable development
400
+
401
+ Focus on providing strategic, actionable insights that improve overall project quality, team productivity, and long-term maintainability across the entire codebase.`;
402
+ return { systemAndContext, dataPayload, outputInstructions };
403
+ }
404
+ /**
405
+ * Backwards compatibility method
406
+ */
407
+ getPromptStages(params) {
408
+ const mode = this.detectAnalysisMode(params);
409
+ if (mode === 'single-file') {
410
+ return this.getSingleFilePromptStages(params);
411
+ }
412
+ else {
413
+ return this.getMultiFilePromptStages(params);
414
+ }
415
+ }
416
+ // Multi-file helper methods
417
+ async discoverRelevantFiles(projectPath, maxDepth, analysisType) {
418
+ const extensions = this.getFileExtensions(analysisType);
419
+ return await this.multiFileAnalysis.discoverFiles(projectPath, extensions, maxDepth);
420
+ }
421
+ async performMultiFileAnalysis(files, params, model, contextLength) {
422
+ const cacheKey = this.analysisCache.generateKey('analyze_single_file', params, files);
423
+ const cached = await this.analysisCache.get(cacheKey);
424
+ if (cached)
425
+ return cached;
426
+ const fileAnalysisResults = await this.multiFileAnalysis.analyzeBatch(files, (file) => this.analyzeIndividualFile(file, params, model), contextLength);
427
+ // Aggregate results for cross-file analysis
428
+ const aggregatedResult = {
429
+ summary: `Multi-file code analysis of ${files.length} files`,
430
+ findings: fileAnalysisResults,
431
+ architecture: this.analyzeArchitecture(fileAnalysisResults),
432
+ dependencies: this.analyzeDependencies(fileAnalysisResults),
433
+ patterns: this.identifyPatterns(fileAnalysisResults),
434
+ data: {
435
+ fileCount: files.length,
436
+ totalSize: fileAnalysisResults.reduce((sum, result) => sum + (result.size || 0), 0),
437
+ languages: this.getLanguageDistribution(fileAnalysisResults),
438
+ complexity: this.calculateProjectComplexity(fileAnalysisResults)
439
+ }
440
+ };
441
+ await this.analysisCache.cacheAnalysis(cacheKey, aggregatedResult, {
442
+ modelUsed: model.identifier || 'unknown',
443
+ executionTime: Date.now() - Date.now(),
444
+ timestamp: new Date().toISOString()
445
+ });
446
+ return aggregatedResult;
447
+ }
448
+ async analyzeIndividualFile(file, params, model) {
449
+ const content = await readFile(file, 'utf-8');
450
+ const stats = await stat(file);
451
+ return {
452
+ filePath: file,
453
+ fileName: basename(file),
454
+ size: content.length,
455
+ lines: content.split('\n').length,
456
+ extension: extname(file),
457
+ relativePath: relative(params.projectPath || '', file),
458
+ // Basic code analysis
459
+ functions: this.extractFunctions(content),
460
+ imports: this.extractImports(content),
461
+ exports: this.extractExports(content),
462
+ complexity: this.estimateComplexity(content),
463
+ modified: stats.mtime
464
+ };
465
+ }
466
+ // Enhanced analysis helper methods
467
+ analyzeArchitecture(results) {
468
+ return {
469
+ fileTypes: this.groupByType(results),
470
+ modularity: this.assessModularity(results),
471
+ layering: this.identifyLayers(results)
472
+ };
473
+ }
474
+ analyzeDependencies(results) {
475
+ return {
476
+ internal: this.findInternalDependencies(results),
477
+ external: this.findExternalDependencies(results),
478
+ circular: this.detectCircularDependencies(results)
479
+ };
480
+ }
481
+ identifyPatterns(results) {
482
+ // Simple pattern identification
483
+ const patterns = [];
484
+ if (results.some(r => r.fileName.includes('Controller')))
485
+ patterns.push('MVC Pattern');
486
+ if (results.some(r => r.fileName.includes('Service')))
487
+ patterns.push('Service Layer');
488
+ if (results.some(r => r.fileName.includes('Factory')))
489
+ patterns.push('Factory Pattern');
490
+ return patterns;
491
+ }
492
+ getLanguageDistribution(results) {
493
+ const distribution = {};
494
+ results.forEach(result => {
495
+ const ext = result.extension || 'unknown';
496
+ distribution[ext] = (distribution[ext] || 0) + 1;
497
+ });
498
+ return distribution;
499
+ }
500
+ calculateProjectComplexity(results) {
501
+ const avgComplexity = results.reduce((sum, r) => sum + (r.complexity || 0), 0) / results.length;
502
+ if (avgComplexity > 10)
503
+ return 'high';
504
+ if (avgComplexity > 5)
505
+ return 'medium';
506
+ return 'low';
507
+ }
508
+ // Simple code extraction methods
509
+ extractFunctions(content) {
510
+ const functionPattern = /function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)|const\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*\(/g;
511
+ const functions = [];
512
+ let match;
513
+ while ((match = functionPattern.exec(content)) !== null) {
514
+ functions.push(match[1] || match[2]);
515
+ }
516
+ return functions;
517
+ }
518
+ extractImports(content) {
519
+ const importPattern = /import.*?from\s+['"]([^'"]+)['"]/g;
520
+ const imports = [];
521
+ let match;
522
+ while ((match = importPattern.exec(content)) !== null) {
523
+ imports.push(match[1]);
524
+ }
525
+ return imports;
526
+ }
527
+ extractExports(content) {
528
+ const exportPattern = /export\s+(?:default\s+)?(?:class|function|const|let|var)?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)/g;
529
+ const exports = [];
530
+ let match;
531
+ while ((match = exportPattern.exec(content)) !== null) {
532
+ exports.push(match[1]);
533
+ }
534
+ return exports;
535
+ }
536
+ estimateComplexity(content) {
537
+ // Simple complexity estimation based on control flow keywords
538
+ const complexityKeywords = /\b(if|else|for|while|switch|case|catch|&&|\|\|)\b/g;
539
+ const matches = content.match(complexityKeywords) || [];
540
+ return matches.length;
541
+ }
542
+ // Placeholder methods for more advanced analysis
543
+ groupByType(results) {
544
+ return results.reduce((acc, r) => {
545
+ const ext = r.extension || 'unknown';
546
+ acc[ext] = (acc[ext] || 0) + 1;
547
+ return acc;
548
+ }, {});
549
+ }
550
+ assessModularity(results) {
551
+ // Simple modularity assessment
552
+ const avgFunctions = results.reduce((sum, r) => sum + (r.functions?.length || 0), 0) / results.length;
553
+ return avgFunctions > 10 ? 'low' : avgFunctions > 5 ? 'medium' : 'high';
554
+ }
555
+ identifyLayers(results) {
556
+ const layers = [];
557
+ if (results.some(r => r.relativePath.includes('controller')))
558
+ layers.push('Controller Layer');
559
+ if (results.some(r => r.relativePath.includes('service')))
560
+ layers.push('Service Layer');
561
+ if (results.some(r => r.relativePath.includes('model')))
562
+ layers.push('Data Layer');
563
+ return layers;
564
+ }
565
+ findInternalDependencies(results) {
566
+ return results.flatMap(r => r.imports?.filter((imp) => imp.startsWith('.')) || []);
567
+ }
568
+ findExternalDependencies(results) {
569
+ return results.flatMap(r => r.imports?.filter((imp) => !imp.startsWith('.')) || []);
570
+ }
571
+ detectCircularDependencies(results) {
572
+ // Simplified circular dependency detection
573
+ return []; // Placeholder for more complex analysis
574
+ }
575
+ getFileExtensions(analysisType) {
576
+ const extensionMap = {
577
+ 'structure': ['.js', '.ts', '.jsx', '.tsx', '.py', '.php', '.java', '.cs', '.rb', '.html', '.css', '.scss', '.sass', '.less'],
578
+ 'quality': ['.js', '.ts', '.jsx', '.tsx', '.py', '.php', '.java', '.cs', '.rb', '.html', '.css', '.scss', '.sass', '.less', '.json', '.yml', '.yaml'],
579
+ 'security': ['.js', '.ts', '.jsx', '.tsx', '.py', '.php', '.java', '.cs', '.html'],
580
+ 'performance': ['.js', '.ts', '.jsx', '.tsx', '.py', '.php', '.java', '.html', '.css', '.scss', '.sass'],
581
+ 'comprehensive': ['.js', '.ts', '.jsx', '.tsx', '.py', '.php', '.java', '.cs', '.rb', '.go', '.cpp', '.c', '.h', '.html', '.css', '.scss', '.sass', '.less', '.json', '.yml', '.yaml', '.md', '.txt', '.xml']
582
+ };
583
+ return extensionMap[analysisType] || extensionMap.comprehensive;
584
+ }
585
+ /**
586
+ * Project-specific analysis instructions
587
+ */
588
+ getProjectSpecificInstructions(projectType) {
589
+ const instructions = {
590
+ 'wordpress-plugin': `
591
+ **WORDPRESS PLUGIN EXPERTISE:**
592
+ - Hook system: action/filter usage, priority settings, timing
593
+ - Database operations: $wpdb practices, custom tables, option API
594
+ - Admin interfaces: menu structure, settings API, meta boxes
595
+ - Security: nonces, capability checks, data sanitization, SQL injection prevention
596
+ - Multisite compatibility and network admin considerations
597
+ - Internationalization: text domains, translation functions
598
+ - Plugin architecture: activation/deactivation hooks, uninstall procedures`,
599
+ 'wordpress-theme': `
600
+ **WORDPRESS THEME EXPERTISE:**
601
+ - Template hierarchy and conditional tags
602
+ - Custom post types, taxonomies, and meta fields
603
+ - Customizer API and theme supports
604
+ - Widget areas, navigation menus, and custom widgets
605
+ - Asset enqueueing and dependency management
606
+ - Child theme compatibility and parent theme integration
607
+ - Performance: lazy loading, critical CSS, image optimization`,
608
+ 'react-app': `
609
+ **REACT APPLICATION EXPERTISE:**
610
+ - Component architecture: composition vs inheritance
611
+ - State management: Context, Redux, Zustand patterns
612
+ - Performance optimization: React.memo, useMemo, useCallback
613
+ - Side effects: useEffect best practices, cleanup functions
614
+ - Routing: React Router patterns, code splitting
615
+ - Testing: component testing, integration testing strategies
616
+ - Build optimization: bundle splitting, tree shaking`,
617
+ 'react-component': `
618
+ **REACT COMPONENT EXPERTISE:**
619
+ - Props design: interface clarity, default values, validation
620
+ - Hook patterns: custom hooks, dependency arrays
621
+ - Render performance: preventing unnecessary re-renders
622
+ - Accessibility: ARIA attributes, keyboard navigation, screen readers
623
+ - Styling approaches: CSS modules, styled-components, Tailwind
624
+ - Component patterns: controlled vs uncontrolled, compound components
625
+ - Testing: unit tests, snapshot tests, user interaction tests`,
626
+ 'n8n-node': `
627
+ **N8N NODE EXPERTISE:**
628
+ - Node structure: properties, credentials, resource locators
629
+ - Execute method: input processing, output formatting
630
+ - Error handling: user-friendly messages, retry strategies
631
+ - API integration: authentication, rate limiting, pagination
632
+ - Resource optimization: memory usage, execution time
633
+ - Testing: node testing framework, mock data patterns`,
634
+ 'node-api': `
635
+ **NODE.JS API EXPERTISE:**
636
+ - Express patterns: middleware design, route organization
637
+ - Authentication: JWT, sessions, OAuth implementations
638
+ - Database patterns: connection pooling, query optimization
639
+ - Error handling: async/await patterns, global error handlers
640
+ - Security: helmet, rate limiting, input validation
641
+ - Performance: caching strategies, response compression
642
+ - API design: RESTful principles, versioning, documentation`,
643
+ 'html-component': `
644
+ **HTML COMPONENT EXPERTISE:**
645
+ - Semantic HTML: proper element usage, document outline
646
+ - Accessibility: WCAG guidelines, ARIA attributes, keyboard navigation
647
+ - Progressive enhancement: baseline functionality, JavaScript enhancement
648
+ - CSS architecture: BEM methodology, component isolation
649
+ - Performance: critical path optimization, resource hints
650
+ - Browser compatibility: graceful degradation, polyfills
651
+ - Web standards: HTML5 validation, microdata, structured data`,
652
+ 'generic': `
653
+ **GENERAL CODE EXPERTISE:**
654
+ Focus on universal software engineering principles: SOLID principles, design patterns, code organization, error handling, testing strategies, performance optimization, and maintainability practices applicable across languages and frameworks.`
655
+ };
656
+ return instructions[projectType] || instructions.generic;
657
+ }
658
+ generateCacheKey(files, params) {
659
+ const fileHash = files.join('|');
660
+ const paramHash = JSON.stringify(params);
661
+ return `${fileHash}_${paramHash}`.substring(0, 64);
662
+ }
663
+ }
664
+ export default CodeStructureAnalyzer;
665
+ //# sourceMappingURL=single-file.js.map