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