@tpitre/story-ui 3.7.0 → 3.8.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.
- package/dist/mcp-server/routes/generateStory.d.ts.map +1 -1
- package/dist/mcp-server/routes/generateStory.js +36 -0
- package/dist/story-generator/runtimeValidator.d.ts +64 -0
- package/dist/story-generator/runtimeValidator.d.ts.map +1 -0
- package/dist/story-generator/runtimeValidator.js +356 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateStory.d.ts","sourceRoot":"","sources":["../../../mcp-server/routes/generateStory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"generateStory.d.ts","sourceRoot":"","sources":["../../../mcp-server/routes/generateStory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAgc5C,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,2DAkgBxE"}
|
|
@@ -18,6 +18,7 @@ import { chatCompletion, generateTitle as llmGenerateTitle, isProviderConfigured
|
|
|
18
18
|
import { processImageInputs } from '../../story-generator/imageProcessor.js';
|
|
19
19
|
import { buildVisionAwarePrompt } from '../../story-generator/visionPrompts.js';
|
|
20
20
|
import { aggregateValidationErrors, shouldContinueRetrying, buildSelfHealingPrompt, hasNoErrors, getTotalErrorCount, createEmptyErrors, formatErrorsForLog, selectBestAttempt, } from '../../story-generator/selfHealingLoop.js';
|
|
21
|
+
import { validateStoryRuntime, formatRuntimeErrorForHealing, isRuntimeValidationEnabled, } from '../../story-generator/runtimeValidator.js';
|
|
21
22
|
// Build suggestion using the user's actual discovered components (design-system agnostic)
|
|
22
23
|
function buildComponentSuggestion(components) {
|
|
23
24
|
if (!components?.length) {
|
|
@@ -730,6 +731,33 @@ export async function generateStoryFromPrompt(req, res) {
|
|
|
730
731
|
// Save to history
|
|
731
732
|
historyManager.addVersion(finalFileName, prompt, fixedFileContents, parentVersionId);
|
|
732
733
|
logger.log(`Story ${isActualUpdate ? 'updated' : 'written'} to:`, outPath);
|
|
734
|
+
// --- RUNTIME VALIDATION: Check if story loads in Storybook ---
|
|
735
|
+
// This catches errors that static validation cannot detect, like CSF module loader errors
|
|
736
|
+
let runtimeValidationResult = { success: true, storyExists: true };
|
|
737
|
+
let hasRuntimeError = false;
|
|
738
|
+
if (isRuntimeValidationEnabled()) {
|
|
739
|
+
logger.info('🔍 Running runtime validation...');
|
|
740
|
+
try {
|
|
741
|
+
runtimeValidationResult = await validateStoryRuntime(fixedFileContents, aiTitle, config.storyPrefix);
|
|
742
|
+
if (!runtimeValidationResult.success) {
|
|
743
|
+
hasRuntimeError = true;
|
|
744
|
+
hasValidationWarnings = true;
|
|
745
|
+
logger.error(`❌ Runtime validation failed: ${runtimeValidationResult.renderError}`);
|
|
746
|
+
logger.error(` Error type: ${runtimeValidationResult.errorType}`);
|
|
747
|
+
// Format the error for potential future self-healing
|
|
748
|
+
const runtimeErrorMessage = formatRuntimeErrorForHealing(runtimeValidationResult);
|
|
749
|
+
logger.debug('Runtime error details:', runtimeErrorMessage);
|
|
750
|
+
}
|
|
751
|
+
else {
|
|
752
|
+
logger.info('✅ Runtime validation passed - story loads correctly in Storybook');
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
catch (runtimeErr) {
|
|
756
|
+
// Don't fail the request if runtime validation itself fails (e.g., Storybook not running)
|
|
757
|
+
logger.warn(`⚠️ Runtime validation could not complete: ${runtimeErr.message}`);
|
|
758
|
+
logger.warn(' Story was saved but runtime status is unknown');
|
|
759
|
+
}
|
|
760
|
+
}
|
|
733
761
|
// Track URL redirect if this is an update and the title changed
|
|
734
762
|
if (isActualUpdate && oldTitle && oldStoryUrl) {
|
|
735
763
|
const newTitleMatch = fixedFileContents.match(/title:\s*["']([^"']+)['"]/);
|
|
@@ -759,6 +787,14 @@ export async function generateStoryFromPrompt(req, res) {
|
|
|
759
787
|
warnings: [],
|
|
760
788
|
selfHealingUsed,
|
|
761
789
|
attempts
|
|
790
|
+
},
|
|
791
|
+
runtimeValidation: {
|
|
792
|
+
enabled: isRuntimeValidationEnabled(),
|
|
793
|
+
success: runtimeValidationResult.success,
|
|
794
|
+
storyExists: runtimeValidationResult.storyExists,
|
|
795
|
+
error: runtimeValidationResult.renderError,
|
|
796
|
+
errorType: runtimeValidationResult.errorType,
|
|
797
|
+
details: runtimeValidationResult.details
|
|
762
798
|
}
|
|
763
799
|
});
|
|
764
800
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Validator for Story UI
|
|
3
|
+
*
|
|
4
|
+
* Validates that generated stories actually load and render in Storybook
|
|
5
|
+
* by making HTTP requests to the running Storybook instance after HMR processes
|
|
6
|
+
* the new story file.
|
|
7
|
+
*
|
|
8
|
+
* This catches runtime errors that static validation cannot detect, such as:
|
|
9
|
+
* - "importers[path] is not a function" - Storybook CSF loader errors
|
|
10
|
+
* - Module resolution failures
|
|
11
|
+
* - Runtime component errors
|
|
12
|
+
*/
|
|
13
|
+
export interface RuntimeValidationResult {
|
|
14
|
+
success: boolean;
|
|
15
|
+
storyExists: boolean;
|
|
16
|
+
renderError?: string;
|
|
17
|
+
errorType?: 'module_error' | 'render_error' | 'not_found' | 'timeout' | 'connection_error';
|
|
18
|
+
details?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface RuntimeValidatorConfig {
|
|
21
|
+
storybookUrl: string;
|
|
22
|
+
hmrWaitMs?: number;
|
|
23
|
+
fetchTimeoutMs?: number;
|
|
24
|
+
retryAttempts?: number;
|
|
25
|
+
retryDelayMs?: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Get the Storybook URL based on environment configuration
|
|
29
|
+
*/
|
|
30
|
+
export declare function getStorybookUrl(): string | null;
|
|
31
|
+
/**
|
|
32
|
+
* Check if runtime validation is enabled
|
|
33
|
+
*/
|
|
34
|
+
export declare function isRuntimeValidationEnabled(): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Convert a story title to the Storybook story ID prefix format
|
|
37
|
+
* e.g., "Simple Card" with prefix "Generated/" -> "generated-simple-card"
|
|
38
|
+
* Note: This returns the prefix only, without the story export name
|
|
39
|
+
*/
|
|
40
|
+
export declare function titleToStoryIdPrefix(title: string, storyPrefix?: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* Extract the actual title from generated story content
|
|
43
|
+
* Looks for: title: 'Generated/Something' or title: "Generated/Something"
|
|
44
|
+
*/
|
|
45
|
+
export declare function extractTitleFromStory(storyContent: string): string | null;
|
|
46
|
+
/**
|
|
47
|
+
* Convert a full story title (like "Generated/Button Click Counter") to story ID prefix
|
|
48
|
+
*/
|
|
49
|
+
export declare function fullTitleToStoryIdPrefix(fullTitle: string): string;
|
|
50
|
+
/**
|
|
51
|
+
* Validate that a story loads and renders correctly in Storybook
|
|
52
|
+
*
|
|
53
|
+
* @param storyContent - The generated story content (used to extract the actual title)
|
|
54
|
+
* @param fallbackTitle - Fallback title if extraction fails (e.g., "Simple Card")
|
|
55
|
+
* @param storyPrefix - The story prefix from config (e.g., "Generated/")
|
|
56
|
+
* @param customConfig - Runtime validator configuration
|
|
57
|
+
* @returns Validation result with success status and any errors
|
|
58
|
+
*/
|
|
59
|
+
export declare function validateStoryRuntime(storyContent: string, fallbackTitle: string, storyPrefix?: string, customConfig?: Partial<RuntimeValidatorConfig>): Promise<RuntimeValidationResult>;
|
|
60
|
+
/**
|
|
61
|
+
* Format runtime validation errors for the self-healing prompt
|
|
62
|
+
*/
|
|
63
|
+
export declare function formatRuntimeErrorForHealing(result: RuntimeValidationResult): string;
|
|
64
|
+
//# sourceMappingURL=runtimeValidator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtimeValidator.d.ts","sourceRoot":"","sources":["../../story-generator/runtimeValidator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,cAAc,GAAG,cAAc,GAAG,WAAW,GAAG,SAAS,GAAG,kBAAkB,CAAC;IAC3F,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAeD;;GAEG;AACH,wBAAgB,eAAe,IAAI,MAAM,GAAG,IAAI,CAmB/C;AAED;;GAEG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAcpD;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,GAAE,MAAqB,GAAG,MAAM,CAQ9F;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAOzE;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAKlE;AAiJD;;;;;;;;GAQG;AACH,wBAAsB,oBAAoB,CACxC,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,WAAW,GAAE,MAAqB,EAClC,YAAY,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,GAC7C,OAAO,CAAC,uBAAuB,CAAC,CA6FlC;AAED;;GAEG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,uBAAuB,GAAG,MAAM,CAoDpF"}
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Validator for Story UI
|
|
3
|
+
*
|
|
4
|
+
* Validates that generated stories actually load and render in Storybook
|
|
5
|
+
* by making HTTP requests to the running Storybook instance after HMR processes
|
|
6
|
+
* the new story file.
|
|
7
|
+
*
|
|
8
|
+
* This catches runtime errors that static validation cannot detect, such as:
|
|
9
|
+
* - "importers[path] is not a function" - Storybook CSF loader errors
|
|
10
|
+
* - Module resolution failures
|
|
11
|
+
* - Runtime component errors
|
|
12
|
+
*/
|
|
13
|
+
import { logger } from './logger.js';
|
|
14
|
+
// Known Storybook runtime error patterns
|
|
15
|
+
const RUNTIME_ERROR_PATTERNS = [
|
|
16
|
+
{ pattern: /importers\[.*?\] is not a function/i, type: 'module_error', description: 'CSF module loader error' },
|
|
17
|
+
{ pattern: /Cannot read propert.*of undefined/i, type: 'render_error', description: 'Component render error' },
|
|
18
|
+
{ pattern: /is not defined/i, type: 'render_error', description: 'Undefined variable error' },
|
|
19
|
+
{ pattern: /Module not found/i, type: 'module_error', description: 'Module resolution error' },
|
|
20
|
+
{ pattern: /Failed to resolve import/i, type: 'module_error', description: 'Import resolution error' },
|
|
21
|
+
{ pattern: /SyntaxError/i, type: 'module_error', description: 'Runtime syntax error' },
|
|
22
|
+
{ pattern: /Unexpected token/i, type: 'module_error', description: 'Parse error' },
|
|
23
|
+
{ pattern: /ReferenceError/i, type: 'render_error', description: 'Reference error' },
|
|
24
|
+
{ pattern: /TypeError/i, type: 'render_error', description: 'Type error' },
|
|
25
|
+
];
|
|
26
|
+
/**
|
|
27
|
+
* Get the Storybook URL based on environment configuration
|
|
28
|
+
*/
|
|
29
|
+
export function getStorybookUrl() {
|
|
30
|
+
// Priority 1: Explicit storybookUrl in environment
|
|
31
|
+
if (process.env.STORYBOOK_URL) {
|
|
32
|
+
return process.env.STORYBOOK_URL;
|
|
33
|
+
}
|
|
34
|
+
// Priority 2: Proxy mode - use internal Storybook port
|
|
35
|
+
if (process.env.STORYBOOK_PROXY_ENABLED === 'true') {
|
|
36
|
+
const proxyPort = process.env.STORYBOOK_PROXY_PORT || '6006';
|
|
37
|
+
return `http://localhost:${proxyPort}`;
|
|
38
|
+
}
|
|
39
|
+
// Priority 3: Explicit Storybook port
|
|
40
|
+
if (process.env.STORYBOOK_PORT) {
|
|
41
|
+
return `http://localhost:${process.env.STORYBOOK_PORT}`;
|
|
42
|
+
}
|
|
43
|
+
// Priority 4: Default local Storybook
|
|
44
|
+
return 'http://localhost:6006';
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Check if runtime validation is enabled
|
|
48
|
+
*/
|
|
49
|
+
export function isRuntimeValidationEnabled() {
|
|
50
|
+
// Enabled by default if we can determine a Storybook URL
|
|
51
|
+
// Can be explicitly disabled with STORYBOOK_RUNTIME_VALIDATION=false
|
|
52
|
+
if (process.env.STORYBOOK_RUNTIME_VALIDATION === 'false') {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
// In proxy mode, always enable since we know Storybook is accessible
|
|
56
|
+
if (process.env.STORYBOOK_PROXY_ENABLED === 'true') {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
// Otherwise, enable if explicitly set to true
|
|
60
|
+
return process.env.STORYBOOK_RUNTIME_VALIDATION === 'true';
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Convert a story title to the Storybook story ID prefix format
|
|
64
|
+
* e.g., "Simple Card" with prefix "Generated/" -> "generated-simple-card"
|
|
65
|
+
* Note: This returns the prefix only, without the story export name
|
|
66
|
+
*/
|
|
67
|
+
export function titleToStoryIdPrefix(title, storyPrefix = 'Generated/') {
|
|
68
|
+
// Remove prefix and convert to kebab case
|
|
69
|
+
const fullTitle = storyPrefix + title;
|
|
70
|
+
const kebabTitle = fullTitle
|
|
71
|
+
.toLowerCase()
|
|
72
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
73
|
+
.replace(/^-|-$/g, '');
|
|
74
|
+
return kebabTitle;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Extract the actual title from generated story content
|
|
78
|
+
* Looks for: title: 'Generated/Something' or title: "Generated/Something"
|
|
79
|
+
*/
|
|
80
|
+
export function extractTitleFromStory(storyContent) {
|
|
81
|
+
const titleMatch = storyContent.match(/title:\s*['"]([^'"]+)['"]/);
|
|
82
|
+
if (titleMatch) {
|
|
83
|
+
// Return the full title (including prefix like "Generated/")
|
|
84
|
+
return titleMatch[1];
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Convert a full story title (like "Generated/Button Click Counter") to story ID prefix
|
|
90
|
+
*/
|
|
91
|
+
export function fullTitleToStoryIdPrefix(fullTitle) {
|
|
92
|
+
return fullTitle
|
|
93
|
+
.toLowerCase()
|
|
94
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
95
|
+
.replace(/^-|-$/g, '');
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Sleep utility
|
|
99
|
+
*/
|
|
100
|
+
function sleep(ms) {
|
|
101
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Fetch with timeout
|
|
105
|
+
*/
|
|
106
|
+
async function fetchWithTimeout(url, timeoutMs) {
|
|
107
|
+
const controller = new AbortController();
|
|
108
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
109
|
+
try {
|
|
110
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
111
|
+
clearTimeout(timeoutId);
|
|
112
|
+
return response;
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
clearTimeout(timeoutId);
|
|
116
|
+
if (error.name === 'AbortError') {
|
|
117
|
+
throw new Error(`Request timed out after ${timeoutMs}ms`);
|
|
118
|
+
}
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Check if stories exist in Storybook's index that match the given title prefix
|
|
124
|
+
* Returns the first matching story ID for iframe validation
|
|
125
|
+
*/
|
|
126
|
+
async function checkStoryInIndex(storyIdPrefix, storybookUrl, config) {
|
|
127
|
+
const indexUrl = `${storybookUrl}/index.json`;
|
|
128
|
+
const timeout = config.fetchTimeoutMs || 5000;
|
|
129
|
+
try {
|
|
130
|
+
const response = await fetchWithTimeout(indexUrl, timeout);
|
|
131
|
+
if (!response.ok) {
|
|
132
|
+
return { exists: false, error: `Index returned ${response.status}` };
|
|
133
|
+
}
|
|
134
|
+
const index = await response.json();
|
|
135
|
+
// Storybook 7+ uses 'entries', older versions use 'stories'
|
|
136
|
+
const stories = index.entries || index.stories || {};
|
|
137
|
+
// Find story IDs that match our prefix (not docs entries)
|
|
138
|
+
const matchingIds = Object.keys(stories).filter(id => {
|
|
139
|
+
// Skip docs entries - we want actual story entries
|
|
140
|
+
if (id.endsWith('--docs'))
|
|
141
|
+
return false;
|
|
142
|
+
// Check if the ID starts with our prefix
|
|
143
|
+
return id.startsWith(storyIdPrefix + '--');
|
|
144
|
+
});
|
|
145
|
+
if (matchingIds.length > 0) {
|
|
146
|
+
return { exists: true, matchingStoryId: matchingIds[0] };
|
|
147
|
+
}
|
|
148
|
+
return { exists: false };
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
return { exists: false, error: error.message };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Check the story iframe for runtime errors
|
|
156
|
+
*/
|
|
157
|
+
async function checkStoryIframe(storyId, storybookUrl, config) {
|
|
158
|
+
const iframeUrl = `${storybookUrl}/iframe.html?id=${storyId}&viewMode=story`;
|
|
159
|
+
const timeout = config.fetchTimeoutMs || 5000;
|
|
160
|
+
try {
|
|
161
|
+
const response = await fetchWithTimeout(iframeUrl, timeout);
|
|
162
|
+
if (!response.ok) {
|
|
163
|
+
return {
|
|
164
|
+
success: false,
|
|
165
|
+
error: `Story iframe returned ${response.status}`,
|
|
166
|
+
errorType: 'not_found'
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const html = await response.text();
|
|
170
|
+
// Check for known error patterns in the HTML response
|
|
171
|
+
for (const { pattern, type, description } of RUNTIME_ERROR_PATTERNS) {
|
|
172
|
+
if (pattern.test(html)) {
|
|
173
|
+
// Extract the actual error message if possible
|
|
174
|
+
const match = html.match(/<pre[^>]*>([\s\S]*?)<\/pre>/i) ||
|
|
175
|
+
html.match(/Error:?\s*([^\n<]+)/i);
|
|
176
|
+
const errorDetail = match ? match[1].trim().substring(0, 200) : description;
|
|
177
|
+
return {
|
|
178
|
+
success: false,
|
|
179
|
+
error: errorDetail,
|
|
180
|
+
errorType: type
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// Check for Storybook error boundary markers
|
|
185
|
+
// Note: We need to check for VISIBLE errors, not just the error display template
|
|
186
|
+
// The 'sb-show-errordisplay' class is added to body when an error is actually shown
|
|
187
|
+
// IMPORTANT: Must use regex to check for class attribute, not just includes()
|
|
188
|
+
// because ':not(.sb-show-errordisplay)' exists in CSS selectors
|
|
189
|
+
const hasVisibleError = /class="[^"]*sb-show-errordisplay[^"]*"/i.test(html);
|
|
190
|
+
// Check for actual error content in the error display elements (non-empty)
|
|
191
|
+
const hasErrorContent = /<h1[^>]*id="error-message"[^>]*>[^<]+<\/h1>/i.test(html) ||
|
|
192
|
+
/<code[^>]*id="error-stack"[^>]*>[^<]+<\/code>/i.test(html);
|
|
193
|
+
// Check for specific error text (not in CSS context)
|
|
194
|
+
const hasDocsError = />\s*DocsRenderer error/i.test(html);
|
|
195
|
+
const hasStoryError = /class="[^"]*story-error[^"]*"/i.test(html);
|
|
196
|
+
if (hasVisibleError || hasErrorContent || hasDocsError || hasStoryError) {
|
|
197
|
+
// Try to extract the actual error message
|
|
198
|
+
const errorMsgMatch = html.match(/<h1[^>]*id="error-message"[^>]*>([^<]+)<\/h1>/i);
|
|
199
|
+
const errorDetail = errorMsgMatch ? errorMsgMatch[1].trim() : 'Storybook error boundary triggered';
|
|
200
|
+
return {
|
|
201
|
+
success: false,
|
|
202
|
+
error: errorDetail,
|
|
203
|
+
errorType: 'render_error'
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
return { success: true };
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (error.message.includes('timed out')) {
|
|
210
|
+
return { success: false, error: error.message, errorType: 'timeout' };
|
|
211
|
+
}
|
|
212
|
+
return { success: false, error: error.message, errorType: 'connection_error' };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Validate that a story loads and renders correctly in Storybook
|
|
217
|
+
*
|
|
218
|
+
* @param storyContent - The generated story content (used to extract the actual title)
|
|
219
|
+
* @param fallbackTitle - Fallback title if extraction fails (e.g., "Simple Card")
|
|
220
|
+
* @param storyPrefix - The story prefix from config (e.g., "Generated/")
|
|
221
|
+
* @param customConfig - Runtime validator configuration
|
|
222
|
+
* @returns Validation result with success status and any errors
|
|
223
|
+
*/
|
|
224
|
+
export async function validateStoryRuntime(storyContent, fallbackTitle, storyPrefix = 'Generated/', customConfig) {
|
|
225
|
+
// Check if runtime validation is enabled
|
|
226
|
+
if (!isRuntimeValidationEnabled()) {
|
|
227
|
+
logger.debug('Runtime validation disabled, skipping');
|
|
228
|
+
return { success: true, storyExists: true };
|
|
229
|
+
}
|
|
230
|
+
const storybookUrl = getStorybookUrl();
|
|
231
|
+
if (!storybookUrl) {
|
|
232
|
+
logger.warn('Could not determine Storybook URL for runtime validation');
|
|
233
|
+
return { success: true, storyExists: true, details: 'Storybook URL not configured' };
|
|
234
|
+
}
|
|
235
|
+
const config = {
|
|
236
|
+
storybookUrl,
|
|
237
|
+
hmrWaitMs: 3000,
|
|
238
|
+
fetchTimeoutMs: 5000,
|
|
239
|
+
retryAttempts: 3,
|
|
240
|
+
retryDelayMs: 1000,
|
|
241
|
+
...customConfig
|
|
242
|
+
};
|
|
243
|
+
// Extract the actual title from the story content, or use fallback
|
|
244
|
+
const extractedTitle = extractTitleFromStory(storyContent);
|
|
245
|
+
let storyIdPrefix;
|
|
246
|
+
if (extractedTitle) {
|
|
247
|
+
// Use the exact title from the generated code
|
|
248
|
+
storyIdPrefix = fullTitleToStoryIdPrefix(extractedTitle);
|
|
249
|
+
logger.debug(`Extracted title from story: "${extractedTitle}" -> prefix: "${storyIdPrefix}"`);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
// Fall back to constructing from the provided title
|
|
253
|
+
storyIdPrefix = titleToStoryIdPrefix(fallbackTitle, storyPrefix);
|
|
254
|
+
logger.debug(`Using fallback title: "${fallbackTitle}" -> prefix: "${storyIdPrefix}"`);
|
|
255
|
+
}
|
|
256
|
+
logger.info(`Runtime validation: checking stories with prefix "${storyIdPrefix}" at ${storybookUrl}`);
|
|
257
|
+
// Wait for HMR to process the new file
|
|
258
|
+
logger.debug(`Waiting ${config.hmrWaitMs}ms for HMR to process...`);
|
|
259
|
+
await sleep(config.hmrWaitMs);
|
|
260
|
+
// Step 1: Check if story appears in the index (with retries for HMR timing)
|
|
261
|
+
let matchingStoryId;
|
|
262
|
+
let lastIndexError;
|
|
263
|
+
for (let attempt = 1; attempt <= config.retryAttempts; attempt++) {
|
|
264
|
+
const indexResult = await checkStoryInIndex(storyIdPrefix, storybookUrl, config);
|
|
265
|
+
if (indexResult.exists && indexResult.matchingStoryId) {
|
|
266
|
+
matchingStoryId = indexResult.matchingStoryId;
|
|
267
|
+
logger.debug(`Found matching story: "${matchingStoryId}"`);
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
lastIndexError = indexResult.error;
|
|
271
|
+
if (attempt < config.retryAttempts) {
|
|
272
|
+
logger.debug(`Story not found in index (attempt ${attempt}/${config.retryAttempts}), waiting...`);
|
|
273
|
+
await sleep(config.retryDelayMs);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (!matchingStoryId) {
|
|
277
|
+
logger.warn(`Stories with prefix "${storyIdPrefix}" not found in Storybook index after ${config.retryAttempts} attempts`);
|
|
278
|
+
return {
|
|
279
|
+
success: false,
|
|
280
|
+
storyExists: false,
|
|
281
|
+
errorType: 'not_found',
|
|
282
|
+
renderError: lastIndexError || 'Story not found in Storybook index - HMR may not have processed the file',
|
|
283
|
+
details: `Story ID prefix: ${storyIdPrefix}`
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
// Step 2: Load the story iframe and check for runtime errors
|
|
287
|
+
const iframeResult = await checkStoryIframe(matchingStoryId, storybookUrl, config);
|
|
288
|
+
if (!iframeResult.success) {
|
|
289
|
+
logger.error(`Runtime error detected in story "${matchingStoryId}": ${iframeResult.error}`);
|
|
290
|
+
return {
|
|
291
|
+
success: false,
|
|
292
|
+
storyExists: true,
|
|
293
|
+
renderError: iframeResult.error,
|
|
294
|
+
errorType: iframeResult.errorType,
|
|
295
|
+
details: `Story ID: ${matchingStoryId}, URL: ${storybookUrl}/iframe.html?id=${matchingStoryId}`
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
logger.info(`Runtime validation passed for story "${matchingStoryId}"`);
|
|
299
|
+
return {
|
|
300
|
+
success: true,
|
|
301
|
+
storyExists: true
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Format runtime validation errors for the self-healing prompt
|
|
306
|
+
*/
|
|
307
|
+
export function formatRuntimeErrorForHealing(result) {
|
|
308
|
+
if (result.success)
|
|
309
|
+
return '';
|
|
310
|
+
const parts = [];
|
|
311
|
+
parts.push(`RUNTIME ERROR: The generated story failed to load in Storybook.`);
|
|
312
|
+
if (result.renderError) {
|
|
313
|
+
parts.push(`Error: ${result.renderError}`);
|
|
314
|
+
}
|
|
315
|
+
if (result.errorType === 'module_error') {
|
|
316
|
+
parts.push(`This is a module/import error. Common causes:`);
|
|
317
|
+
parts.push(`- Invalid CSF (Component Story Format) structure`);
|
|
318
|
+
parts.push(`- Missing or malformed default export (meta)`);
|
|
319
|
+
parts.push(`- Story exports that conflict with Storybook internals`);
|
|
320
|
+
parts.push(`- Invalid import statements`);
|
|
321
|
+
parts.push(`\nEnsure the story follows this exact structure:`);
|
|
322
|
+
parts.push(`\`\`\`tsx`);
|
|
323
|
+
parts.push(`import type { Meta, StoryObj } from '@storybook/react';`);
|
|
324
|
+
parts.push(`import { Component } from '@design-system/core';`);
|
|
325
|
+
parts.push(``);
|
|
326
|
+
parts.push(`const meta: Meta<typeof Component> = {`);
|
|
327
|
+
parts.push(` title: 'Generated/Story Title',`);
|
|
328
|
+
parts.push(` component: Component,`);
|
|
329
|
+
parts.push(`};`);
|
|
330
|
+
parts.push(``);
|
|
331
|
+
parts.push(`export default meta;`);
|
|
332
|
+
parts.push(`type Story = StoryObj<typeof meta>;`);
|
|
333
|
+
parts.push(``);
|
|
334
|
+
parts.push(`export const Default: Story = {`);
|
|
335
|
+
parts.push(` render: () => <Component />,`);
|
|
336
|
+
parts.push(`};`);
|
|
337
|
+
parts.push(`\`\`\``);
|
|
338
|
+
}
|
|
339
|
+
else if (result.errorType === 'render_error') {
|
|
340
|
+
parts.push(`This is a component render error. Common causes:`);
|
|
341
|
+
parts.push(`- Using undefined variables or components`);
|
|
342
|
+
parts.push(`- Invalid props passed to components`);
|
|
343
|
+
parts.push(`- Missing required props`);
|
|
344
|
+
parts.push(`- Incorrect component composition`);
|
|
345
|
+
}
|
|
346
|
+
else if (result.errorType === 'not_found') {
|
|
347
|
+
parts.push(`The story was not found in Storybook's index. This usually means:`);
|
|
348
|
+
parts.push(`- The file has syntax errors that prevent Storybook from parsing it`);
|
|
349
|
+
parts.push(`- The story title/path doesn't match expected format`);
|
|
350
|
+
parts.push(`- The default export is missing or invalid`);
|
|
351
|
+
}
|
|
352
|
+
if (result.details) {
|
|
353
|
+
parts.push(`\nDetails: ${result.details}`);
|
|
354
|
+
}
|
|
355
|
+
return parts.join('\n');
|
|
356
|
+
}
|