mcp-image 0.1.0 → 0.2.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 (178) hide show
  1. package/README.md +41 -17
  2. package/dist/api/geminiClient.d.ts +2 -12
  3. package/dist/api/geminiClient.d.ts.map +1 -1
  4. package/dist/api/geminiClient.js +28 -56
  5. package/dist/api/geminiClient.js.map +1 -1
  6. package/dist/api/geminiTextClient.d.ts +42 -0
  7. package/dist/api/geminiTextClient.d.ts.map +1 -0
  8. package/dist/api/geminiTextClient.js +198 -0
  9. package/dist/api/geminiTextClient.js.map +1 -0
  10. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.d.ts +84 -0
  11. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.d.ts.map +1 -0
  12. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.js +100 -0
  13. package/dist/business/__tests__/mocks/mcpSamplingClient.mock.js.map +1 -0
  14. package/dist/business/bestPracticesEngine.d.ts +149 -0
  15. package/dist/business/bestPracticesEngine.d.ts.map +1 -0
  16. package/dist/business/bestPracticesEngine.js +781 -0
  17. package/dist/business/bestPracticesEngine.js.map +1 -0
  18. package/dist/business/complexityAssessment.d.ts +132 -0
  19. package/dist/business/complexityAssessment.d.ts.map +1 -0
  20. package/dist/business/complexityAssessment.js +488 -0
  21. package/dist/business/complexityAssessment.js.map +1 -0
  22. package/dist/business/fallbackStrategies.d.ts +177 -0
  23. package/dist/business/fallbackStrategies.d.ts.map +1 -0
  24. package/dist/business/fallbackStrategies.js +368 -0
  25. package/dist/business/fallbackStrategies.js.map +1 -0
  26. package/dist/business/imageGenerator.d.ts.map +1 -1
  27. package/dist/business/imageGenerator.js +26 -5
  28. package/dist/business/imageGenerator.js.map +1 -1
  29. package/dist/business/multiImage/aspectRatioController.d.ts +77 -0
  30. package/dist/business/multiImage/aspectRatioController.d.ts.map +1 -0
  31. package/dist/business/multiImage/aspectRatioController.js +580 -0
  32. package/dist/business/multiImage/aspectRatioController.js.map +1 -0
  33. package/dist/business/multiImage/multiImageCoordinator.d.ts +142 -0
  34. package/dist/business/multiImage/multiImageCoordinator.d.ts.map +1 -0
  35. package/dist/business/multiImage/multiImageCoordinator.js +801 -0
  36. package/dist/business/multiImage/multiImageCoordinator.js.map +1 -0
  37. package/dist/business/pomlTemplateEngine.d.ts +206 -0
  38. package/dist/business/pomlTemplateEngine.d.ts.map +1 -0
  39. package/dist/business/pomlTemplateEngine.js +737 -0
  40. package/dist/business/pomlTemplateEngine.js.map +1 -0
  41. package/dist/business/promptOrchestrator.d.ts +173 -0
  42. package/dist/business/promptOrchestrator.d.ts.map +1 -0
  43. package/dist/business/promptOrchestrator.js +490 -0
  44. package/dist/business/promptOrchestrator.js.map +1 -0
  45. package/dist/business/responseBuilder.d.ts +2 -2
  46. package/dist/business/responseBuilder.d.ts.map +1 -1
  47. package/dist/business/responseBuilder.js +6 -1
  48. package/dist/business/responseBuilder.js.map +1 -1
  49. package/dist/business/structuredPromptGenerator.d.ts +54 -0
  50. package/dist/business/structuredPromptGenerator.d.ts.map +1 -0
  51. package/dist/business/structuredPromptGenerator.js +208 -0
  52. package/dist/business/structuredPromptGenerator.js.map +1 -0
  53. package/dist/business/templateNormalizer.d.ts +81 -0
  54. package/dist/business/templateNormalizer.d.ts.map +1 -0
  55. package/dist/business/templateNormalizer.js +659 -0
  56. package/dist/business/templateNormalizer.js.map +1 -0
  57. package/dist/documentation/apiContractValidation.d.ts +62 -0
  58. package/dist/documentation/apiContractValidation.d.ts.map +1 -0
  59. package/dist/documentation/apiContractValidation.js +305 -0
  60. package/dist/documentation/apiContractValidation.js.map +1 -0
  61. package/dist/infrastructure/concurrency/concurrencyManager.d.ts +101 -0
  62. package/dist/infrastructure/concurrency/concurrencyManager.d.ts.map +1 -0
  63. package/dist/infrastructure/concurrency/concurrencyManager.js +345 -0
  64. package/dist/infrastructure/concurrency/concurrencyManager.js.map +1 -0
  65. package/dist/infrastructure/config/secureConfigManager.d.ts +319 -0
  66. package/dist/infrastructure/config/secureConfigManager.d.ts.map +1 -0
  67. package/dist/infrastructure/config/secureConfigManager.js +600 -0
  68. package/dist/infrastructure/config/secureConfigManager.js.map +1 -0
  69. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.d.ts +229 -0
  70. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.d.ts.map +1 -0
  71. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.js +61 -0
  72. package/dist/infrastructure/errorHandling/orchestrationErrorHandler.js.map +1 -0
  73. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.d.ts +133 -0
  74. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.d.ts.map +1 -0
  75. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.js +569 -0
  76. package/dist/infrastructure/errorHandling/orchestrationErrorHandlerImpl.js.map +1 -0
  77. package/dist/infrastructure/mcp/MCPSamplingClient.d.ts +19 -0
  78. package/dist/infrastructure/mcp/MCPSamplingClient.d.ts.map +1 -0
  79. package/dist/infrastructure/mcp/MCPSamplingClient.js +31 -0
  80. package/dist/infrastructure/mcp/MCPSamplingClient.js.map +1 -0
  81. package/dist/infrastructure/mcp/RealMCPSamplingClient.d.ts +59 -0
  82. package/dist/infrastructure/mcp/RealMCPSamplingClient.d.ts.map +1 -0
  83. package/dist/infrastructure/mcp/RealMCPSamplingClient.js +271 -0
  84. package/dist/infrastructure/mcp/RealMCPSamplingClient.js.map +1 -0
  85. package/dist/infrastructure/metadata/generationMetadata.d.ts +72 -0
  86. package/dist/infrastructure/metadata/generationMetadata.d.ts.map +1 -0
  87. package/dist/infrastructure/metadata/generationMetadata.js +228 -0
  88. package/dist/infrastructure/metadata/generationMetadata.js.map +1 -0
  89. package/dist/infrastructure/monitoring/OrchestrationMetrics.d.ts +106 -0
  90. package/dist/infrastructure/monitoring/OrchestrationMetrics.d.ts.map +1 -0
  91. package/dist/infrastructure/monitoring/OrchestrationMetrics.js +456 -0
  92. package/dist/infrastructure/monitoring/OrchestrationMetrics.js.map +1 -0
  93. package/dist/infrastructure/monitoring/alertingSystem.d.ts +135 -0
  94. package/dist/infrastructure/monitoring/alertingSystem.d.ts.map +1 -0
  95. package/dist/infrastructure/monitoring/alertingSystem.js +549 -0
  96. package/dist/infrastructure/monitoring/alertingSystem.js.map +1 -0
  97. package/dist/infrastructure/optimization/performanceOptimizer.d.ts +89 -0
  98. package/dist/infrastructure/optimization/performanceOptimizer.d.ts.map +1 -0
  99. package/dist/infrastructure/optimization/performanceOptimizer.js +375 -0
  100. package/dist/infrastructure/optimization/performanceOptimizer.js.map +1 -0
  101. package/dist/infrastructure/security/AdvancedContentFilter.d.ts +99 -0
  102. package/dist/infrastructure/security/AdvancedContentFilter.d.ts.map +1 -0
  103. package/dist/infrastructure/security/AdvancedContentFilter.js +363 -0
  104. package/dist/infrastructure/security/AdvancedContentFilter.js.map +1 -0
  105. package/dist/infrastructure/security/MCPSecurityValidator.d.ts +62 -0
  106. package/dist/infrastructure/security/MCPSecurityValidator.d.ts.map +1 -0
  107. package/dist/infrastructure/security/MCPSecurityValidator.js +129 -0
  108. package/dist/infrastructure/security/MCPSecurityValidator.js.map +1 -0
  109. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.d.ts +304 -0
  110. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.d.ts.map +1 -0
  111. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.js +61 -0
  112. package/dist/infrastructure/security/OrchestrationSecurityMiddleware.js.map +1 -0
  113. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.d.ts +62 -0
  114. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.d.ts.map +1 -0
  115. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.js +591 -0
  116. package/dist/infrastructure/security/OrchestrationSecurityMiddlewareImpl.js.map +1 -0
  117. package/dist/infrastructure/security/SecureMCPClient.d.ts +154 -0
  118. package/dist/infrastructure/security/SecureMCPClient.d.ts.map +1 -0
  119. package/dist/infrastructure/security/SecureMCPClient.js +292 -0
  120. package/dist/infrastructure/security/SecureMCPClient.js.map +1 -0
  121. package/dist/infrastructure/security/SecurityIncidentManager.d.ts +142 -0
  122. package/dist/infrastructure/security/SecurityIncidentManager.d.ts.map +1 -0
  123. package/dist/infrastructure/security/SecurityIncidentManager.js +260 -0
  124. package/dist/infrastructure/security/SecurityIncidentManager.js.map +1 -0
  125. package/dist/infrastructure/security/apiKeyManager.d.ts +297 -0
  126. package/dist/infrastructure/security/apiKeyManager.d.ts.map +1 -0
  127. package/dist/infrastructure/security/apiKeyManager.js +254 -0
  128. package/dist/infrastructure/security/apiKeyManager.js.map +1 -0
  129. package/dist/infrastructure/security/dataSanitizer.d.ts +157 -0
  130. package/dist/infrastructure/security/dataSanitizer.d.ts.map +1 -0
  131. package/dist/infrastructure/security/dataSanitizer.js +525 -0
  132. package/dist/infrastructure/security/dataSanitizer.js.map +1 -0
  133. package/dist/infrastructure/validation/inputValidator.d.ts +54 -0
  134. package/dist/infrastructure/validation/inputValidator.d.ts.map +1 -0
  135. package/dist/infrastructure/validation/inputValidator.js +362 -0
  136. package/dist/infrastructure/validation/inputValidator.js.map +1 -0
  137. package/dist/integration/parameterOptimizer.d.ts +69 -0
  138. package/dist/integration/parameterOptimizer.d.ts.map +1 -0
  139. package/dist/integration/parameterOptimizer.js +317 -0
  140. package/dist/integration/parameterOptimizer.js.map +1 -0
  141. package/dist/integration/twoStageProcessor.d.ts +66 -0
  142. package/dist/integration/twoStageProcessor.d.ts.map +1 -0
  143. package/dist/integration/twoStageProcessor.js +348 -0
  144. package/dist/integration/twoStageProcessor.js.map +1 -0
  145. package/dist/server/handlers/structuredPromptHandler.d.ts +65 -0
  146. package/dist/server/handlers/structuredPromptHandler.d.ts.map +1 -0
  147. package/dist/server/handlers/structuredPromptHandler.js +314 -0
  148. package/dist/server/handlers/structuredPromptHandler.js.map +1 -0
  149. package/dist/server/mcpServer.d.ts +16 -35
  150. package/dist/server/mcpServer.d.ts.map +1 -1
  151. package/dist/server/mcpServer.js +111 -150
  152. package/dist/server/mcpServer.js.map +1 -1
  153. package/dist/server/mcpServerWithOrchestration.d.ts +98 -0
  154. package/dist/server/mcpServerWithOrchestration.d.ts.map +1 -0
  155. package/dist/server/mcpServerWithOrchestration.js +284 -0
  156. package/dist/server/mcpServerWithOrchestration.js.map +1 -0
  157. package/dist/types/mcpOrchestrationTypes.d.ts +135 -0
  158. package/dist/types/mcpOrchestrationTypes.d.ts.map +1 -0
  159. package/dist/types/mcpOrchestrationTypes.js +28 -0
  160. package/dist/types/mcpOrchestrationTypes.js.map +1 -0
  161. package/dist/types/multiImageTypes.d.ts +328 -0
  162. package/dist/types/multiImageTypes.d.ts.map +1 -0
  163. package/dist/types/multiImageTypes.js +27 -0
  164. package/dist/types/multiImageTypes.js.map +1 -0
  165. package/dist/types/performanceTypes.d.ts +300 -0
  166. package/dist/types/performanceTypes.d.ts.map +1 -0
  167. package/dist/types/performanceTypes.js +50 -0
  168. package/dist/types/performanceTypes.js.map +1 -0
  169. package/dist/types/twoStageTypes.d.ts +123 -0
  170. package/dist/types/twoStageTypes.d.ts.map +1 -0
  171. package/dist/types/twoStageTypes.js +7 -0
  172. package/dist/types/twoStageTypes.js.map +1 -0
  173. package/dist/utils/config.d.ts +1 -0
  174. package/dist/utils/config.d.ts.map +1 -1
  175. package/dist/utils/config.js +1 -0
  176. package/dist/utils/config.js.map +1 -1
  177. package/package.json +11 -4
  178. package/vitest.config.mjs +0 -47
