@fragments-sdk/cli 0.11.1 → 0.13.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/ai-client-I6MDWNYA.js +21 -0
- package/dist/bin.js +419 -410
- package/dist/bin.js.map +1 -1
- package/dist/{chunk-HRFUSSZI.js → chunk-3SOAPJDX.js} +2 -2
- package/dist/{chunk-D5PYOXEI.js → chunk-4K7EAQ5L.js} +148 -13
- package/dist/{chunk-D5PYOXEI.js.map → chunk-4K7EAQ5L.js.map} +1 -1
- package/dist/chunk-DXX6HADE.js +443 -0
- package/dist/chunk-DXX6HADE.js.map +1 -0
- package/dist/chunk-EYXVAMEX.js +626 -0
- package/dist/chunk-EYXVAMEX.js.map +1 -0
- package/dist/{chunk-ZM4ZQZWZ.js → chunk-FO6EBJWP.js} +39 -37
- package/dist/chunk-FO6EBJWP.js.map +1 -0
- package/dist/{chunk-OQO55NKV.js → chunk-QM7SVOGF.js} +120 -12
- package/dist/chunk-QM7SVOGF.js.map +1 -0
- package/dist/{chunk-5G3VZH43.js → chunk-RF3C6LGA.js} +281 -351
- package/dist/chunk-RF3C6LGA.js.map +1 -0
- package/dist/{chunk-WXSR2II7.js → chunk-SM674YAS.js} +58 -6
- package/dist/chunk-SM674YAS.js.map +1 -0
- package/dist/chunk-SXTKFDCR.js +104 -0
- package/dist/chunk-SXTKFDCR.js.map +1 -0
- package/dist/{chunk-PW7QTQA6.js → chunk-UV5JQV3R.js} +2 -2
- package/dist/core/index.js +13 -1
- package/dist/{discovery-NEOY4MPN.js → discovery-VSGC76JN.js} +3 -3
- package/dist/{generate-FBHSXR3D.js → generate-QZXOXYFW.js} +4 -4
- package/dist/index.js +7 -6
- package/dist/index.js.map +1 -1
- package/dist/init-XK6PRUE5.js +636 -0
- package/dist/init-XK6PRUE5.js.map +1 -0
- package/dist/mcp-bin.js +2 -2
- package/dist/{scan-CJF2DOQW.js → scan-CHQHXWVD.js} +6 -6
- package/dist/scan-generate-U3RFVDTX.js +1115 -0
- package/dist/scan-generate-U3RFVDTX.js.map +1 -0
- package/dist/{service-TQYWY65E.js → service-MMEKG4MZ.js} +3 -3
- package/dist/{snapshot-SV2JOFZH.js → snapshot-53TUR3HW.js} +2 -2
- package/dist/{static-viewer-NUBFPKWH.js → static-viewer-KKCR4KXR.js} +3 -3
- package/dist/static-viewer-KKCR4KXR.js.map +1 -0
- package/dist/{test-Z5LVO724.js → test-5UCKXYSC.js} +4 -4
- package/dist/{tokens-CE46OTMD.js → tokens-L46MK5AW.js} +5 -5
- package/dist/{viewer-DLLJIMCK.js → viewer-M2EQQSGE.js} +14 -14
- package/dist/viewer-M2EQQSGE.js.map +1 -0
- package/package.json +11 -9
- package/src/ai-client.ts +156 -0
- package/src/bin.ts +99 -2
- package/src/build.ts +95 -33
- package/src/commands/__tests__/drift-sync.test.ts +252 -0
- package/src/commands/__tests__/scan-generate.test.ts +497 -45
- package/src/commands/enhance.ts +11 -35
- package/src/commands/govern.ts +122 -0
- package/src/commands/init.ts +288 -260
- package/src/commands/scan-generate.ts +740 -139
- package/src/commands/scan.ts +37 -32
- package/src/commands/setup.ts +143 -52
- package/src/commands/sync.ts +357 -0
- package/src/commands/validate.ts +43 -1
- package/src/core/component-extractor.test.ts +282 -0
- package/src/core/component-extractor.ts +1030 -0
- package/src/core/discovery.ts +93 -7
- package/src/service/enhance/props-extractor.ts +235 -13
- package/src/validators.ts +236 -0
- package/src/viewer/vite-plugin.ts +1 -1
- package/dist/chunk-5G3VZH43.js.map +0 -1
- package/dist/chunk-OQO55NKV.js.map +0 -1
- package/dist/chunk-WXSR2II7.js.map +0 -1
- package/dist/chunk-ZM4ZQZWZ.js.map +0 -1
- package/dist/init-UFGK5TCN.js +0 -867
- package/dist/init-UFGK5TCN.js.map +0 -1
- package/dist/scan-generate-SJAN5MVI.js +0 -691
- package/dist/scan-generate-SJAN5MVI.js.map +0 -1
- package/dist/viewer-DLLJIMCK.js.map +0 -1
- package/src/ai.ts +0 -266
- package/src/commands/init-framework.ts +0 -414
- package/src/mcp/bin.ts +0 -36
- package/src/migrate/bin.ts +0 -114
- package/src/theme/index.ts +0 -77
- package/src/viewer/bin.ts +0 -86
- package/src/viewer/cli/health.ts +0 -256
- package/src/viewer/cli/index.ts +0 -33
- package/src/viewer/cli/scan.ts +0 -124
- package/src/viewer/cli/utils.ts +0 -174
- /package/dist/{discovery-NEOY4MPN.js.map → ai-client-I6MDWNYA.js.map} +0 -0
- /package/dist/{chunk-HRFUSSZI.js.map → chunk-3SOAPJDX.js.map} +0 -0
- /package/dist/{chunk-PW7QTQA6.js.map → chunk-UV5JQV3R.js.map} +0 -0
- /package/dist/{scan-CJF2DOQW.js.map → discovery-VSGC76JN.js.map} +0 -0
- /package/dist/{generate-FBHSXR3D.js.map → generate-QZXOXYFW.js.map} +0 -0
- /package/dist/{service-TQYWY65E.js.map → scan-CHQHXWVD.js.map} +0 -0
- /package/dist/{static-viewer-NUBFPKWH.js.map → service-MMEKG4MZ.js.map} +0 -0
- /package/dist/{snapshot-SV2JOFZH.js.map → snapshot-53TUR3HW.js.map} +0 -0
- /package/dist/{test-Z5LVO724.js.map → test-5UCKXYSC.js.map} +0 -0
- /package/dist/{tokens-CE46OTMD.js.map → tokens-L46MK5AW.js.map} +0 -0
|
@@ -0,0 +1,1115 @@
|
|
|
1
|
+
import { createRequire as __banner_createRequire } from 'module'; const require = __banner_createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
createComponentExtractor
|
|
4
|
+
} from "./chunk-EYXVAMEX.js";
|
|
5
|
+
import "./chunk-3SOAPJDX.js";
|
|
6
|
+
import {
|
|
7
|
+
discoverAllComponents
|
|
8
|
+
} from "./chunk-SM674YAS.js";
|
|
9
|
+
import "./chunk-D2CDBRNU.js";
|
|
10
|
+
import {
|
|
11
|
+
BRAND
|
|
12
|
+
} from "./chunk-QM7SVOGF.js";
|
|
13
|
+
import "./chunk-Z7EY4VHE.js";
|
|
14
|
+
|
|
15
|
+
// src/commands/scan-generate.ts
|
|
16
|
+
import { readFile, writeFile, access, mkdir } from "fs/promises";
|
|
17
|
+
import { resolve, basename, dirname, relative, join } from "path";
|
|
18
|
+
import * as ts from "typescript";
|
|
19
|
+
import pc from "picocolors";
|
|
20
|
+
async function scanGenerate(options) {
|
|
21
|
+
const scanPath = resolve(options.scanPath);
|
|
22
|
+
const generated = [];
|
|
23
|
+
const skipped = [];
|
|
24
|
+
const errors = [];
|
|
25
|
+
console.log(pc.cyan(`
|
|
26
|
+
${BRAND.name} Scan \u2192 Generate
|
|
27
|
+
`));
|
|
28
|
+
console.log(pc.dim(`Scanning: ${scanPath}
|
|
29
|
+
`));
|
|
30
|
+
console.log(pc.dim("Phase 1: Discovering components..."));
|
|
31
|
+
const defaultScanPatterns = [
|
|
32
|
+
"**/*.tsx",
|
|
33
|
+
"**/*.ts"
|
|
34
|
+
];
|
|
35
|
+
const components = await discoverAllComponents(scanPath, {
|
|
36
|
+
patterns: options.patterns || defaultScanPatterns,
|
|
37
|
+
exclude: [
|
|
38
|
+
"**/*.test.*",
|
|
39
|
+
"**/*.spec.*",
|
|
40
|
+
"**/*.stories.*",
|
|
41
|
+
"**/*.fragment.*",
|
|
42
|
+
"**/*.d.ts",
|
|
43
|
+
"**/__tests__/**",
|
|
44
|
+
"**/__mocks__/**",
|
|
45
|
+
"**/node_modules/**",
|
|
46
|
+
"**/dist/**"
|
|
47
|
+
]
|
|
48
|
+
});
|
|
49
|
+
if (components.length === 0) {
|
|
50
|
+
console.log(
|
|
51
|
+
pc.yellow("No components found. Check the path or file patterns.")
|
|
52
|
+
);
|
|
53
|
+
return {
|
|
54
|
+
success: false,
|
|
55
|
+
generated: [],
|
|
56
|
+
skipped: [],
|
|
57
|
+
errors: [{ name: "*", error: "No components found" }],
|
|
58
|
+
averageConfidence: 0
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
console.log(pc.green(` Found ${components.length} components`));
|
|
62
|
+
console.log(pc.dim("\nPhase 2: Extracting component metadata..."));
|
|
63
|
+
const extractor = createComponentExtractor(options.tsconfig);
|
|
64
|
+
const componentDataList = [];
|
|
65
|
+
const extractionStart = performance.now();
|
|
66
|
+
for (const comp of components) {
|
|
67
|
+
let meta = null;
|
|
68
|
+
try {
|
|
69
|
+
meta = extractor.extract(comp.sourcePath, comp.name);
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
if (meta && !meta.composition) {
|
|
73
|
+
try {
|
|
74
|
+
const subComponents = await detectCompoundComponents(comp.sourcePath, comp.name);
|
|
75
|
+
if (subComponents.length > 0) {
|
|
76
|
+
meta = {
|
|
77
|
+
...meta,
|
|
78
|
+
composition: {
|
|
79
|
+
pattern: "compound",
|
|
80
|
+
parts: subComponents.map((name) => ({ name, props: {} })),
|
|
81
|
+
required: []
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
} catch {
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
let storyVariants = [];
|
|
89
|
+
if (!options.skipStorybook && comp.storyPath) {
|
|
90
|
+
try {
|
|
91
|
+
storyVariants = await extractStoryVariantsFromFile(comp.storyPath);
|
|
92
|
+
} catch {
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
componentDataList.push({
|
|
96
|
+
component: comp,
|
|
97
|
+
meta,
|
|
98
|
+
storyVariants
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
extractor.dispose();
|
|
102
|
+
const extractionMs = (performance.now() - extractionStart).toFixed(0);
|
|
103
|
+
const propsExtracted = componentDataList.filter(
|
|
104
|
+
(d) => d.meta && Object.keys(d.meta.props).length > 0
|
|
105
|
+
).length;
|
|
106
|
+
const compoundCount = componentDataList.filter(
|
|
107
|
+
(d) => d.meta?.composition !== null
|
|
108
|
+
).length;
|
|
109
|
+
console.log(pc.green(` Extracted props for ${propsExtracted} components (${extractionMs}ms)`));
|
|
110
|
+
if (compoundCount > 0) {
|
|
111
|
+
console.log(pc.green(` Detected ${compoundCount} compound component(s) with sub-component props`));
|
|
112
|
+
}
|
|
113
|
+
let enrichments = /* @__PURE__ */ new Map();
|
|
114
|
+
let enrichmentCost;
|
|
115
|
+
if (options.enrich) {
|
|
116
|
+
console.log(pc.dim("\nPhase 3: Enriching with AI..."));
|
|
117
|
+
const enrichResult = await enrichComponents(componentDataList, {
|
|
118
|
+
dryRun: options.dryRun,
|
|
119
|
+
provider: options.provider,
|
|
120
|
+
apiKey: options.apiKey,
|
|
121
|
+
model: options.model
|
|
122
|
+
});
|
|
123
|
+
enrichments = enrichResult.enrichments;
|
|
124
|
+
if (enrichResult.model && enrichResult.totalInputTokens > 0) {
|
|
125
|
+
const { calculateCost } = await import("./ai-client-I6MDWNYA.js");
|
|
126
|
+
enrichmentCost = calculateCost(
|
|
127
|
+
enrichResult.model,
|
|
128
|
+
enrichResult.totalInputTokens,
|
|
129
|
+
enrichResult.totalOutputTokens
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
console.log(pc.dim(`
|
|
134
|
+
Phase ${options.enrich ? "4" : "3"}: Generating fragment files...`));
|
|
135
|
+
for (const data of componentDataList) {
|
|
136
|
+
const comp = data.component;
|
|
137
|
+
const componentDir = dirname(comp.sourcePath);
|
|
138
|
+
const componentBaseName = basename(comp.sourcePath, ".tsx");
|
|
139
|
+
let fragmentDir;
|
|
140
|
+
if (options.outputDir) {
|
|
141
|
+
fragmentDir = resolve(options.outputDir, comp.name);
|
|
142
|
+
await mkdir(fragmentDir, { recursive: true });
|
|
143
|
+
} else {
|
|
144
|
+
fragmentDir = componentDir;
|
|
145
|
+
}
|
|
146
|
+
const fragmentPath = join(
|
|
147
|
+
fragmentDir,
|
|
148
|
+
`${componentBaseName}${BRAND.fileExtension}`
|
|
149
|
+
);
|
|
150
|
+
let fragmentExists = false;
|
|
151
|
+
try {
|
|
152
|
+
await access(fragmentPath);
|
|
153
|
+
fragmentExists = true;
|
|
154
|
+
} catch {
|
|
155
|
+
}
|
|
156
|
+
if (fragmentExists && !options.force) {
|
|
157
|
+
skipped.push({ name: comp.name, reason: "Fragment already exists" });
|
|
158
|
+
if (options.verbose) {
|
|
159
|
+
console.log(pc.dim(` Skipping ${comp.name} (fragment exists)`));
|
|
160
|
+
}
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const enrichment = enrichments.get(comp.name);
|
|
165
|
+
const confidence = calculateFieldConfidence(data, enrichment);
|
|
166
|
+
const importPath = computeImportPath(
|
|
167
|
+
fragmentDir,
|
|
168
|
+
comp.sourcePath,
|
|
169
|
+
componentBaseName
|
|
170
|
+
);
|
|
171
|
+
const content = generateFragmentWithTodos(
|
|
172
|
+
comp.name,
|
|
173
|
+
importPath,
|
|
174
|
+
data,
|
|
175
|
+
confidence,
|
|
176
|
+
enrichment
|
|
177
|
+
);
|
|
178
|
+
await writeFile(fragmentPath, content, "utf-8");
|
|
179
|
+
const relPath = relative(process.cwd(), fragmentPath);
|
|
180
|
+
generated.push({
|
|
181
|
+
name: comp.name,
|
|
182
|
+
path: relPath,
|
|
183
|
+
confidence: confidence.score,
|
|
184
|
+
todoCount: confidence.todoFields.length,
|
|
185
|
+
enriched: !!enrichment
|
|
186
|
+
});
|
|
187
|
+
const confColor = confidence.score >= 70 ? pc.green : confidence.score >= 40 ? pc.yellow : pc.red;
|
|
188
|
+
console.log(
|
|
189
|
+
pc.green(` \u2713 ${comp.name}`) + pc.dim(` (confidence: `) + confColor(`${confidence.score}`) + pc.dim(`, TODOs: ${confidence.todoFields.length})`)
|
|
190
|
+
);
|
|
191
|
+
} catch (e) {
|
|
192
|
+
errors.push({
|
|
193
|
+
name: comp.name,
|
|
194
|
+
error: e instanceof Error ? e.message : String(e)
|
|
195
|
+
});
|
|
196
|
+
console.log(pc.red(` \u2717 ${comp.name}: ${e instanceof Error ? e.message : String(e)}`));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const avgConfidence = generated.length > 0 ? Math.round(
|
|
200
|
+
generated.reduce((sum, g) => sum + g.confidence, 0) / generated.length
|
|
201
|
+
) : 0;
|
|
202
|
+
console.log(pc.dim("\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
|
|
203
|
+
console.log(pc.green(`
|
|
204
|
+
\u2713 Generated ${generated.length} fragment file(s)`));
|
|
205
|
+
if (skipped.length > 0) {
|
|
206
|
+
console.log(
|
|
207
|
+
pc.dim(` Skipped ${skipped.length} (use --force to overwrite)`)
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
if (errors.length > 0) {
|
|
211
|
+
console.log(pc.yellow(` ${errors.length} error(s)`));
|
|
212
|
+
}
|
|
213
|
+
console.log(pc.dim(` Average confidence: ${avgConfidence}/100`));
|
|
214
|
+
if (options.enrich) {
|
|
215
|
+
const enrichedCount = generated.filter((g) => g.enriched).length;
|
|
216
|
+
console.log(pc.dim(` Enriched: ${enrichedCount}/${generated.length} components`));
|
|
217
|
+
if (enrichmentCost !== void 0 && enrichmentCost > 0) {
|
|
218
|
+
console.log(pc.dim(` Estimated cost: $${enrichmentCost.toFixed(4)}`));
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const totalTodos = generated.reduce((sum, g) => sum + g.todoCount, 0);
|
|
222
|
+
if (totalTodos > 0) {
|
|
223
|
+
console.log(
|
|
224
|
+
pc.dim(` Total TODOs: ${totalTodos}`) + pc.dim(` \u2014 search for "TODO:" in generated files`)
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
console.log();
|
|
228
|
+
return {
|
|
229
|
+
success: errors.length === 0,
|
|
230
|
+
generated,
|
|
231
|
+
skipped,
|
|
232
|
+
errors,
|
|
233
|
+
averageConfidence: avgConfidence,
|
|
234
|
+
enrichmentCost
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
async function extractComponentJSDoc(filePath, componentName) {
|
|
238
|
+
const content = await readFile(filePath, "utf-8");
|
|
239
|
+
return extractComponentJSDocFromSource(content, filePath, componentName);
|
|
240
|
+
}
|
|
241
|
+
function extractComponentJSDocFromSource(source, filePath, componentName) {
|
|
242
|
+
const sourceFile = ts.createSourceFile(
|
|
243
|
+
filePath,
|
|
244
|
+
source,
|
|
245
|
+
ts.ScriptTarget.ESNext,
|
|
246
|
+
true,
|
|
247
|
+
filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
|
|
248
|
+
);
|
|
249
|
+
const targetName = componentName || basename(filePath).replace(/\.(tsx?|jsx?)$/, "");
|
|
250
|
+
let componentDoc = null;
|
|
251
|
+
let propsInterfaceDoc = null;
|
|
252
|
+
for (const statement of sourceFile.statements) {
|
|
253
|
+
if (ts.isFunctionDeclaration(statement) && statement.name?.text === targetName && hasExportModifier(statement)) {
|
|
254
|
+
const doc = getLeadingJSDoc(statement, sourceFile);
|
|
255
|
+
if (doc) componentDoc = doc;
|
|
256
|
+
}
|
|
257
|
+
if (ts.isVariableStatement(statement) && hasExportModifier(statement)) {
|
|
258
|
+
for (const decl of statement.declarationList.declarations) {
|
|
259
|
+
if (ts.isIdentifier(decl.name) && decl.name.text === targetName) {
|
|
260
|
+
const doc = getLeadingJSDoc(statement, sourceFile);
|
|
261
|
+
if (doc) componentDoc = doc;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (ts.isFunctionDeclaration(statement) && hasDefaultExportModifier(statement)) {
|
|
266
|
+
const doc = getLeadingJSDoc(statement, sourceFile);
|
|
267
|
+
if (doc) componentDoc = doc;
|
|
268
|
+
}
|
|
269
|
+
if (ts.isInterfaceDeclaration(statement) && (statement.name.text === `${targetName}Props` || statement.name.text === `${targetName}Properties`)) {
|
|
270
|
+
const doc = getLeadingJSDoc(statement, sourceFile);
|
|
271
|
+
if (doc) propsInterfaceDoc = doc;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return componentDoc || propsInterfaceDoc;
|
|
275
|
+
}
|
|
276
|
+
function hasExportModifier(node) {
|
|
277
|
+
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
|
|
278
|
+
return modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;
|
|
279
|
+
}
|
|
280
|
+
function hasDefaultExportModifier(node) {
|
|
281
|
+
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0;
|
|
282
|
+
if (!modifiers) return false;
|
|
283
|
+
return modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) && modifiers.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword);
|
|
284
|
+
}
|
|
285
|
+
function getLeadingJSDoc(node, sourceFile) {
|
|
286
|
+
const fullText = sourceFile.getFullText();
|
|
287
|
+
const nodeStart = node.getFullStart();
|
|
288
|
+
const nodePos = node.getStart(sourceFile);
|
|
289
|
+
const leadingText = fullText.slice(nodeStart, nodePos);
|
|
290
|
+
const jsDocMatch = leadingText.match(/\/\*\*([\s\S]*?)\*\//);
|
|
291
|
+
if (!jsDocMatch) return null;
|
|
292
|
+
const lines = jsDocMatch[1].split("\n");
|
|
293
|
+
const descriptionLines = [];
|
|
294
|
+
for (const line of lines) {
|
|
295
|
+
const trimmed = line.replace(/^\s*\*?\s?/, "").trim();
|
|
296
|
+
if (trimmed.startsWith("@")) break;
|
|
297
|
+
if (trimmed) descriptionLines.push(trimmed);
|
|
298
|
+
}
|
|
299
|
+
return descriptionLines.length > 0 ? descriptionLines.join(" ") : null;
|
|
300
|
+
}
|
|
301
|
+
async function detectCompoundComponents(filePath, primaryComponentName) {
|
|
302
|
+
const content = await readFile(filePath, "utf-8");
|
|
303
|
+
return detectCompoundComponentsFromSource(content, filePath, primaryComponentName);
|
|
304
|
+
}
|
|
305
|
+
function detectCompoundComponentsFromSource(source, filePath, primaryComponentName) {
|
|
306
|
+
const sourceFile = ts.createSourceFile(
|
|
307
|
+
filePath,
|
|
308
|
+
source,
|
|
309
|
+
ts.ScriptTarget.ESNext,
|
|
310
|
+
true,
|
|
311
|
+
filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
|
|
312
|
+
);
|
|
313
|
+
const subComponents = [];
|
|
314
|
+
function visit(node) {
|
|
315
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Object" && node.expression.name.text === "assign" && node.arguments.length >= 2) {
|
|
316
|
+
const secondArg = node.arguments[1];
|
|
317
|
+
if (ts.isObjectLiteralExpression(secondArg)) {
|
|
318
|
+
for (const prop of secondArg.properties) {
|
|
319
|
+
if (ts.isShorthandPropertyAssignment(prop)) {
|
|
320
|
+
subComponents.push(prop.name.text);
|
|
321
|
+
} else if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
|
|
322
|
+
subComponents.push(prop.name.text);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
ts.forEachChild(node, visit);
|
|
328
|
+
}
|
|
329
|
+
ts.forEachChild(sourceFile, visit);
|
|
330
|
+
if (subComponents.length === 0 && primaryComponentName) {
|
|
331
|
+
const exportedNames = [];
|
|
332
|
+
for (const statement of sourceFile.statements) {
|
|
333
|
+
if (ts.isExportDeclaration(statement) && statement.exportClause) {
|
|
334
|
+
if (ts.isNamedExports(statement.exportClause)) {
|
|
335
|
+
for (const element of statement.exportClause.elements) {
|
|
336
|
+
exportedNames.push(element.name.text);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (ts.isFunctionDeclaration(statement) && statement.name) {
|
|
341
|
+
const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : void 0;
|
|
342
|
+
if (modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
343
|
+
exportedNames.push(statement.name.text);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (ts.isVariableStatement(statement)) {
|
|
347
|
+
const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : void 0;
|
|
348
|
+
if (modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
|
|
349
|
+
for (const decl of statement.declarationList.declarations) {
|
|
350
|
+
if (ts.isIdentifier(decl.name)) {
|
|
351
|
+
exportedNames.push(decl.name.text);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const prefix = primaryComponentName;
|
|
358
|
+
for (const name of exportedNames) {
|
|
359
|
+
if (name !== prefix && name.startsWith(prefix) && /^[A-Z]/.test(name.slice(prefix.length))) {
|
|
360
|
+
const subName = name.slice(prefix.length);
|
|
361
|
+
subComponents.push(subName);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return subComponents;
|
|
366
|
+
}
|
|
367
|
+
async function extractStoryVariantsFromFile(storyPath) {
|
|
368
|
+
const content = await readFile(storyPath, "utf-8");
|
|
369
|
+
const variants = [];
|
|
370
|
+
const exportMatches = content.matchAll(
|
|
371
|
+
/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/g
|
|
372
|
+
);
|
|
373
|
+
for (const match of exportMatches) {
|
|
374
|
+
const name = match[1];
|
|
375
|
+
if (name === "default" || name.endsWith("Args") || name.endsWith("Meta")) {
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const args = extractStoryArgs(content, name);
|
|
379
|
+
variants.push({ name, args });
|
|
380
|
+
}
|
|
381
|
+
return variants;
|
|
382
|
+
}
|
|
383
|
+
function extractStoryArgs(content, storyName) {
|
|
384
|
+
const storyPattern = new RegExp(
|
|
385
|
+
`export\\s+const\\s+${storyName}[^=]*=\\s*\\{([\\s\\S]*?)\\n\\};`
|
|
386
|
+
);
|
|
387
|
+
const storyMatch = content.match(storyPattern);
|
|
388
|
+
if (!storyMatch) return {};
|
|
389
|
+
const storyBody = storyMatch[1];
|
|
390
|
+
const argsStart = storyBody.indexOf("args:");
|
|
391
|
+
if (argsStart === -1) return {};
|
|
392
|
+
const braceStart = storyBody.indexOf("{", argsStart);
|
|
393
|
+
if (braceStart === -1) return {};
|
|
394
|
+
let depth = 0;
|
|
395
|
+
let braceEnd = -1;
|
|
396
|
+
for (let i = braceStart; i < storyBody.length; i++) {
|
|
397
|
+
if (storyBody[i] === "{") depth++;
|
|
398
|
+
else if (storyBody[i] === "}") {
|
|
399
|
+
depth--;
|
|
400
|
+
if (depth === 0) {
|
|
401
|
+
braceEnd = i;
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (braceEnd === -1) return {};
|
|
407
|
+
const argsBlock = storyBody.slice(braceStart + 1, braceEnd).trim();
|
|
408
|
+
return parseArgsBlock(argsBlock);
|
|
409
|
+
}
|
|
410
|
+
function parseArgsBlock(argsBlock) {
|
|
411
|
+
const args = {};
|
|
412
|
+
const pairPattern = /(\w+)\s*:\s*(?:['"]([^'"]*?)['"]|(true|false)|(\d+(?:\.\d+)?))/g;
|
|
413
|
+
let pairMatch;
|
|
414
|
+
while ((pairMatch = pairPattern.exec(argsBlock)) !== null) {
|
|
415
|
+
const key = pairMatch[1];
|
|
416
|
+
if (pairMatch[2] !== void 0) {
|
|
417
|
+
args[key] = pairMatch[2];
|
|
418
|
+
} else if (pairMatch[3] !== void 0) {
|
|
419
|
+
args[key] = pairMatch[3] === "true";
|
|
420
|
+
} else if (pairMatch[4] !== void 0) {
|
|
421
|
+
args[key] = Number(pairMatch[4]);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return args;
|
|
425
|
+
}
|
|
426
|
+
function buildEnrichmentSystemPrompt() {
|
|
427
|
+
return `You are a senior frontend architect and design system expert.
|
|
428
|
+
Given a component's metadata (name, description, props, composition), generate knowledge fields that help AI models use the component correctly.
|
|
429
|
+
|
|
430
|
+
Respond ONLY with a JSON object. No explanation, no markdown outside the JSON.
|
|
431
|
+
|
|
432
|
+
The JSON must have exactly these fields:
|
|
433
|
+
{
|
|
434
|
+
"when": ["..."], // 3-5 scenarios when this component should be used
|
|
435
|
+
"whenNot": ["..."], // 2-4 scenarios when NOT to use this component (suggest alternatives)
|
|
436
|
+
"guidelines": ["..."], // 2-3 usage guidelines or best practices
|
|
437
|
+
"a11yRules": ["..."], // 2-4 accessibility rules or requirements
|
|
438
|
+
"scenarioTags": ["..."], // 3-5 dot-notation scenario tags (e.g., "form.input.text", "layout.container.card")
|
|
439
|
+
"tags": ["..."] // 3-5 search keywords for component discovery
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
Rules:
|
|
443
|
+
- "when" items should describe concrete UI scenarios (e.g., "Displaying grouped content with a header, body, and footer")
|
|
444
|
+
- "whenNot" items should name a better alternative (e.g., "Simple text grouping without visual separation \u2014 use a div or Stack instead")
|
|
445
|
+
- "guidelines" should be actionable best practices
|
|
446
|
+
- "a11yRules" should reference WCAG or ARIA patterns where relevant
|
|
447
|
+
- "scenarioTags" use dot notation: category.subcategory.detail
|
|
448
|
+
- "tags" should be lowercase single words or short phrases for search
|
|
449
|
+
- Keep each item to 1 sentence. Be specific, not generic.`;
|
|
450
|
+
}
|
|
451
|
+
function buildEnrichmentUserPrompt(name, data) {
|
|
452
|
+
const props = data.meta?.props ?? {};
|
|
453
|
+
const localProps = Object.entries(props).filter(([_, p]) => p.source === "local");
|
|
454
|
+
const composition = data.meta?.composition ?? null;
|
|
455
|
+
const description = data.meta?.description || "";
|
|
456
|
+
const category = inferCategoryFromMeta(
|
|
457
|
+
name,
|
|
458
|
+
Object.fromEntries(localProps)
|
|
459
|
+
);
|
|
460
|
+
const lines = [
|
|
461
|
+
`Component: ${name}`,
|
|
462
|
+
`Category: ${category}`
|
|
463
|
+
];
|
|
464
|
+
if (description) {
|
|
465
|
+
lines.push(`Description: ${description}`);
|
|
466
|
+
}
|
|
467
|
+
if (localProps.length > 0) {
|
|
468
|
+
lines.push("");
|
|
469
|
+
lines.push("Props:");
|
|
470
|
+
for (const [propName, prop] of localProps) {
|
|
471
|
+
let propLine = ` - ${propName}: ${prop.typeKind}`;
|
|
472
|
+
if (prop.values && prop.values.length > 0) {
|
|
473
|
+
propLine += ` (${prop.values.join(" | ")})`;
|
|
474
|
+
}
|
|
475
|
+
if (prop.required) propLine += " [required]";
|
|
476
|
+
if (prop.description) propLine += ` \u2014 ${prop.description}`;
|
|
477
|
+
lines.push(propLine);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (composition && composition.parts.length > 0) {
|
|
481
|
+
lines.push("");
|
|
482
|
+
lines.push(`Composition: ${composition.pattern} pattern`);
|
|
483
|
+
lines.push(`Sub-components: ${composition.parts.map((p) => p.name).join(", ")}`);
|
|
484
|
+
}
|
|
485
|
+
if (data.storyVariants.length > 0) {
|
|
486
|
+
lines.push("");
|
|
487
|
+
lines.push(`Known variants: ${data.storyVariants.map((v) => v.name).join(", ")}`);
|
|
488
|
+
}
|
|
489
|
+
return lines.join("\n");
|
|
490
|
+
}
|
|
491
|
+
function parseEnrichmentResponse(text) {
|
|
492
|
+
const empty = {
|
|
493
|
+
when: [],
|
|
494
|
+
whenNot: [],
|
|
495
|
+
guidelines: [],
|
|
496
|
+
a11yRules: [],
|
|
497
|
+
scenarioTags: [],
|
|
498
|
+
tags: []
|
|
499
|
+
};
|
|
500
|
+
try {
|
|
501
|
+
const jsonMatch = text.match(/```json\n?([\s\S]*?)\n?```/) || text.match(/\{[\s\S]*\}/);
|
|
502
|
+
const jsonStr = jsonMatch ? jsonMatch[1] || jsonMatch[0] : text;
|
|
503
|
+
const parsed = JSON.parse(jsonStr);
|
|
504
|
+
const getArray = (key, maxLen) => {
|
|
505
|
+
const val = parsed[key];
|
|
506
|
+
if (!Array.isArray(val)) return [];
|
|
507
|
+
return val.filter((item) => typeof item === "string").slice(0, maxLen);
|
|
508
|
+
};
|
|
509
|
+
return {
|
|
510
|
+
when: getArray("when", 5),
|
|
511
|
+
whenNot: getArray("whenNot", 4),
|
|
512
|
+
guidelines: getArray("guidelines", 3),
|
|
513
|
+
a11yRules: getArray("a11yRules", 4),
|
|
514
|
+
scenarioTags: getArray("scenarioTags", 5),
|
|
515
|
+
tags: getArray("tags", 5)
|
|
516
|
+
};
|
|
517
|
+
} catch {
|
|
518
|
+
return empty;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
async function enrichComponents(componentDataList, options) {
|
|
522
|
+
const enrichments = /* @__PURE__ */ new Map();
|
|
523
|
+
let totalInputTokens = 0;
|
|
524
|
+
let totalOutputTokens = 0;
|
|
525
|
+
const {
|
|
526
|
+
detectProvider,
|
|
527
|
+
getApiKey,
|
|
528
|
+
createAIClient,
|
|
529
|
+
generateCompletion,
|
|
530
|
+
ENRICHMENT_MODELS
|
|
531
|
+
} = await import("./ai-client-I6MDWNYA.js");
|
|
532
|
+
const provider = detectProvider({ provider: options.provider, apiKey: options.apiKey });
|
|
533
|
+
if (provider === "none") {
|
|
534
|
+
console.log(pc.yellow(" No API key found. Set ANTHROPIC_API_KEY or OPENAI_API_KEY, or use --api-key"));
|
|
535
|
+
console.log(pc.yellow(" Skipping enrichment \u2014 fragment files will have TODO markers instead.\n"));
|
|
536
|
+
return { enrichments, totalInputTokens: 0, totalOutputTokens: 0, model: "" };
|
|
537
|
+
}
|
|
538
|
+
const apiKey = getApiKey(provider, options.apiKey);
|
|
539
|
+
if (!apiKey) {
|
|
540
|
+
console.log(pc.yellow(" API key not found for provider: " + provider));
|
|
541
|
+
console.log(pc.yellow(" Skipping enrichment.\n"));
|
|
542
|
+
return { enrichments, totalInputTokens: 0, totalOutputTokens: 0, model: "" };
|
|
543
|
+
}
|
|
544
|
+
const model = options.model || ENRICHMENT_MODELS[provider];
|
|
545
|
+
if (options.dryRun) {
|
|
546
|
+
for (const data of componentDataList) {
|
|
547
|
+
console.log(pc.dim(` Would enrich: ${data.component.name}`));
|
|
548
|
+
}
|
|
549
|
+
return { enrichments, totalInputTokens: 0, totalOutputTokens: 0, model };
|
|
550
|
+
}
|
|
551
|
+
const client = await createAIClient(provider, apiKey);
|
|
552
|
+
const systemPrompt = buildEnrichmentSystemPrompt();
|
|
553
|
+
for (const data of componentDataList) {
|
|
554
|
+
const name = data.component.name;
|
|
555
|
+
process.stdout.write(pc.dim(` Enriching ${name}...`));
|
|
556
|
+
try {
|
|
557
|
+
const userPrompt = buildEnrichmentUserPrompt(name, data);
|
|
558
|
+
const result = await generateCompletion(client, provider, model, systemPrompt, userPrompt, 512);
|
|
559
|
+
totalInputTokens += result.inputTokens;
|
|
560
|
+
totalOutputTokens += result.outputTokens;
|
|
561
|
+
const enrichment = parseEnrichmentResponse(result.text);
|
|
562
|
+
const fieldCount = enrichment.when.length + enrichment.whenNot.length + enrichment.guidelines.length + enrichment.a11yRules.length + enrichment.scenarioTags.length + enrichment.tags.length;
|
|
563
|
+
enrichments.set(name, enrichment);
|
|
564
|
+
process.stdout.write(`\r ${pc.green("\u2713")} ${name} (${fieldCount} fields)
|
|
565
|
+
`);
|
|
566
|
+
} catch (e) {
|
|
567
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
568
|
+
process.stdout.write(`\r ${pc.yellow("!")} ${name}: ${msg}
|
|
569
|
+
`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return { enrichments, totalInputTokens, totalOutputTokens, model };
|
|
573
|
+
}
|
|
574
|
+
function buildEnrichedUsageBlock(enrichment) {
|
|
575
|
+
const lines = [];
|
|
576
|
+
lines.push(" usage: {");
|
|
577
|
+
if (enrichment.when.length > 0) {
|
|
578
|
+
lines.push(" when: [");
|
|
579
|
+
for (const item of enrichment.when) {
|
|
580
|
+
lines.push(` '${escapeQuotes(item)}',`);
|
|
581
|
+
}
|
|
582
|
+
lines.push(" ],");
|
|
583
|
+
} else {
|
|
584
|
+
lines.push(" when: [],");
|
|
585
|
+
}
|
|
586
|
+
if (enrichment.whenNot.length > 0) {
|
|
587
|
+
lines.push(" whenNot: [");
|
|
588
|
+
for (const item of enrichment.whenNot) {
|
|
589
|
+
lines.push(` '${escapeQuotes(item)}',`);
|
|
590
|
+
}
|
|
591
|
+
lines.push(" ],");
|
|
592
|
+
} else {
|
|
593
|
+
lines.push(" whenNot: [],");
|
|
594
|
+
}
|
|
595
|
+
if (enrichment.guidelines.length > 0) {
|
|
596
|
+
lines.push(" guidelines: [");
|
|
597
|
+
for (const item of enrichment.guidelines) {
|
|
598
|
+
lines.push(` '${escapeQuotes(item)}',`);
|
|
599
|
+
}
|
|
600
|
+
lines.push(" ],");
|
|
601
|
+
}
|
|
602
|
+
lines.push(" },");
|
|
603
|
+
return lines.join("\n");
|
|
604
|
+
}
|
|
605
|
+
function calculateFieldConfidence(data, enrichment) {
|
|
606
|
+
let score = 0;
|
|
607
|
+
const todoFields = [];
|
|
608
|
+
const props = data.meta?.props ?? {};
|
|
609
|
+
const localEntries = Object.values(props).filter((p) => p.source === "local");
|
|
610
|
+
const hasProps = localEntries.length > 0;
|
|
611
|
+
if (hasProps) {
|
|
612
|
+
score += 30;
|
|
613
|
+
}
|
|
614
|
+
if (data.meta?.description) {
|
|
615
|
+
score += 15;
|
|
616
|
+
} else {
|
|
617
|
+
todoFields.push("meta.description");
|
|
618
|
+
}
|
|
619
|
+
const localProps = Object.fromEntries(
|
|
620
|
+
Object.entries(props).filter(([_, p]) => p.source === "local")
|
|
621
|
+
);
|
|
622
|
+
const category = inferCategoryFromMeta(data.component.name, localProps);
|
|
623
|
+
if (category !== "Components") {
|
|
624
|
+
score += 10;
|
|
625
|
+
} else {
|
|
626
|
+
todoFields.push("meta.category");
|
|
627
|
+
}
|
|
628
|
+
if (data.storyVariants.length > 0) {
|
|
629
|
+
score += 25;
|
|
630
|
+
}
|
|
631
|
+
if (hasProps) {
|
|
632
|
+
const allResolved = localEntries.every((p) => p.typeKind !== "custom");
|
|
633
|
+
if (allResolved) {
|
|
634
|
+
score += 10;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (data.meta?.composition && data.meta.composition.parts.length > 0) {
|
|
638
|
+
score += 10;
|
|
639
|
+
}
|
|
640
|
+
if (hasProps) {
|
|
641
|
+
const hasDefaults = localEntries.some((p) => p.default !== void 0);
|
|
642
|
+
if (hasDefaults) {
|
|
643
|
+
score += 5;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
if (enrichment && enrichment.when.length > 0) {
|
|
647
|
+
score += 10;
|
|
648
|
+
} else {
|
|
649
|
+
todoFields.push("usage.when");
|
|
650
|
+
}
|
|
651
|
+
if (enrichment && enrichment.whenNot.length > 0) {
|
|
652
|
+
score += 5;
|
|
653
|
+
} else {
|
|
654
|
+
todoFields.push("usage.whenNot");
|
|
655
|
+
}
|
|
656
|
+
if (enrichment && enrichment.guidelines.length > 0) {
|
|
657
|
+
score += 5;
|
|
658
|
+
}
|
|
659
|
+
if (enrichment && enrichment.tags.length > 0) {
|
|
660
|
+
score += 5;
|
|
661
|
+
}
|
|
662
|
+
return { score: Math.min(score, 100), todoFields };
|
|
663
|
+
}
|
|
664
|
+
var CATEGORY_PATTERNS = {
|
|
665
|
+
Actions: ["button", "action", "cta", "fab", "floatingaction"],
|
|
666
|
+
Forms: [
|
|
667
|
+
"form",
|
|
668
|
+
"input",
|
|
669
|
+
"select",
|
|
670
|
+
"checkbox",
|
|
671
|
+
"radio",
|
|
672
|
+
"textarea",
|
|
673
|
+
"field",
|
|
674
|
+
"textfield",
|
|
675
|
+
"datepicker",
|
|
676
|
+
"switch",
|
|
677
|
+
"slider",
|
|
678
|
+
"segmented"
|
|
679
|
+
],
|
|
680
|
+
Layout: [
|
|
681
|
+
"layout",
|
|
682
|
+
"container",
|
|
683
|
+
"grid",
|
|
684
|
+
"flex",
|
|
685
|
+
"stack",
|
|
686
|
+
"box",
|
|
687
|
+
"divider",
|
|
688
|
+
"spacer",
|
|
689
|
+
"sidebar"
|
|
690
|
+
],
|
|
691
|
+
Navigation: [
|
|
692
|
+
"nav",
|
|
693
|
+
"menu",
|
|
694
|
+
"breadcrumb",
|
|
695
|
+
"tab",
|
|
696
|
+
"link",
|
|
697
|
+
"pagination",
|
|
698
|
+
"stepper",
|
|
699
|
+
"topbar"
|
|
700
|
+
],
|
|
701
|
+
Feedback: [
|
|
702
|
+
"alert",
|
|
703
|
+
"toast",
|
|
704
|
+
"notification",
|
|
705
|
+
"message",
|
|
706
|
+
"badge",
|
|
707
|
+
"indicator",
|
|
708
|
+
"progress",
|
|
709
|
+
"spinner",
|
|
710
|
+
"loading",
|
|
711
|
+
"loader",
|
|
712
|
+
"lozenge",
|
|
713
|
+
"chip"
|
|
714
|
+
],
|
|
715
|
+
"Data Display": [
|
|
716
|
+
"table",
|
|
717
|
+
"list",
|
|
718
|
+
"card",
|
|
719
|
+
"avatar",
|
|
720
|
+
"stat",
|
|
721
|
+
"timeline",
|
|
722
|
+
"tree",
|
|
723
|
+
"datalist",
|
|
724
|
+
"datacard"
|
|
725
|
+
],
|
|
726
|
+
Overlays: [
|
|
727
|
+
"modal",
|
|
728
|
+
"dialog",
|
|
729
|
+
"drawer",
|
|
730
|
+
"popover",
|
|
731
|
+
"tooltip",
|
|
732
|
+
"dropdown",
|
|
733
|
+
"slidepanel"
|
|
734
|
+
],
|
|
735
|
+
Typography: ["text", "heading", "title", "label", "paragraph"],
|
|
736
|
+
Media: ["image", "video", "icon", "carousel"]
|
|
737
|
+
};
|
|
738
|
+
function inferCategoryFromMeta(componentName, props) {
|
|
739
|
+
const lower = componentName.toLowerCase();
|
|
740
|
+
for (const [category, patterns] of Object.entries(CATEGORY_PATTERNS)) {
|
|
741
|
+
for (const pattern of patterns) {
|
|
742
|
+
if (lower.includes(pattern)) {
|
|
743
|
+
return category;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
const propNames = new Set(Object.keys(props));
|
|
748
|
+
if (propNames.has("onClick") || propNames.has("onPress")) return "Actions";
|
|
749
|
+
if (propNames.has("value") || propNames.has("defaultValue")) return "Forms";
|
|
750
|
+
if (propNames.has("children")) return "Layout";
|
|
751
|
+
return "Components";
|
|
752
|
+
}
|
|
753
|
+
function inferStatus(filePath) {
|
|
754
|
+
const lowerPath = filePath.toLowerCase();
|
|
755
|
+
if (lowerPath.includes("/experimental/") || lowerPath.includes("/labs/"))
|
|
756
|
+
return "experimental";
|
|
757
|
+
if (lowerPath.includes("/beta/")) return "beta";
|
|
758
|
+
if (lowerPath.includes("/deprecated/") || lowerPath.includes("/legacy/"))
|
|
759
|
+
return "deprecated";
|
|
760
|
+
if (lowerPath.includes("/draft/") || lowerPath.includes("/wip/"))
|
|
761
|
+
return "draft";
|
|
762
|
+
return "stable";
|
|
763
|
+
}
|
|
764
|
+
function inferDescriptionFromMeta(componentName, props) {
|
|
765
|
+
const words = componentName.replace(/([A-Z])/g, " $1").trim().toLowerCase();
|
|
766
|
+
const propNames = new Set(Object.keys(props));
|
|
767
|
+
const hasOnClick = propNames.has("onClick") || propNames.has("onPress");
|
|
768
|
+
const hasValue = propNames.has("value") || propNames.has("defaultValue");
|
|
769
|
+
const hasChildren = propNames.has("children");
|
|
770
|
+
if (hasOnClick && !hasValue)
|
|
771
|
+
return `Interactive ${words} element for triggering actions`;
|
|
772
|
+
if (hasValue) return `Form ${words} for user input`;
|
|
773
|
+
if (hasChildren) return `Container ${words} for grouping content`;
|
|
774
|
+
return `${words.charAt(0).toUpperCase() + words.slice(1)} component`;
|
|
775
|
+
}
|
|
776
|
+
function inferAccessibilityFromMeta(props) {
|
|
777
|
+
const propNames = new Set(Object.keys(props));
|
|
778
|
+
const accessibility = {};
|
|
779
|
+
const hasOnClick = propNames.has("onClick") || propNames.has("onPress");
|
|
780
|
+
const hasAriaLabel = propNames.has("ariaLabel") || propNames.has("aria-label");
|
|
781
|
+
const hasDisabled = propNames.has("disabled");
|
|
782
|
+
const hasHref = propNames.has("href");
|
|
783
|
+
if (hasOnClick && !hasHref) accessibility.role = "button";
|
|
784
|
+
else if (hasHref) accessibility.role = "link";
|
|
785
|
+
const requirements = [];
|
|
786
|
+
if (hasOnClick && !hasAriaLabel)
|
|
787
|
+
requirements.push("Should have visible text or aria-label");
|
|
788
|
+
if (hasDisabled)
|
|
789
|
+
requirements.push(
|
|
790
|
+
"Disabled state should be conveyed to assistive technology"
|
|
791
|
+
);
|
|
792
|
+
if (requirements.length > 0) accessibility.requirements = requirements;
|
|
793
|
+
return accessibility;
|
|
794
|
+
}
|
|
795
|
+
function buildContractBlock(componentName, props, composition, accessibility) {
|
|
796
|
+
const localEntries = Object.entries(props).filter(([_, p]) => p.source === "local");
|
|
797
|
+
if (localEntries.length === 0 && !composition && !accessibility.requirements?.length) {
|
|
798
|
+
return null;
|
|
799
|
+
}
|
|
800
|
+
const contract = { propsSummary: [] };
|
|
801
|
+
for (const [name, prop] of localEntries) {
|
|
802
|
+
let summary = name + ": ";
|
|
803
|
+
if (prop.typeKind === "enum" && prop.values && prop.values.length > 0) {
|
|
804
|
+
summary += prop.values.join(" | ");
|
|
805
|
+
} else {
|
|
806
|
+
summary += prop.typeKind;
|
|
807
|
+
}
|
|
808
|
+
if (prop.required) summary += " (required)";
|
|
809
|
+
if (prop.default !== void 0) summary += ` (default: ${prop.default})`;
|
|
810
|
+
contract.propsSummary.push(summary);
|
|
811
|
+
}
|
|
812
|
+
if (composition && composition.parts.length > 0) {
|
|
813
|
+
const children = {};
|
|
814
|
+
for (const part of composition.parts) {
|
|
815
|
+
const childEntry = {};
|
|
816
|
+
if (composition.required.includes(part.name)) {
|
|
817
|
+
childEntry.required = true;
|
|
818
|
+
}
|
|
819
|
+
const nodeProps = Object.entries(part.props).filter(([_, p]) => p.typeKind === "node" || p.typeKind === "element").map(([n]) => n);
|
|
820
|
+
if (nodeProps.length > 0) {
|
|
821
|
+
childEntry.accepts = nodeProps;
|
|
822
|
+
}
|
|
823
|
+
children[part.name] = childEntry;
|
|
824
|
+
}
|
|
825
|
+
contract.compoundChildren = children;
|
|
826
|
+
}
|
|
827
|
+
if (composition && composition.parts.length > 0) {
|
|
828
|
+
const innerLines = composition.parts.map((part) => ` <${componentName}.${part.name}>...</${componentName}.${part.name}>`).join("\n");
|
|
829
|
+
contract.canonicalUsage = [
|
|
830
|
+
`<${componentName}>
|
|
831
|
+
${innerLines}
|
|
832
|
+
</${componentName}>`
|
|
833
|
+
];
|
|
834
|
+
}
|
|
835
|
+
const rules = [];
|
|
836
|
+
if (accessibility.role) {
|
|
837
|
+
rules.push(`Role: ${accessibility.role}`);
|
|
838
|
+
}
|
|
839
|
+
if (accessibility.requirements) {
|
|
840
|
+
rules.push(...accessibility.requirements);
|
|
841
|
+
}
|
|
842
|
+
if (rules.length > 0) {
|
|
843
|
+
contract.a11yRules = rules;
|
|
844
|
+
}
|
|
845
|
+
return contract;
|
|
846
|
+
}
|
|
847
|
+
function emitContractBlock(contract) {
|
|
848
|
+
const lines = [];
|
|
849
|
+
lines.push("\n contract: {");
|
|
850
|
+
if (contract.propsSummary.length > 0) {
|
|
851
|
+
lines.push(" propsSummary: [");
|
|
852
|
+
for (const s of contract.propsSummary) {
|
|
853
|
+
lines.push(` '${escapeQuotes(s)}',`);
|
|
854
|
+
}
|
|
855
|
+
lines.push(" ],");
|
|
856
|
+
}
|
|
857
|
+
if (contract.compoundChildren && Object.keys(contract.compoundChildren).length > 0) {
|
|
858
|
+
lines.push(" compoundChildren: {");
|
|
859
|
+
for (const [name, meta] of Object.entries(contract.compoundChildren)) {
|
|
860
|
+
const fields = [];
|
|
861
|
+
if (meta.required) fields.push(`required: true`);
|
|
862
|
+
if (meta.accepts && meta.accepts.length > 0) {
|
|
863
|
+
fields.push(`accepts: [${meta.accepts.map((a) => `'${a}'`).join(", ")}]`);
|
|
864
|
+
}
|
|
865
|
+
if (meta.description) fields.push(`description: '${escapeQuotes(meta.description)}'`);
|
|
866
|
+
lines.push(` ${name}: { ${fields.join(", ")} },`);
|
|
867
|
+
}
|
|
868
|
+
lines.push(" },");
|
|
869
|
+
}
|
|
870
|
+
if (contract.canonicalUsage && contract.canonicalUsage.length > 0) {
|
|
871
|
+
lines.push(" canonicalUsage: [");
|
|
872
|
+
for (const usage of contract.canonicalUsage) {
|
|
873
|
+
lines.push(` \`${usage}\`,`);
|
|
874
|
+
}
|
|
875
|
+
lines.push(" ],");
|
|
876
|
+
}
|
|
877
|
+
if (contract.a11yRules && contract.a11yRules.length > 0) {
|
|
878
|
+
lines.push(" a11yRules: [");
|
|
879
|
+
for (const rule of contract.a11yRules) {
|
|
880
|
+
lines.push(` '${escapeQuotes(rule)}',`);
|
|
881
|
+
}
|
|
882
|
+
lines.push(" ],");
|
|
883
|
+
}
|
|
884
|
+
if (contract.scenarioTags && contract.scenarioTags.length > 0) {
|
|
885
|
+
lines.push(" scenarioTags: [");
|
|
886
|
+
for (const tag of contract.scenarioTags) {
|
|
887
|
+
lines.push(` '${escapeQuotes(tag)}',`);
|
|
888
|
+
}
|
|
889
|
+
lines.push(" ],");
|
|
890
|
+
}
|
|
891
|
+
lines.push(" },");
|
|
892
|
+
return lines.join("\n");
|
|
893
|
+
}
|
|
894
|
+
function computeImportPath(fragmentDir, sourcePath, componentBaseName) {
|
|
895
|
+
const sourceDir = dirname(sourcePath);
|
|
896
|
+
if (fragmentDir === sourceDir) {
|
|
897
|
+
if (componentBaseName === "index") {
|
|
898
|
+
return ".";
|
|
899
|
+
}
|
|
900
|
+
return `./${componentBaseName}`;
|
|
901
|
+
}
|
|
902
|
+
let rel = relative(fragmentDir, sourceDir);
|
|
903
|
+
if (!rel.startsWith(".")) rel = `./${rel}`;
|
|
904
|
+
if (componentBaseName !== "index") {
|
|
905
|
+
rel = `${rel}/${componentBaseName}`;
|
|
906
|
+
}
|
|
907
|
+
return rel;
|
|
908
|
+
}
|
|
909
|
+
function escapeQuotes(str) {
|
|
910
|
+
return str.replace(/'/g, "\\'");
|
|
911
|
+
}
|
|
912
|
+
function generateFragmentWithTodos(componentName, importPath, data, confidence, enrichment) {
|
|
913
|
+
const props = data.meta?.props ?? {};
|
|
914
|
+
const localProps = Object.fromEntries(
|
|
915
|
+
Object.entries(props).filter(([_, p]) => p.source === "local")
|
|
916
|
+
);
|
|
917
|
+
const composition = data.meta?.composition ?? null;
|
|
918
|
+
const description = data.meta?.description || inferDescriptionFromMeta(componentName, localProps);
|
|
919
|
+
const descriptionTodo = data.meta?.description ? "" : " // TODO: Review description";
|
|
920
|
+
const category = inferCategoryFromMeta(componentName, localProps);
|
|
921
|
+
const categoryTodo = category === "Components" ? " // TODO: Set correct category" : "";
|
|
922
|
+
const status = inferStatus(data.component.sourcePath);
|
|
923
|
+
const accessibility = inferAccessibilityFromMeta(localProps);
|
|
924
|
+
const propsBlock = buildPropsBlockFromMeta(props);
|
|
925
|
+
const contract = buildContractBlock(componentName, props, composition, accessibility);
|
|
926
|
+
if (contract && enrichment) {
|
|
927
|
+
if (enrichment.a11yRules.length > 0) {
|
|
928
|
+
contract.a11yRules = enrichment.a11yRules;
|
|
929
|
+
}
|
|
930
|
+
if (enrichment.scenarioTags.length > 0) {
|
|
931
|
+
contract.scenarioTags = enrichment.scenarioTags;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const contractBlock = contract ? emitContractBlock(contract) : "";
|
|
935
|
+
let usageBlock;
|
|
936
|
+
if (enrichment && (enrichment.when.length > 0 || enrichment.whenNot.length > 0)) {
|
|
937
|
+
usageBlock = buildEnrichedUsageBlock(enrichment);
|
|
938
|
+
} else {
|
|
939
|
+
usageBlock = ` usage: {
|
|
940
|
+
when: [
|
|
941
|
+
// TODO: Describe when to use ${componentName}
|
|
942
|
+
],
|
|
943
|
+
whenNot: [
|
|
944
|
+
// TODO: Describe when NOT to use ${componentName}
|
|
945
|
+
],
|
|
946
|
+
},`;
|
|
947
|
+
}
|
|
948
|
+
const tagsLine = enrichment && enrichment.tags.length > 0 ? `
|
|
949
|
+
tags: [${enrichment.tags.map((t) => `'${escapeQuotes(t)}'`).join(", ")}],` : "";
|
|
950
|
+
const variantsBlock = buildVariantsBlock(
|
|
951
|
+
componentName,
|
|
952
|
+
data.storyVariants,
|
|
953
|
+
composition
|
|
954
|
+
);
|
|
955
|
+
const aiBlock = buildAIBlock(composition);
|
|
956
|
+
const provenanceBlock = buildProvenanceBlock(confidence, props);
|
|
957
|
+
const compoundComment = composition && composition.parts.length > 0 ? `
|
|
958
|
+
// Compound sub-components detected: ${composition.parts.map((p) => p.name).join(", ")}` : "";
|
|
959
|
+
return `// Auto-generated by fragments init --scan | Confidence: ${confidence.score}/100
|
|
960
|
+
// ${confidence.todoFields.length} TODO(s) \u2014 search for "TODO:" and fill in human knowledge${compoundComment}
|
|
961
|
+
import React from 'react';
|
|
962
|
+
import { defineFragment } from '@fragments-sdk/core';
|
|
963
|
+
import { ${componentName} } from '${importPath}';
|
|
964
|
+
|
|
965
|
+
export default defineFragment({
|
|
966
|
+
component: ${componentName},
|
|
967
|
+
|
|
968
|
+
meta: {
|
|
969
|
+
name: '${escapeQuotes(componentName)}',
|
|
970
|
+
description: '${escapeQuotes(description)}',${descriptionTodo}
|
|
971
|
+
category: '${escapeQuotes(category)}',${categoryTodo}
|
|
972
|
+
status: '${status}',${tagsLine}
|
|
973
|
+
},
|
|
974
|
+
|
|
975
|
+
${usageBlock}
|
|
976
|
+
|
|
977
|
+
props: ${propsBlock},${contractBlock}${aiBlock}
|
|
978
|
+
|
|
979
|
+
variants: [
|
|
980
|
+
${variantsBlock}
|
|
981
|
+
],
|
|
982
|
+
${provenanceBlock}});
|
|
983
|
+
`;
|
|
984
|
+
}
|
|
985
|
+
function buildPropsBlockFromMeta(props) {
|
|
986
|
+
const entries = Object.entries(props).filter(([_, p]) => p.source === "local");
|
|
987
|
+
if (entries.length === 0) return "{}";
|
|
988
|
+
const lines = entries.map(([name, prop]) => {
|
|
989
|
+
const type = prop.typeKind;
|
|
990
|
+
const parts = [` type: '${type}'`];
|
|
991
|
+
if (prop.description) {
|
|
992
|
+
parts.push(
|
|
993
|
+
` description: '${escapeQuotes(prop.description.replace(/\n/g, " "))}'`
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
parts.push(` required: ${prop.required}`);
|
|
997
|
+
if (prop.default !== void 0) {
|
|
998
|
+
parts.push(` default: ${JSON.stringify(prop.default)}`);
|
|
999
|
+
}
|
|
1000
|
+
if (prop.values && prop.values.length > 0) {
|
|
1001
|
+
parts.push(` values: ${JSON.stringify(prop.values)}`);
|
|
1002
|
+
}
|
|
1003
|
+
const todoComment = type === "custom" ? " // TODO: Review type" : "";
|
|
1004
|
+
return ` ${name}: {
|
|
1005
|
+
${parts.join(",\n")},
|
|
1006
|
+
},${todoComment}`;
|
|
1007
|
+
});
|
|
1008
|
+
return `{
|
|
1009
|
+
${lines.join("\n")}
|
|
1010
|
+
}`;
|
|
1011
|
+
}
|
|
1012
|
+
function buildVariantsBlock(componentName, storyVariants, composition) {
|
|
1013
|
+
const entries = [];
|
|
1014
|
+
const hasDefault = storyVariants.some((v) => v.name === "Default");
|
|
1015
|
+
if (!hasDefault) {
|
|
1016
|
+
if (composition && composition.pattern === "compound" && composition.parts.length > 0) {
|
|
1017
|
+
entries.push(formatCompoundVariantEntry(componentName, composition));
|
|
1018
|
+
} else {
|
|
1019
|
+
entries.push(formatVariantEntry(componentName, "Default", `Default ${componentName}`, {}));
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
for (const variant of storyVariants) {
|
|
1023
|
+
const description = variant.name.replace(/([A-Z])/g, " $1").trim();
|
|
1024
|
+
entries.push(
|
|
1025
|
+
formatVariantEntry(
|
|
1026
|
+
componentName,
|
|
1027
|
+
variant.name,
|
|
1028
|
+
`${description} ${componentName}`,
|
|
1029
|
+
variant.args
|
|
1030
|
+
)
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
return entries.join("\n");
|
|
1034
|
+
}
|
|
1035
|
+
function formatVariantEntry(componentName, name, description, args) {
|
|
1036
|
+
const jsxCode = buildJsxString(componentName, args);
|
|
1037
|
+
return ` {
|
|
1038
|
+
name: '${escapeQuotes(name)}',
|
|
1039
|
+
description: '${escapeQuotes(description)}',
|
|
1040
|
+
code: \`${jsxCode}\`,
|
|
1041
|
+
render: () => ${jsxCode},
|
|
1042
|
+
},`;
|
|
1043
|
+
}
|
|
1044
|
+
function formatCompoundVariantEntry(componentName, composition) {
|
|
1045
|
+
const parts = composition.parts;
|
|
1046
|
+
const innerJsx = parts.map((part) => ` <${componentName}.${part.name}>...</${componentName}.${part.name}>`).join("\n");
|
|
1047
|
+
const jsxCode = `<${componentName}>
|
|
1048
|
+
${innerJsx}
|
|
1049
|
+
</${componentName}>`;
|
|
1050
|
+
return ` {
|
|
1051
|
+
name: 'Default',
|
|
1052
|
+
description: 'Default ${componentName} with sub-components',
|
|
1053
|
+
code: \`${jsxCode}\`,
|
|
1054
|
+
render: () => (
|
|
1055
|
+
${jsxCode}
|
|
1056
|
+
),
|
|
1057
|
+
},`;
|
|
1058
|
+
}
|
|
1059
|
+
function buildAIBlock(composition) {
|
|
1060
|
+
if (!composition || composition.parts.length === 0) return "";
|
|
1061
|
+
const subComponents = composition.parts.map((p) => `'${p.name}'`).join(", ");
|
|
1062
|
+
const pattern = `
|
|
1063
|
+
<Component>
|
|
1064
|
+
${composition.parts.map((p) => ` <Component.${p.name}>...</Component.${p.name}>`).join("\n")}
|
|
1065
|
+
</Component>`;
|
|
1066
|
+
return `
|
|
1067
|
+
|
|
1068
|
+
ai: {
|
|
1069
|
+
compositionPattern: '${composition.pattern}',
|
|
1070
|
+
subComponents: [${subComponents}],
|
|
1071
|
+
commonPatterns: [\`${pattern}
|
|
1072
|
+
\`],
|
|
1073
|
+
},`;
|
|
1074
|
+
}
|
|
1075
|
+
function buildProvenanceBlock(confidence, props) {
|
|
1076
|
+
const autoFields = Object.keys(props).filter((name) => props[name].source === "local");
|
|
1077
|
+
return `
|
|
1078
|
+
_generated: {
|
|
1079
|
+
source: 'ai',
|
|
1080
|
+
confidence: ${(confidence.score / 100).toFixed(2)},
|
|
1081
|
+
timestamp: '${(/* @__PURE__ */ new Date()).toISOString()}',
|
|
1082
|
+
},
|
|
1083
|
+
`;
|
|
1084
|
+
}
|
|
1085
|
+
function buildJsxString(componentName, args) {
|
|
1086
|
+
const { children, ...restArgs } = args;
|
|
1087
|
+
const propParts = [];
|
|
1088
|
+
for (const [key, value] of Object.entries(restArgs)) {
|
|
1089
|
+
if (typeof value === "string") {
|
|
1090
|
+
propParts.push(`${key}="${escapeQuotes(value)}"`);
|
|
1091
|
+
} else if (typeof value === "boolean") {
|
|
1092
|
+
propParts.push(value ? key : `${key}={false}`);
|
|
1093
|
+
} else if (typeof value === "number") {
|
|
1094
|
+
propParts.push(`${key}={${value}}`);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
const propsStr = propParts.length > 0 ? " " + propParts.join(" ") : "";
|
|
1098
|
+
if (typeof children === "string") {
|
|
1099
|
+
return `<${componentName}${propsStr}>${children}</${componentName}>`;
|
|
1100
|
+
}
|
|
1101
|
+
return `<${componentName}${propsStr} />`;
|
|
1102
|
+
}
|
|
1103
|
+
export {
|
|
1104
|
+
buildEnrichedUsageBlock,
|
|
1105
|
+
buildEnrichmentSystemPrompt,
|
|
1106
|
+
buildEnrichmentUserPrompt,
|
|
1107
|
+
calculateFieldConfidence,
|
|
1108
|
+
detectCompoundComponents,
|
|
1109
|
+
detectCompoundComponentsFromSource,
|
|
1110
|
+
extractComponentJSDoc,
|
|
1111
|
+
extractComponentJSDocFromSource,
|
|
1112
|
+
parseEnrichmentResponse,
|
|
1113
|
+
scanGenerate
|
|
1114
|
+
};
|
|
1115
|
+
//# sourceMappingURL=scan-generate-U3RFVDTX.js.map
|