@@ -0,0 +1,737 @@
1
+ "use strict";
2
+ /**
3
+ * POML Template Engine for Microsoft POML syntax processing
4
+ * Handles template application logic, prompt structuring, and individual feature control
5
+ * Supports CONFIG3 requirement: granular feature flag control for best practices
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.POMLTemplateEngineImpl = void 0;
9
+ exports.createPOMLTemplateEngine = createPOMLTemplateEngine;
10
+ const result_1 = require("../types/result");
11
+ const errors_1 = require("../utils/errors");
12
+ /**
13
+ * Default feature flags configuration (all enabled)
14
+ */
15
+ const DEFAULT_FEATURE_FLAGS = {
16
+ hyperSpecific: true,
17
+ characterConsistency: true,
18
+ contextIntent: true,
19
+ semanticNegatives: true,
20
+ cameraControl: true,
21
+ aspectRatio: true,
22
+ iterateRefine: true,
23
+ };
24
+ /**
25
+ * Implementation of POML Template Engine
26
+ * Handles Microsoft POML syntax processing with granular feature control
27
+ */
28
+ /**
29
+ * Factory function to create POMLTemplateEngine instance
30
+ * @param initialFlags Optional feature flags configuration
31
+ * @returns POMLTemplateEngine instance
32
+ */
33
+ function createPOMLTemplateEngine(initialFlags) {
34
+ return new POMLTemplateEngineImpl(initialFlags);
35
+ }
36
+ class POMLTemplateEngineImpl {
37
+ constructor(initialFlags) {
38
+ this.featureFlags = { ...DEFAULT_FEATURE_FLAGS, ...initialFlags };
39
+ this.templates = new Map();
40
+ this.initializeBuiltinTemplates();
41
+ }
42
+ async applyTemplate(prompt, template, options) {
43
+ const startTime = Date.now();
44
+ try {
45
+ // Validate inputs
46
+ if (!prompt || prompt.trim().length === 0) {
47
+ return (0, result_1.Err)(new errors_1.GeminiAPIError('Empty prompt provided', 'Please provide a non-empty prompt for template application'));
48
+ }
49
+ // Apply feature flags from options
50
+ const effectiveFlags = { ...this.featureFlags, ...options?.featureFlags };
51
+ // Validate template
52
+ const validation = this.validateTemplate(template);
53
+ if (!validation.valid) {
54
+ return (0, result_1.Err)(new errors_1.GeminiAPIError(`Template validation failed: ${validation.errors.join(', ')}`, 'Please check the template structure and syntax'));
55
+ }
56
+ // Apply template transformation based on feature flags
57
+ let structuredPrompt = prompt;
58
+ // Apply features based on flags (CONFIG3 granular control)
59
+ const appliedFeatures = [];
60
+ if (effectiveFlags.hyperSpecific && this.shouldApplyFeature(template, 'hyper-specific')) {
61
+ structuredPrompt = this.applyHyperSpecific(structuredPrompt, template);
62
+ appliedFeatures.push('hyper-specific');
63
+ }
64
+ if (effectiveFlags.characterConsistency &&
65
+ this.shouldApplyFeature(template, 'character-consistency')) {
66
+ structuredPrompt = this.applyCharacterConsistency(structuredPrompt, template);
67
+ appliedFeatures.push('character-consistency');
68
+ }
69
+ if (effectiveFlags.contextIntent && this.shouldApplyFeature(template, 'context-intent')) {
70
+ structuredPrompt = this.applyContextIntent(structuredPrompt, template);
71
+ appliedFeatures.push('context-intent');
72
+ }
73
+ if (effectiveFlags.semanticNegatives &&
74
+ this.shouldApplyFeature(template, 'semantic-negatives')) {
75
+ structuredPrompt = this.applySemanticNegatives(structuredPrompt, template);
76
+ appliedFeatures.push('semantic-negatives');
77
+ }
78
+ if (effectiveFlags.cameraControl && this.shouldApplyFeature(template, 'camera-control')) {
79
+ structuredPrompt = this.applyCameraControl(structuredPrompt, template);
80
+ appliedFeatures.push('camera-control');
81
+ }
82
+ if (effectiveFlags.aspectRatio && this.shouldApplyFeature(template, 'aspect-ratio')) {
83
+ structuredPrompt = this.applyAspectRatio(structuredPrompt, template);
84
+ appliedFeatures.push('aspect-ratio');
85
+ }
86
+ const processingTime = Math.max(Date.now() - startTime, 1); // Ensure minimum 1ms
87
+ const result = {
88
+ originalPrompt: prompt,
89
+ structuredPrompt,
90
+ appliedTemplate: template,
91
+ processingMeta: {
92
+ processingTime,
93
+ appliedFeatures,
94
+ featureFlags: effectiveFlags,
95
+ templateId: template.id,
96
+ timestamp: new Date(),
97
+ },
98
+ };
99
+ return (0, result_1.Ok)(result);
100
+ }
101
+ catch (error) {
102
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
103
+ return (0, result_1.Err)(new errors_1.GeminiAPIError(`Template application failed: ${errorMessage}`, 'Check template configuration and try again'));
104
+ }
105
+ }
106
+ parseTemplate(templateString) {
107
+ try {
108
+ // Enhanced validation with detailed error messages
109
+ const validationResult = this.validateTemplateString(templateString);
110
+ if (!validationResult.isValid) {
111
+ return (0, result_1.Err)(new errors_1.GeminiAPIError(`Template parsing failed: ${validationResult.errors.join(', ')}`, validationResult.suggestions.join('. ')));
112
+ }
113
+ // Enhanced POML XML-like parsing with error recovery
114
+ const parseResults = this.parseTemplateWithErrorRecovery(templateString);
115
+ if (!parseResults.success) {
116
+ return (0, result_1.Err)(new errors_1.GeminiAPIError(`Template parsing failed: ${parseResults.errors.join(', ')}`, 'Check POML syntax and structure. Ensure all tags are properly closed and attributes are correctly formatted.'));
117
+ }
118
+ if (!parseResults.template) {
119
+ return (0, result_1.Err)(new errors_1.GeminiAPIError('Template parsing failed: No template returned', 'Check POML syntax and structure'));
120
+ }
121
+ return (0, result_1.Ok)(parseResults.template);
122
+ }
123
+ catch (error) {
124
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
125
+ return (0, result_1.Err)(new errors_1.GeminiAPIError(`Template parsing failed with unexpected error: ${errorMessage}`, 'Check POML syntax and structure. Ensure the template follows Microsoft POML specification.'));
126
+ }
127
+ }
128
+ validateTemplate(template) {
129
+ const errors = [];
130
+ const warnings = [];
131
+ // Validate required fields
132
+ if (!template.id || template.id.trim().length === 0) {
133
+ errors.push('Template ID is required');
134
+ }
135
+ if (!template.name || template.name.trim().length === 0) {
136
+ errors.push('Template name is required');
137
+ }
138
+ // Validate structure
139
+ if (!template.structure) {
140
+ errors.push('Template structure is required');
141
+ }
142
+ // Validate features
143
+ if (!template.features || template.features.length === 0) {
144
+ warnings.push('Template has no features defined');
145
+ }
146
+ // Check feature dependencies
147
+ for (const feature of template.features || []) {
148
+ if (feature.dependencies) {
149
+ for (const dep of feature.dependencies) {
150
+ const depExists = template.features.some((f) => f.name === dep);
151
+ if (!depExists) {
152
+ errors.push(`Feature '${feature.name}' depends on missing feature '${dep}'`);
153
+ }
154
+ }
155
+ }
156
+ }
157
+ return {
158
+ valid: errors.length === 0,
159
+ errors,
160
+ warnings,
161
+ };
162
+ }
163
+ getAvailableTemplates() {
164
+ return Array.from(this.templates.values());
165
+ }
166
+ configureFeatureFlags(flags) {
167
+ try {
168
+ this.featureFlags = { ...this.featureFlags, ...flags };
169
+ return true;
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ }
175
+ getFeatureFlags() {
176
+ return { ...this.featureFlags };
177
+ }
178
+ // Private helper methods
179
+ initializeBuiltinTemplates() {
180
+ // Basic image generation template
181
+ const basicImageTemplate = {
182
+ id: 'basic-image-generation',
183
+ name: 'Basic Image Generation Template',
184
+ structure: {
185
+ role: 'Professional image generation assistant',
186
+ task: 'Generate detailed image based on user requirements',
187
+ context: '{originalPrompt}',
188
+ constraints: {
189
+ quality: 'High resolution, professional quality',
190
+ style: 'Consistent with project aesthetic',
191
+ technical: ['aspect-ratio-aware', 'camera-controlled'],
192
+ conditions: {
193
+ enableStyleGuide: true,
194
+ maintainConsistency: true,
195
+ },
196
+ },
197
+ },
198
+ features: [
199
+ {
200
+ name: 'hyper-specific',
201
+ enabled: true,
202
+ priority: 1,
203
+ category: 'basic',
204
+ },
205
+ {
206
+ name: 'character-consistency',
207
+ enabled: true,
208
+ priority: 2,
209
+ category: 'advanced',
210
+ },
211
+ {
212
+ name: 'context-intent',
213
+ enabled: true,
214
+ priority: 3,
215
+ category: 'advanced',
216
+ },
217
+ {
218
+ name: 'semantic-negatives',
219
+ enabled: true,
220
+ priority: 4,
221
+ category: 'advanced',
222
+ },
223
+ {
224
+ name: 'camera-control',
225
+ enabled: true,
226
+ priority: 5,
227
+ category: 'complete',
228
+ },
229
+ {
230
+ name: 'aspect-ratio',
231
+ enabled: true,
232
+ priority: 6,
233
+ category: 'complete',
234
+ },
235
+ ],
236
+ metadata: {
237
+ version: '1.0.0',
238
+ author: 'POMLTemplateEngine',
239
+ description: 'Basic template for image generation with POML features',
240
+ tags: ['image-generation', 'basic', 'poml'],
241
+ created: new Date(),
242
+ lastModified: new Date(),
243
+ },
244
+ };
245
+ this.templates.set(basicImageTemplate.id, basicImageTemplate);
246
+ }
247
+ shouldApplyFeature(template, featureName) {
248
+ const feature = template.features.find((f) => f.name === featureName);
249
+ return feature?.enabled ?? true;
250
+ }
251
+ applyHyperSpecific(prompt, template) {
252
+ // Enhanced hyper-specific transformation optimized for various prompt structures
253
+ let enhanced = prompt;
254
+ // Analyze prompt structure to determine enhancement approach
255
+ const promptType = this.analyzePromptStructure(prompt);
256
+ switch (promptType) {
257
+ case 'character-focused':
258
+ enhanced = this.enhanceCharacterPrompt(prompt, template);
259
+ break;
260
+ case 'scene-focused':
261
+ enhanced = this.enhanceScenePrompt(prompt, template);
262
+ break;
263
+ case 'object-focused':
264
+ enhanced = this.enhanceObjectPrompt(prompt, template);
265
+ break;
266
+ default:
267
+ enhanced = this.enhanceGenericPrompt(prompt, template);
268
+ }
269
+ // Add quality constraints if available
270
+ if (template.structure.constraints?.quality) {
271
+ enhanced = `${enhanced}, ${template.structure.constraints.quality}`;
272
+ }
273
+ return `Enhanced with hyper-specific details: ${enhanced}`;
274
+ }
275
+ applyCharacterConsistency(prompt, _template) {
276
+ const hasCharacter = this.detectCharacterReferences(prompt);
277
+ if (!hasCharacter) {
278
+ return prompt;
279
+ }
280
+ const consistencyFeatures = [
281
+ 'detailed facial features',
282
+ 'consistent clothing style',
283
+ 'maintained body proportions',
284
+ 'recognizable character traits',
285
+ ];
286
+ const selectedFeatures = this.selectRelevantFeatures(prompt, consistencyFeatures);
287
+ return `${prompt} with ${selectedFeatures.join(', ')} for consistency maintenance`;
288
+ }
289
+ applyContextIntent(prompt, template) {
290
+ const role = template.structure.role || 'professional image generation assistant';
291
+ const task = template.structure.task || 'create visually compelling content';
292
+ // Analyze prompt to determine appropriate context level
293
+ const contextLevel = this.determineContextLevel(prompt);
294
+ if (contextLevel === 'detailed') {
295
+ return `Context: ${role} performing ${task} with specific focus on ${this.extractKeyElements(prompt)}. Intent: ${prompt}`;
296
+ }
297
+ return `Context: ${role} performing ${task}. Intent: ${prompt}`;
298
+ }
299
+ applySemanticNegatives(prompt, _template) {
300
+ // Enhanced semantic negatives conversion with context awareness
301
+ const negativePatterns = [
302
+ { pattern: /no cars?/gi, replacement: 'quiet empty street' },
303
+ { pattern: /no people/gi, replacement: 'solitary peaceful scene' },
304
+ { pattern: /not visible/gi, replacement: 'hidden from view' },
305
+ { pattern: /don't (show|include)/gi, replacement: 'exclude' },
306
+ { pattern: /without/gi, replacement: 'featuring absence of' },
307
+ { pattern: /avoid/gi, replacement: 'specifically omit' },
308
+ ];
309
+ let enhanced = prompt;
310
+ for (const { pattern, replacement } of negativePatterns) {
311
+ enhanced = enhanced.replace(pattern, replacement);
312
+ }
313
+ return enhanced;
314
+ }
315
+ applyCameraControl(prompt, _template) {
316
+ const promptType = this.analyzePromptStructure(prompt);
317
+ // Select appropriate camera settings based on prompt type
318
+ const cameraSettings = this.selectCameraSettings(promptType, prompt);
319
+ return `${prompt} captured with professional camera control, ${cameraSettings.join(', ')}`;
320
+ }
321
+ applyAspectRatio(prompt, _template) {
322
+ const suggestedRatio = this.suggestOptimalAspectRatio(prompt);
323
+ return `${prompt} with optimal aspect ratio composition (${suggestedRatio})`;
324
+ }
325
+ // Optimization helper methods for various prompt structures
326
+ analyzePromptStructure(prompt) {
327
+ const lowerPrompt = prompt.toLowerCase();
328
+ if (this.detectCharacterReferences(prompt)) {
329
+ return 'character-focused';
330
+ }
331
+ if (lowerPrompt.includes('landscape') ||
332
+ lowerPrompt.includes('scene') ||
333
+ lowerPrompt.includes('environment')) {
334
+ return 'scene-focused';
335
+ }
336
+ if (lowerPrompt.includes('logo') ||
337
+ lowerPrompt.includes('icon') ||
338
+ lowerPrompt.includes('product')) {
339
+ return 'object-focused';
340
+ }
341
+ return 'generic';
342
+ }
343
+ detectCharacterReferences(prompt) {
344
+ const characterKeywords = [
345
+ 'character',
346
+ 'person',
347
+ 'people',
348
+ 'man',
349
+ 'woman',
350
+ 'child',
351
+ 'warrior',
352
+ 'hero',
353
+ 'villain',
354
+ 'face',
355
+ 'portrait',
356
+ 'human',
357
+ ];
358
+ const lowerPrompt = prompt.toLowerCase();
359
+ return characterKeywords.some((keyword) => lowerPrompt.includes(keyword));
360
+ }
361
+ enhanceCharacterPrompt(prompt, _template) {
362
+ const enhancements = [
363
+ 'detailed facial features',
364
+ 'expressive eyes',
365
+ 'defined bone structure',
366
+ 'realistic skin texture',
367
+ ];
368
+ return `${prompt} featuring ${enhancements.slice(0, 2).join(' and ')}`;
369
+ }
370
+ enhanceScenePrompt(prompt, _template) {
371
+ const enhancements = [
372
+ 'atmospheric lighting',
373
+ 'detailed environmental textures',
374
+ 'depth of field composition',
375
+ 'natural color gradients',
376
+ ];
377
+ return `${prompt} with ${enhancements.slice(0, 2).join(' and ')}`;
378
+ }
379
+ enhanceObjectPrompt(prompt, _template) {
380
+ const enhancements = [
381
+ 'crisp edge definition',
382
+ 'professional product lighting',
383
+ 'clean background composition',
384
+ 'high contrast clarity',
385
+ ];
386
+ return `${prompt} featuring ${enhancements.slice(0, 2).join(' and ')}`;
387
+ }
388
+ enhanceGenericPrompt(prompt, _template) {
389
+ return `${prompt} with enhanced detail and professional composition`;
390
+ }
391
+ selectRelevantFeatures(_prompt, features) {
392
+ // Select 2-3 most relevant features based on prompt content
393
+ return features.slice(0, Math.min(3, features.length));
394
+ }
395
+ determineContextLevel(prompt) {
396
+ return prompt.length > 50 ? 'detailed' : 'basic';
397
+ }
398
+ extractKeyElements(prompt) {
399
+ // Extract main subject/object from prompt for context
400
+ const words = prompt.split(' ').filter((word) => word.length > 3);
401
+ return words.slice(0, 3).join(', ');
402
+ }
403
+ selectCameraSettings(promptType, _prompt) {
404
+ const baseSettings = ['professional composition'];
405
+ switch (promptType) {
406
+ case 'character-focused':
407
+ return [...baseSettings, '85mm portrait lens', 'shallow depth of field'];
408
+ case 'scene-focused':
409
+ return [...baseSettings, 'wide-angle perspective', 'balanced exposure'];
410
+ case 'object-focused':
411
+ return [...baseSettings, 'macro lens clarity', 'controlled lighting'];
412
+ default:
413
+ return [...baseSettings, '50mm standard lens'];
414
+ }
415
+ }
416
+ suggestOptimalAspectRatio(prompt) {
417
+ const promptType = this.analyzePromptStructure(prompt);
418
+ switch (promptType) {
419
+ case 'character-focused':
420
+ return '3:4 portrait';
421
+ case 'scene-focused':
422
+ return '16:9 landscape';
423
+ case 'object-focused':
424
+ return '1:1 square';
425
+ default:
426
+ return '4:3 standard';
427
+ }
428
+ }
429
+ // POML parsing helper methods - extracted for reusability
430
+ extractAttribute(xml, attributeName) {
431
+ const regex = new RegExp(`${attributeName}=['"]([^'"]*?)['"]`, 'i');
432
+ const match = xml.match(regex);
433
+ return match ? match[1] : undefined;
434
+ }
435
+ parseStructure(xml) {
436
+ return {
437
+ role: this.extractTagContent(xml, 'role') || undefined,
438
+ task: this.extractTagContent(xml, 'task') || undefined,
439
+ context: this.extractTagContent(xml, 'context') || undefined,
440
+ constraints: this.parseConstraints(xml) || undefined,
441
+ };
442
+ }
443
+ parseFeatures(xml) {
444
+ // Enhanced feature parsing from XML with fallback to default features
445
+ const defaultFeatures = [
446
+ {
447
+ name: 'hyper-specific',
448
+ enabled: true,
449
+ priority: 1,
450
+ category: 'basic',
451
+ },
452
+ {
453
+ name: 'character-consistency',
454
+ enabled: true,
455
+ priority: 2,
456
+ category: 'advanced',
457
+ },
458
+ {
459
+ name: 'context-intent',
460
+ enabled: true,
461
+ priority: 3,
462
+ category: 'advanced',
463
+ },
464
+ ];
465
+ // Try to parse features from XML, fallback to defaults
466
+ const featuresMatch = xml.match(/<features[^>]*>(.*?)<\/features>/is);
467
+ if (!featuresMatch) {
468
+ return defaultFeatures;
469
+ }
470
+ // Parse individual feature elements
471
+ const featuresContent = featuresMatch[1];
472
+ if (!featuresContent) {
473
+ return defaultFeatures;
474
+ }
475
+ const featureMatches = featuresContent.match(/<feature[^>]*\/>/g);
476
+ if (!featureMatches) {
477
+ return defaultFeatures;
478
+ }
479
+ const parsedFeatures = [];
480
+ for (const featureXml of featureMatches) {
481
+ const name = this.extractAttribute(featureXml, 'name');
482
+ const enabled = this.extractAttribute(featureXml, 'enabled') !== 'false';
483
+ const category = this.extractAttribute(featureXml, 'category') || 'basic';
484
+ const priority = Number.parseInt(this.extractAttribute(featureXml, 'priority') || '1', 10);
485
+ if (name) {
486
+ parsedFeatures.push({
487
+ name,
488
+ enabled,
489
+ category,
490
+ priority,
491
+ });
492
+ }
493
+ }
494
+ return parsedFeatures.length > 0 ? parsedFeatures : defaultFeatures;
495
+ }
496
+ parseMetadata(xml) {
497
+ return {
498
+ version: this.extractAttribute(xml, 'version') || '1.0.0',
499
+ author: this.extractAttribute(xml, 'author') || 'Unknown',
500
+ description: this.extractTagContent(xml, 'description') || 'No description',
501
+ tags: this.parseTagsFromDescription(xml),
502
+ created: new Date(),
503
+ lastModified: new Date(),
504
+ };
505
+ }
506
+ parseConstraints(xml) {
507
+ const constraintsMatch = xml.match(/<constraints[^>]*>(.*?)<\/constraints>/is);
508
+ if (!constraintsMatch) {
509
+ return {
510
+ quality: undefined,
511
+ style: undefined,
512
+ technical: undefined,
513
+ conditions: undefined,
514
+ };
515
+ }
516
+ const constraintsContent = constraintsMatch[1];
517
+ if (!constraintsContent) {
518
+ return {
519
+ quality: undefined,
520
+ style: undefined,
521
+ technical: undefined,
522
+ conditions: undefined,
523
+ };
524
+ }
525
+ const qualityContent = this.extractTagContent(constraintsContent, 'quality');
526
+ const styleContent = this.extractTagContent(constraintsContent, 'style');
527
+ const technicalContent = this.parseTechnicalConstraints(constraintsContent);
528
+ const conditionsContent = this.parseConditions(constraintsContent);
529
+ return {
530
+ quality: qualityContent || undefined,
531
+ style: styleContent || undefined,
532
+ technical: technicalContent || undefined,
533
+ conditions: conditionsContent || undefined,
534
+ };
535
+ }
536
+ parseTagsFromDescription(xml) {
537
+ const description = this.extractTagContent(xml, 'description');
538
+ if (!description)
539
+ return [];
540
+ // Extract tags from description or use default tags
541
+ return ['poml', 'template', 'image-generation'];
542
+ }
543
+ parseTechnicalConstraints(constraintsXml) {
544
+ const technicalMatches = constraintsXml.match(/<technical[^>]*>(.*?)<\/technical>/is);
545
+ if (!technicalMatches)
546
+ return [];
547
+ // Parse comma-separated technical constraints
548
+ const content = technicalMatches[1];
549
+ if (!content)
550
+ return [];
551
+ return content
552
+ .split(',')
553
+ .map((constraint) => constraint.trim())
554
+ .filter((constraint) => constraint.length > 0);
555
+ }
556
+ parseConditions(constraintsXml) {
557
+ const conditions = {};
558
+ // Look for condition attributes in constraints
559
+ const conditionMatches = constraintsXml.match(/condition=['"]([^'"]+)['"].*?(['"]true['"]|['"]false['"])?/g);
560
+ if (!conditionMatches)
561
+ return conditions;
562
+ for (const match of conditionMatches) {
563
+ const nameMatch = match.match(/condition=['"]([^'"]+)['"]/);
564
+ const valueMatch = match.match(/(['"]true['"]|['"]false['"])/);
565
+ if (nameMatch?.[1]) {
566
+ const name = nameMatch[1];
567
+ const value = valueMatch?.[1] ? valueMatch[1].includes('true') : true;
568
+ conditions[name] = value;
569
+ }
570
+ }
571
+ return conditions;
572
+ }
573
+ extractTagContent(xml, tagName) {
574
+ const regex = new RegExp(`<${tagName}[^>]*>(.*?)<\/${tagName}>`, 'is');
575
+ const match = xml.match(regex);
576
+ return match?.[1] ? match[1].trim() : undefined;
577
+ }
578
+ // Enhanced error handling methods for malformed POML syntax
579
+ validateTemplateString(templateString) {
580
+ const errors = [];
581
+ const suggestions = [];
582
+ // Basic validation checks
583
+ if (!templateString || templateString.trim().length === 0) {
584
+ errors.push('Empty template string provided');
585
+ suggestions.push('Provide a valid POML template string');
586
+ return { isValid: false, errors, suggestions };
587
+ }
588
+ // Check for template tags
589
+ if (!templateString.includes('<template')) {
590
+ errors.push('Missing opening <template> tag');
591
+ suggestions.push('Add <template> opening tag with id and name attributes');
592
+ }
593
+ if (!templateString.includes('</template>')) {
594
+ errors.push('Missing closing </template> tag');
595
+ suggestions.push('Add </template> closing tag at the end of the template');
596
+ }
597
+ // Check for malformed XML structure
598
+ if (this.hasUnmatchedTags(templateString)) {
599
+ errors.push('Unmatched XML tags detected');
600
+ suggestions.push('Ensure all opening tags have corresponding closing tags');
601
+ }
602
+ // Check for invalid characters
603
+ if (this.hasInvalidXMLCharacters(templateString)) {
604
+ errors.push('Invalid XML characters detected');
605
+ suggestions.push('Remove or escape invalid XML characters (< > & without proper escaping)');
606
+ }
607
+ // Check for proper attribute syntax
608
+ if (this.hasMalformedAttributes(templateString)) {
609
+ errors.push('Malformed attribute syntax detected');
610
+ suggestions.push('Ensure attributes are properly quoted: attribute="value"');
611
+ }
612
+ return {
613
+ isValid: errors.length === 0,
614
+ errors,
615
+ suggestions,
616
+ };
617
+ }
618
+ parseTemplateWithErrorRecovery(templateString) {
619
+ const errors = [];
620
+ try {
621
+ // Attempt to parse with error recovery
622
+ const template = {
623
+ id: this.extractAttributeWithFallback(templateString, 'id', `template-${Date.now()}`),
624
+ name: this.extractAttributeWithFallback(templateString, 'name', 'Untitled Template'),
625
+ structure: this.parseStructureWithErrorRecovery(templateString, errors),
626
+ features: this.parseFeaturesWithErrorRecovery(templateString, errors),
627
+ metadata: this.parseMetadataWithErrorRecovery(templateString, errors),
628
+ };
629
+ return {
630
+ success: true,
631
+ template,
632
+ errors,
633
+ };
634
+ }
635
+ catch (error) {
636
+ const errorMessage = error instanceof Error ? error.message : 'Unknown parsing error';
637
+ errors.push(errorMessage);
638
+ return {
639
+ success: false,
640
+ errors,
641
+ };
642
+ }
643
+ }
644
+ hasUnmatchedTags(xml) {
645
+ // Simplified check - only flag obvious mismatches
646
+ const openTagCount = (xml.match(/<[^/][^>]*[^/]>/g) || []).length;
647
+ const closeTagCount = (xml.match(/<\/[^>]*>/g) || []).length;
648
+ const selfClosingCount = (xml.match(/<[^>]*\/>/g) || []).length;
649
+ // Allow reasonable tolerance for complex templates
650
+ const netOpenTags = openTagCount - selfClosingCount;
651
+ return Math.abs(netOpenTags - closeTagCount) > 2; // More tolerant
652
+ }
653
+ hasInvalidXMLCharacters(xml) {
654
+ // Check for common invalid XML character patterns
655
+ const invalidPatterns = [
656
+ /&(?!amp;|lt;|gt;|quot;|apos;)/, // Unescaped ampersands
657
+ /<(?![^>]*>)/, // Lone less-than signs
658
+ />>+/, // Multiple consecutive greater-than signs
659
+ ];
660
+ return invalidPatterns.some((pattern) => pattern.test(xml));
661
+ }
662
+ hasMalformedAttributes(xml) {
663
+ // Simplified check - only flag obviously malformed attributes
664
+ const obviouslyMalformedPatterns = [
665
+ /=\s*$/, // Attributes ending with = at end of string
666
+ /=\s*>/, // Attributes ending with = before closing tag
667
+ ];
668
+ return obviouslyMalformedPatterns.some((pattern) => pattern.test(xml));
669
+ }
670
+ extractAttributeWithFallback(xml, attributeName, fallback) {
671
+ try {
672
+ return this.extractAttribute(xml, attributeName) || fallback;
673
+ }
674
+ catch {
675
+ return fallback;
676
+ }
677
+ }
678
+ parseStructureWithErrorRecovery(xml, errors) {
679
+ try {
680
+ return this.parseStructure(xml);
681
+ }
682
+ catch (error) {
683
+ const errorMessage = error instanceof Error ? error.message : 'Structure parsing error';
684
+ errors.push(`Structure parsing warning: ${errorMessage}`);
685
+ // Return minimal structure as fallback
686
+ return {
687
+ role: 'assistant',
688
+ task: 'generate content',
689
+ context: '{originalPrompt}',
690
+ constraints: {
691
+ quality: undefined,
692
+ style: undefined,
693
+ technical: undefined,
694
+ conditions: undefined,
695
+ },
696
+ };
697
+ }
698
+ }
699
+ parseFeaturesWithErrorRecovery(xml, errors) {
700
+ try {
701
+ return this.parseFeatures(xml);
702
+ }
703
+ catch (error) {
704
+ const errorMessage = error instanceof Error ? error.message : 'Features parsing error';
705
+ errors.push(`Features parsing warning: ${errorMessage}`);
706
+ // Return basic features as fallback
707
+ return [
708
+ {
709
+ name: 'hyper-specific',
710
+ enabled: true,
711
+ priority: 1,
712
+ category: 'basic',
713
+ },
714
+ ];
715
+ }
716
+ }
717
+ parseMetadataWithErrorRecovery(xml, errors) {
718
+ try {
719
+ return this.parseMetadata(xml);
720
+ }
721
+ catch (error) {
722
+ const errorMessage = error instanceof Error ? error.message : 'Metadata parsing error';
723
+ errors.push(`Metadata parsing warning: ${errorMessage}`);
724
+ // Return minimal metadata as fallback
725
+ return {
726
+ version: '1.0.0',
727
+ author: 'Unknown',
728
+ description: 'Template with parsing errors - using fallback metadata',
729
+ tags: ['poml', 'error-recovery'],
730
+ created: new Date(),
731
+ lastModified: new Date(),
732
+ };
733
+ }
734
+ }
735
+ }
736
+ exports.POMLTemplateEngineImpl = POMLTemplateEngineImpl;
737
+ //# sourceMappingURL=pomlTemplateEngine.js.map