@fragments-sdk/cli 0.14.3 → 0.15.1

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 (181) hide show
  1. package/README.md +0 -3
  2. package/dist/{ai-client-I6MDWNYA.js → ai-client-LSLQGOMM.js} +1 -2
  3. package/dist/bin.js +4745 -3817
  4. package/dist/bin.js.map +1 -1
  5. package/dist/{chunk-TXFCEDOC.js → chunk-2WXKALIG.js} +2 -2
  6. package/dist/{chunk-I34BC3CU.js → chunk-32LIWN2P.js} +1006 -3
  7. package/dist/chunk-32LIWN2P.js.map +1 -0
  8. package/dist/chunk-5JF26E55.js +1255 -0
  9. package/dist/chunk-5JF26E55.js.map +1 -0
  10. package/dist/{chunk-APTQIBS5.js → chunk-6SQPP47U.js} +153 -1342
  11. package/dist/chunk-6SQPP47U.js.map +1 -0
  12. package/dist/chunk-7DZC4YEV.js +294 -0
  13. package/dist/chunk-7DZC4YEV.js.map +1 -0
  14. package/dist/{chunk-PJT5IZ37.js → chunk-BJE3425I.js} +19 -52
  15. package/dist/{chunk-PJT5IZ37.js.map → chunk-BJE3425I.js.map} +1 -1
  16. package/dist/{chunk-55KERLWL.js → chunk-HQ6A6DTV.js} +1587 -1073
  17. package/dist/chunk-HQ6A6DTV.js.map +1 -0
  18. package/dist/chunk-MHIBEEW4.js +511 -0
  19. package/dist/chunk-MHIBEEW4.js.map +1 -0
  20. package/dist/{chunk-5A6X2Y73.js → chunk-ONUP6Z4W.js} +25 -13
  21. package/dist/chunk-ONUP6Z4W.js.map +1 -0
  22. package/dist/chunk-QCN35LJU.js +630 -0
  23. package/dist/chunk-QCN35LJU.js.map +1 -0
  24. package/dist/chunk-T47OLCSF.js +36 -0
  25. package/dist/chunk-T47OLCSF.js.map +1 -0
  26. package/dist/codebase-scanner-MQHUZC2G.js +21 -0
  27. package/dist/converter-7XM3Y6NJ.js +33 -0
  28. package/dist/converter-7XM3Y6NJ.js.map +1 -0
  29. package/dist/core/index.js +43 -2
  30. package/dist/create-IH4R45GE.js +806 -0
  31. package/dist/create-IH4R45GE.js.map +1 -0
  32. package/dist/{generate-RYWIPDN2.js → generate-PVOLUAAC.js} +4 -6
  33. package/dist/{generate-RYWIPDN2.js.map → generate-PVOLUAAC.js.map} +1 -1
  34. package/dist/govern-scan-OYFZYOQW.js +413 -0
  35. package/dist/govern-scan-OYFZYOQW.js.map +1 -0
  36. package/dist/index.d.ts +4 -23
  37. package/dist/index.js +15 -14
  38. package/dist/index.js.map +1 -1
  39. package/dist/{init-WRUSW7R5.js → init-SSGUSP7Z.js} +131 -129
  40. package/dist/init-SSGUSP7Z.js.map +1 -0
  41. package/dist/{init-cloud-REQ3XLHO.js → init-cloud-3DNKPWFB.js} +30 -5
  42. package/dist/{init-cloud-REQ3XLHO.js.map → init-cloud-3DNKPWFB.js.map} +1 -1
  43. package/dist/mcp-bin.js +5 -37
  44. package/dist/mcp-bin.js.map +1 -1
  45. package/dist/node-37AUE74M.js +65 -0
  46. package/dist/push-contracts-WY32TFP6.js +84 -0
  47. package/dist/push-contracts-WY32TFP6.js.map +1 -0
  48. package/dist/scan-PKSYSTRR.js +15 -0
  49. package/dist/{scan-generate-TFZVL3BT.js → scan-generate-VY27PIOX.js} +340 -52
  50. package/dist/scan-generate-VY27PIOX.js.map +1 -0
  51. package/dist/scanner-4KZNOXAK.js +12 -0
  52. package/dist/{service-HKJ6B7P7.js → service-QJGWUIVL.js} +41 -30
  53. package/dist/{snapshot-C5DYIGIV.js → snapshot-WIJMEIFT.js} +2 -3
  54. package/dist/{snapshot-C5DYIGIV.js.map → snapshot-WIJMEIFT.js.map} +1 -1
  55. package/dist/{static-viewer-DUVC4UIM.js → static-viewer-7QIBQZRC.js} +3 -4
  56. package/dist/static-viewer-7QIBQZRC.js.map +1 -0
  57. package/dist/{test-JW7JIDFG.js → test-64Z5BKBA.js} +4 -7
  58. package/dist/{test-JW7JIDFG.js.map → test-64Z5BKBA.js.map} +1 -1
  59. package/dist/token-normalizer-TEPOVBPV.js +312 -0
  60. package/dist/token-normalizer-TEPOVBPV.js.map +1 -0
  61. package/dist/token-parser-32KOIOFN.js +22 -0
  62. package/dist/token-parser-32KOIOFN.js.map +1 -0
  63. package/dist/{tokens-KE73G5JC.js → tokens-NZWFQIAB.js} +10 -9
  64. package/dist/{tokens-KE73G5JC.js.map → tokens-NZWFQIAB.js.map} +1 -1
  65. package/dist/tokens-generate-5JQSJ27E.js +85 -0
  66. package/dist/tokens-generate-5JQSJ27E.js.map +1 -0
  67. package/dist/tokens-push-HY3KO36V.js +148 -0
  68. package/dist/tokens-push-HY3KO36V.js.map +1 -0
  69. package/package.json +8 -6
  70. package/src/bin.ts +300 -48
  71. package/src/commands/__fixtures__/shadcn-label-wrapper/package.json +7 -0
  72. package/src/commands/__fixtures__/shadcn-label-wrapper/src/components/ui/label.contract.json +42 -0
  73. package/src/commands/__fixtures__/shadcn-label-wrapper/src/components/ui/label.tsx +11 -0
  74. package/src/commands/__fixtures__/shadcn-label-wrapper/src/components/ui/primitive.contract.json +20 -0
  75. package/src/commands/__fixtures__/shadcn-label-wrapper/src/components/ui/primitive.tsx +14 -0
  76. package/src/commands/__fixtures__/shadcn-label-wrapper/tsconfig.app.json +23 -0
  77. package/src/commands/__tests__/build-freshness.test.ts +231 -0
  78. package/src/commands/__tests__/create.test.ts +71 -0
  79. package/src/commands/__tests__/drift-sync.test.ts +1 -1
  80. package/src/commands/__tests__/govern.test.ts +258 -0
  81. package/src/commands/__tests__/init.test.ts +113 -0
  82. package/src/commands/__tests__/scan-generate.test.ts +189 -70
  83. package/src/commands/__tests__/verify.test.ts +91 -0
  84. package/src/commands/build.ts +54 -1
  85. package/src/commands/context.ts +1 -1
  86. package/src/commands/create.ts +536 -0
  87. package/src/commands/discover.ts +151 -0
  88. package/src/commands/doctor.ts +3 -2
  89. package/src/commands/enhance.ts +3 -1
  90. package/src/commands/govern-scan.ts +565 -0
  91. package/src/commands/govern.ts +67 -4
  92. package/src/commands/init-cloud.ts +32 -4
  93. package/src/commands/init.ts +152 -28
  94. package/src/commands/inspect.ts +290 -0
  95. package/src/commands/migrate-contract.ts +85 -0
  96. package/src/commands/push-contracts.ts +112 -0
  97. package/src/commands/scan-generate.ts +439 -51
  98. package/src/commands/scan.ts +14 -0
  99. package/src/commands/setup.ts +27 -50
  100. package/src/commands/sync.ts +2 -2
  101. package/src/commands/tokens-generate.ts +113 -0
  102. package/src/commands/tokens-push.ts +199 -0
  103. package/src/commands/verify.ts +195 -1
  104. package/src/core/__fixtures__/shadcn-input/input.tsx +7 -0
  105. package/src/core/__fixtures__/shadcn-input/tsconfig.json +14 -0
  106. package/src/core/__fixtures__/shadcn-label/label.tsx +11 -0
  107. package/src/core/__fixtures__/shadcn-label/primitive.tsx +14 -0
  108. package/src/core/__fixtures__/shadcn-label/tsconfig.json +14 -0
  109. package/src/core/__fixtures__/shadcn-radix-label/label.tsx +11 -0
  110. package/src/core/__fixtures__/shadcn-radix-label/node_modules/radix-ui/index.d.ts +12 -0
  111. package/src/core/__fixtures__/shadcn-radix-label/tsconfig.json +14 -0
  112. package/src/core/__tests__/contract-parity.test.ts +316 -0
  113. package/src/core/__tests__/token-resolver.test.ts +1 -1
  114. package/src/core/component-extractor.test.ts +40 -1
  115. package/src/core/config.ts +2 -1
  116. package/src/core/discovery.ts +13 -2
  117. package/src/core/drift-verifier.ts +123 -0
  118. package/src/core/extractor-adapter.ts +80 -0
  119. package/src/index.ts +3 -3
  120. package/src/mcp/__tests__/projectFields.test.ts +1 -1
  121. package/src/mcp/utils.ts +1 -50
  122. package/src/migrate/converter.ts +3 -3
  123. package/src/migrate/fragment-to-contract.ts +253 -0
  124. package/src/migrate/report.ts +1 -1
  125. package/src/scripts/token-benchmark.ts +121 -0
  126. package/src/service/__tests__/props-extractor.test.ts +94 -0
  127. package/src/service/__tests__/token-normalizer.test.ts +690 -0
  128. package/src/service/ast-utils.ts +4 -23
  129. package/src/service/babel-config.ts +23 -0
  130. package/src/service/enhance/converter.ts +61 -0
  131. package/src/service/enhance/props-extractor.ts +25 -8
  132. package/src/service/enhance/scanner.ts +5 -24
  133. package/src/service/index.ts +8 -0
  134. package/src/service/snippet-validation.ts +9 -3
  135. package/src/service/tailwind-v4-parser.ts +314 -0
  136. package/src/service/token-normalizer.ts +510 -0
  137. package/src/service/token-parser.ts +56 -0
  138. package/src/setup.ts +10 -39
  139. package/src/shared/index.ts +1 -0
  140. package/src/shared/project-fields.ts +46 -0
  141. package/src/theme/__tests__/component-contrast.test.ts +2 -2
  142. package/src/theme/__tests__/serializer.test.ts +1 -1
  143. package/src/theme/generator.ts +16 -1
  144. package/src/theme/schema.ts +8 -0
  145. package/src/theme/serializer.ts +13 -9
  146. package/src/theme/types.ts +8 -0
  147. package/src/validators.ts +1 -2
  148. package/src/viewer/__tests__/viewer-integration.test.ts +8 -8
  149. package/src/viewer/style-utils.ts +27 -412
  150. package/src/viewer/vite-plugin.ts +2 -2
  151. package/dist/chunk-55KERLWL.js.map +0 -1
  152. package/dist/chunk-5A6X2Y73.js.map +0 -1
  153. package/dist/chunk-APTQIBS5.js.map +0 -1
  154. package/dist/chunk-EYXVAMEX.js +0 -626
  155. package/dist/chunk-EYXVAMEX.js.map +0 -1
  156. package/dist/chunk-I34BC3CU.js.map +0 -1
  157. package/dist/chunk-LOYS64QS.js +0 -2453
  158. package/dist/chunk-LOYS64QS.js.map +0 -1
  159. package/dist/chunk-Z7EY4VHE.js +0 -50
  160. package/dist/chunk-ZKTFKHWN.js +0 -324
  161. package/dist/chunk-ZKTFKHWN.js.map +0 -1
  162. package/dist/discovery-VDANZAJ2.js +0 -28
  163. package/dist/init-WRUSW7R5.js.map +0 -1
  164. package/dist/sass.node-4XJK6YBF.js +0 -130708
  165. package/dist/sass.node-4XJK6YBF.js.map +0 -1
  166. package/dist/scan-YJHQIRKG.js +0 -14
  167. package/dist/scan-generate-TFZVL3BT.js.map +0 -1
  168. package/dist/viewer-2TZS3NDL.js +0 -2730
  169. package/dist/viewer-2TZS3NDL.js.map +0 -1
  170. package/src/build.ts +0 -612
  171. package/src/commands/dev.ts +0 -107
  172. package/src/core/auto-props.ts +0 -464
  173. package/src/core/component-extractor.ts +0 -1030
  174. package/src/core/token-resolver.ts +0 -155
  175. /package/dist/{ai-client-I6MDWNYA.js.map → ai-client-LSLQGOMM.js.map} +0 -0
  176. /package/dist/{chunk-TXFCEDOC.js.map → chunk-2WXKALIG.js.map} +0 -0
  177. /package/dist/{chunk-Z7EY4VHE.js.map → codebase-scanner-MQHUZC2G.js.map} +0 -0
  178. /package/dist/{discovery-VDANZAJ2.js.map → node-37AUE74M.js.map} +0 -0
  179. /package/dist/{scan-YJHQIRKG.js.map → scan-PKSYSTRR.js.map} +0 -0
  180. /package/dist/{service-HKJ6B7P7.js.map → scanner-4KZNOXAK.js.map} +0 -0
  181. /package/dist/{static-viewer-DUVC4UIM.js.map → service-QJGWUIVL.js.map} +0 -0
@@ -1,2453 +0,0 @@
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 {
6
- generateContextMd,
7
- generateRegistry,
8
- loadFragmentFile,
9
- parseFragmentFile
10
- } from "./chunk-55KERLWL.js";
11
- import {
12
- discoverBlockFiles,
13
- discoverComponentFiles,
14
- discoverFragmentFiles,
15
- discoverTokenFiles,
16
- extractComponentName
17
- } from "./chunk-ZKTFKHWN.js";
18
- import {
19
- BrowserPool,
20
- CaptureEngine,
21
- DiffEngine,
22
- StorageManager,
23
- analyzeDesignSystem,
24
- formatMs,
25
- generateHtmlReport,
26
- getGrade
27
- } from "./chunk-APTQIBS5.js";
28
- import {
29
- BRAND,
30
- DEFAULTS,
31
- classifyComplexity,
32
- compileBlock,
33
- fragmentDefinitionSchema,
34
- parseTokenFile,
35
- resolvePerformanceConfig
36
- } from "./chunk-I34BC3CU.js";
37
-
38
- // src/service/snippet-validation.ts
39
- import ts from "typescript";
40
- import { readFile } from "fs/promises";
41
- import { existsSync } from "fs";
42
- import { join } from "path";
43
- var INTRINSIC_TAGS = /* @__PURE__ */ new Set([
44
- "div",
45
- "span",
46
- "p",
47
- "h1",
48
- "h2",
49
- "h3",
50
- "h4",
51
- "h5",
52
- "h6",
53
- "main",
54
- "section",
55
- "article",
56
- "aside",
57
- "nav",
58
- "header",
59
- "footer",
60
- "ul",
61
- "ol",
62
- "li",
63
- "button",
64
- "input",
65
- "textarea",
66
- "label",
67
- "svg",
68
- "path"
69
- ]);
70
- var JSX_TAG_PATTERN = /<\s*([A-Za-z][A-Za-z0-9.]*)\b/g;
71
- var STYLE_PATTERN = /\bstyle\s*=\s*\{/;
72
- var TRANSPILED_PATTERN = /jsxDEV|_jsx|@__PURE__|\bfileName\s*:|\blineNumber\s*:|\bcolumnNumber\s*:/;
73
- var ALIAS_DRIFT_PATTERN = /<\s*[A-Z][A-Za-z0-9]*(?:Root|2)\b/;
74
- var HAS_IMPORT_PATTERN = /\bimport\s+[^;]+\s+from\s+['"][^'"]+['"]/;
75
- var HAS_JSX_PATTERN = /<\s*[A-Za-z][A-Za-z0-9.]*\b/;
76
- var DEFAULT_POLICY = {
77
- mode: "warn",
78
- scope: "snippet+render",
79
- requireFullSnippet: true,
80
- allowedExternalModules: /* @__PURE__ */ new Set([
81
- "@phosphor-icons/react",
82
- "recharts",
83
- "react-day-picker"
84
- ])
85
- };
86
- function normalizePolicy(configured, overrides) {
87
- const fromConfig = {
88
- mode: configured?.mode ?? DEFAULT_POLICY.mode,
89
- scope: configured?.scope ?? DEFAULT_POLICY.scope,
90
- requireFullSnippet: configured?.requireFullSnippet ?? DEFAULT_POLICY.requireFullSnippet,
91
- allowedExternalModules: new Set(configured?.allowedExternalModules ?? [...DEFAULT_POLICY.allowedExternalModules]),
92
- componentStart: overrides.componentStart,
93
- componentLimit: overrides.componentLimit
94
- };
95
- if (overrides.mode) fromConfig.mode = overrides.mode;
96
- if (overrides.scope) fromConfig.scope = overrides.scope;
97
- if (typeof overrides.requireFullSnippet === "boolean") {
98
- fromConfig.requireFullSnippet = overrides.requireFullSnippet;
99
- }
100
- if (overrides.allowedExternalModules && overrides.allowedExternalModules.length > 0) {
101
- fromConfig.allowedExternalModules = new Set(overrides.allowedExternalModules);
102
- }
103
- return fromConfig;
104
- }
105
- function isFragmentsModule(modulePath) {
106
- return modulePath === "@fragments-sdk/ui" || modulePath === "." || modulePath === ".." || modulePath.startsWith("@/components/") || modulePath.startsWith("@components/") || modulePath.startsWith("./") || modulePath.startsWith("../");
107
- }
108
- function collectSourceContext(sourceFile) {
109
- const imports = /* @__PURE__ */ new Map();
110
- const localComponents = /* @__PURE__ */ new Set();
111
- function markLocal(name) {
112
- if (!name) return;
113
- if (/^[A-Z]/.test(name)) {
114
- localComponents.add(name);
115
- }
116
- }
117
- function visit(node) {
118
- if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
119
- const modulePath = node.moduleSpecifier.text;
120
- const clause = node.importClause;
121
- if (clause?.name) {
122
- imports.set(clause.name.text, modulePath);
123
- }
124
- if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) {
125
- for (const item of clause.namedBindings.elements) {
126
- imports.set(item.name.text, modulePath);
127
- }
128
- }
129
- }
130
- if (ts.isFunctionDeclaration(node)) {
131
- markLocal(node.name?.text);
132
- }
133
- if (ts.isClassDeclaration(node)) {
134
- markLocal(node.name?.text);
135
- }
136
- if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
137
- markLocal(node.name.text);
138
- }
139
- ts.forEachChild(node, visit);
140
- }
141
- visit(sourceFile);
142
- return { imports, localComponents };
143
- }
144
- function getJsxTags(code) {
145
- const tags = [];
146
- JSX_TAG_PATTERN.lastIndex = 0;
147
- let match;
148
- while ((match = JSX_TAG_PATTERN.exec(code)) !== null) {
149
- tags.push(match[1]);
150
- }
151
- return tags;
152
- }
153
- function rootTagName(tag) {
154
- return tag.split(".")[0];
155
- }
156
- function parseSnippetImports(snippet) {
157
- const sourceFile = ts.createSourceFile(
158
- "snippet.tsx",
159
- snippet,
160
- ts.ScriptTarget.Latest,
161
- true,
162
- ts.ScriptKind.TSX
163
- );
164
- return collectSourceContext(sourceFile).imports;
165
- }
166
- function findDefineCall(sourceFile, name) {
167
- let result = null;
168
- function visit(node) {
169
- if (result) return;
170
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === name) {
171
- result = node;
172
- return;
173
- }
174
- ts.forEachChild(node, visit);
175
- }
176
- visit(sourceFile);
177
- return result;
178
- }
179
- function findProperty(obj, propertyName) {
180
- for (const prop of obj.properties) {
181
- if (!ts.isPropertyAssignment(prop)) continue;
182
- if (!ts.isIdentifier(prop.name)) continue;
183
- if (prop.name.text === propertyName) {
184
- return prop.initializer;
185
- }
186
- }
187
- return null;
188
- }
189
- function readStaticString(expr) {
190
- if (!expr) return null;
191
- if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) {
192
- return expr.text;
193
- }
194
- return null;
195
- }
196
- function readRenderBody(renderExpr, sourceFile) {
197
- if (!ts.isArrowFunction(renderExpr) && !ts.isFunctionExpression(renderExpr)) {
198
- return null;
199
- }
200
- const body = renderExpr.body;
201
- const start = body.getStart(sourceFile);
202
- const end = body.getEnd();
203
- return sourceFile.text.slice(start, end).trim();
204
- }
205
- function report(issues, file, message) {
206
- issues.push({ file, message });
207
- }
208
- function validateRawRules(issues, file, label, code) {
209
- if (STYLE_PATTERN.test(code)) {
210
- report(issues, file, `${label}: inline style usage is not allowed; use Box/Stack/Text props.`);
211
- }
212
- if (TRANSPILED_PATTERN.test(code)) {
213
- report(issues, file, `${label}: transpiler output detected (jsxDEV/_jsx/@__PURE__). Use authored snippet source.`);
214
- }
215
- if (ALIAS_DRIFT_PATTERN.test(code)) {
216
- report(issues, file, `${label}: alias drift tag detected (*Root/*2). Use canonical component names.`);
217
- }
218
- const tags = getJsxTags(code);
219
- const intrinsic = tags.map((tag) => rootTagName(tag)).filter((tag) => /^[a-z]/.test(tag)).map((tag) => tag.toLowerCase()).filter((tag) => INTRINSIC_TAGS.has(tag));
220
- if (intrinsic.length > 0) {
221
- const names = [...new Set(intrinsic)].sort().join(", ");
222
- report(issues, file, `${label}: raw HTML tags are not allowed (${names}). Use Fragments primitives.`);
223
- }
224
- }
225
- function validateComponentAllowlist(issues, file, label, code, imports, localComponents, policy) {
226
- const tags = getJsxTags(code);
227
- const seen = /* @__PURE__ */ new Set();
228
- for (const tag of tags) {
229
- const root = rootTagName(tag);
230
- if (seen.has(root)) continue;
231
- seen.add(root);
232
- if (!/^[A-Z]/.test(root)) {
233
- continue;
234
- }
235
- const modulePath = imports.get(root);
236
- if (modulePath) {
237
- if (isFragmentsModule(modulePath)) {
238
- continue;
239
- }
240
- if (policy.allowedExternalModules.has(modulePath)) {
241
- continue;
242
- }
243
- report(
244
- issues,
245
- file,
246
- `${label}: component "${root}" comes from "${modulePath}" and is not in snippets.allowedExternalModules.`
247
- );
248
- continue;
249
- }
250
- if (localComponents.has(root)) {
251
- report(
252
- issues,
253
- file,
254
- `${label}: locally defined JSX component "${root}" is not allowed in snippets/renders. Import approved components instead.`
255
- );
256
- continue;
257
- }
258
- report(
259
- issues,
260
- file,
261
- `${label}: component "${root}" is used without an import and is not allowed.`
262
- );
263
- }
264
- }
265
- function validateSnippetString(issues, file, label, snippet, policy) {
266
- validateRawRules(issues, file, label, snippet);
267
- if (policy.requireFullSnippet) {
268
- if (!HAS_IMPORT_PATTERN.test(snippet)) {
269
- report(issues, file, `${label}: full snippet required (missing import statement).`);
270
- }
271
- if (!HAS_JSX_PATTERN.test(snippet)) {
272
- report(issues, file, `${label}: full snippet required (missing JSX usage).`);
273
- }
274
- }
275
- const imports = parseSnippetImports(snippet);
276
- validateComponentAllowlist(issues, file, label, snippet, imports, /* @__PURE__ */ new Set(), policy);
277
- }
278
- function validateFragmentSource(sourceFile, file, policy, issues) {
279
- const context = collectSourceContext(sourceFile);
280
- const defineCall = findDefineCall(sourceFile, "defineFragment");
281
- if (!defineCall) {
282
- return;
283
- }
284
- const arg = defineCall.arguments[0];
285
- if (!arg || !ts.isObjectLiteralExpression(arg)) {
286
- return;
287
- }
288
- const variantsExpr = findProperty(arg, "variants");
289
- if (!variantsExpr || !ts.isArrayLiteralExpression(variantsExpr)) {
290
- return;
291
- }
292
- for (const variantExpr of variantsExpr.elements) {
293
- if (!ts.isObjectLiteralExpression(variantExpr)) continue;
294
- const name = readStaticString(findProperty(variantExpr, "name")) ?? "Unknown";
295
- const labelPrefix = `variant "${name}"`;
296
- const codeExpr = findProperty(variantExpr, "code");
297
- const snippet = readStaticString(codeExpr);
298
- if (snippet) {
299
- validateSnippetString(issues, file, `${labelPrefix} snippet`, snippet, policy);
300
- } else {
301
- report(issues, file, `${labelPrefix}: missing explicit code snippet (variant.code).`);
302
- }
303
- if (policy.scope === "snippet+render") {
304
- const renderExpr = findProperty(variantExpr, "render");
305
- if (renderExpr) {
306
- const renderBody = readRenderBody(renderExpr, sourceFile);
307
- if (!renderBody) {
308
- report(issues, file, `${labelPrefix} render: expected a static render function.`);
309
- continue;
310
- }
311
- validateRawRules(issues, file, `${labelPrefix} render`, renderBody);
312
- validateComponentAllowlist(
313
- issues,
314
- file,
315
- `${labelPrefix} render`,
316
- renderBody,
317
- context.imports,
318
- context.localComponents,
319
- policy
320
- );
321
- }
322
- }
323
- }
324
- }
325
- function validateBlockSource(sourceFile, file, policy, issues) {
326
- const defineCall = findDefineCall(sourceFile, "defineBlock");
327
- if (!defineCall) {
328
- return;
329
- }
330
- const arg = defineCall.arguments[0];
331
- if (!arg || !ts.isObjectLiteralExpression(arg)) {
332
- return;
333
- }
334
- const codeExpr = findProperty(arg, "code");
335
- const snippet = readStaticString(codeExpr);
336
- if (!snippet) {
337
- report(issues, file, "block snippet: missing static code string.");
338
- return;
339
- }
340
- validateSnippetString(issues, file, "block snippet", snippet, policy);
341
- }
342
- function validateBlockPreviewExamples(sourceFile, file, policy, issues) {
343
- if (policy.scope !== "snippet+render") {
344
- return;
345
- }
346
- const code = sourceFile.text;
347
- const context = collectSourceContext(sourceFile);
348
- validateRawRules(issues, file, "block preview render", code);
349
- validateComponentAllowlist(
350
- issues,
351
- file,
352
- "block preview render",
353
- code,
354
- context.imports,
355
- context.localComponents,
356
- policy
357
- );
358
- }
359
- function sourceFileFromText(filePath, content) {
360
- return ts.createSourceFile(
361
- filePath,
362
- content,
363
- ts.ScriptTarget.Latest,
364
- true,
365
- ts.ScriptKind.TSX
366
- );
367
- }
368
- function sortAndFilterBatch(files, componentStart, componentLimit) {
369
- const getComponentName = (relativePath) => {
370
- const normalized = relativePath.replace(/\\/g, "/");
371
- const fileName = normalized.split("/").pop() ?? normalized;
372
- if (fileName.endsWith(BRAND.fileExtension)) {
373
- return fileName.slice(0, -BRAND.fileExtension.length);
374
- }
375
- return extractComponentName(relativePath);
376
- };
377
- const sorted = [...files].sort((a, b) => {
378
- const nameA = getComponentName(a.relativePath).toLowerCase();
379
- const nameB = getComponentName(b.relativePath).toLowerCase();
380
- return nameA.localeCompare(nameB);
381
- });
382
- if (!componentStart && !componentLimit) {
383
- return { selected: sorted };
384
- }
385
- const startName = componentStart?.toLowerCase();
386
- let startIndex = 0;
387
- if (startName) {
388
- const foundIndex = sorted.findIndex((file) => getComponentName(file.relativePath).toLowerCase() === startName);
389
- if (foundIndex === -1) {
390
- return {
391
- selected: [],
392
- warning: `Component start "${componentStart}" not found for snippet validation batch.`
393
- };
394
- }
395
- startIndex = foundIndex;
396
- }
397
- const limit = componentLimit && componentLimit > 0 ? componentLimit : sorted.length;
398
- return {
399
- selected: sorted.slice(startIndex, startIndex + limit)
400
- };
401
- }
402
- async function findBlockPreviewExamplesFile(configDir) {
403
- const candidates = [
404
- join(configDir, "apps/docs/src/app/(docs)/blocks/examples/index.tsx"),
405
- join(configDir, "../apps/docs/src/app/(docs)/blocks/examples/index.tsx"),
406
- join(configDir, "../../apps/docs/src/app/(docs)/blocks/examples/index.tsx")
407
- ];
408
- for (const candidate of candidates) {
409
- if (existsSync(candidate)) {
410
- return candidate;
411
- }
412
- }
413
- return null;
414
- }
415
- function toValidationResult(policy, issues) {
416
- if (policy.mode === "error") {
417
- return {
418
- errors: issues,
419
- warnings: []
420
- };
421
- }
422
- return {
423
- errors: [],
424
- warnings: issues
425
- };
426
- }
427
- async function validateSnippetPolicy(config, configDir, options = {}) {
428
- const policy = normalizePolicy(config.snippets, options);
429
- const issues = [];
430
- const discovered = await discoverFragmentFiles(config, configDir);
431
- const fragmentFiles = discovered.filter((file) => file.relativePath.endsWith(BRAND.fileExtension));
432
- const batchResult = sortAndFilterBatch(fragmentFiles, policy.componentStart, policy.componentLimit);
433
- if (batchResult.warning) {
434
- issues.push({ file: "snippets", message: batchResult.warning });
435
- }
436
- for (const file of batchResult.selected) {
437
- try {
438
- const content = await readFile(file.absolutePath, "utf-8");
439
- const sourceFile = sourceFileFromText(file.relativePath, content);
440
- validateFragmentSource(sourceFile, file.relativePath, policy, issues);
441
- } catch (error) {
442
- issues.push({
443
- file: file.relativePath,
444
- message: `Failed to validate fragment snippets: ${error instanceof Error ? error.message : String(error)}`
445
- });
446
- }
447
- }
448
- const isBatchOnly = Boolean(policy.componentStart || policy.componentLimit);
449
- if (!isBatchOnly) {
450
- try {
451
- const blockFiles = await discoverBlockFiles(configDir, config.exclude);
452
- for (const file of blockFiles) {
453
- try {
454
- const content = await readFile(file.absolutePath, "utf-8");
455
- const sourceFile = sourceFileFromText(file.relativePath, content);
456
- validateBlockSource(sourceFile, file.relativePath, policy, issues);
457
- } catch (error) {
458
- issues.push({
459
- file: file.relativePath,
460
- message: `Failed to validate block snippets: ${error instanceof Error ? error.message : String(error)}`
461
- });
462
- }
463
- }
464
- } catch (error) {
465
- issues.push({
466
- file: "blocks",
467
- message: `Failed to discover block files: ${error instanceof Error ? error.message : String(error)}`
468
- });
469
- }
470
- const blockPreviewFile = await findBlockPreviewExamplesFile(configDir);
471
- if (blockPreviewFile) {
472
- try {
473
- const content = await readFile(blockPreviewFile, "utf-8");
474
- const sourceFile = sourceFileFromText(blockPreviewFile, content);
475
- validateBlockPreviewExamples(sourceFile, blockPreviewFile, policy, issues);
476
- } catch (error) {
477
- issues.push({
478
- file: blockPreviewFile,
479
- message: `Failed to validate block preview examples: ${error instanceof Error ? error.message : String(error)}`
480
- });
481
- }
482
- }
483
- }
484
- return toValidationResult(policy, issues);
485
- }
486
-
487
- // src/core/auto-props.ts
488
- import { existsSync as existsSync2, statSync } from "fs";
489
- import { dirname, extname, join as join2, resolve } from "path";
490
- import ts2 from "typescript";
491
- function isFile(filePath) {
492
- if (!existsSync2(filePath)) return false;
493
- try {
494
- return statSync(filePath).isFile();
495
- } catch {
496
- return false;
497
- }
498
- }
499
- function resolveModulePath(basePath) {
500
- const candidates = [];
501
- const extension = extname(basePath);
502
- if (extension) {
503
- candidates.push(basePath);
504
- } else {
505
- candidates.push(
506
- `${basePath}.tsx`,
507
- `${basePath}.ts`,
508
- `${basePath}.jsx`,
509
- `${basePath}.js`,
510
- join2(basePath, "index.tsx"),
511
- join2(basePath, "index.ts"),
512
- join2(basePath, "index.jsx"),
513
- join2(basePath, "index.js")
514
- );
515
- }
516
- for (const candidate of candidates) {
517
- if (isFile(candidate)) {
518
- return resolve(candidate);
519
- }
520
- }
521
- return null;
522
- }
523
- function resolveComponentSourcePath(fragmentFileAbsolutePath, componentImportPath) {
524
- if (!componentImportPath) return null;
525
- if (!componentImportPath.startsWith(".")) return null;
526
- const fragmentDir = dirname(fragmentFileAbsolutePath);
527
- const basePath = resolve(fragmentDir, componentImportPath);
528
- return resolveModulePath(basePath);
529
- }
530
-
531
- // src/validators.ts
532
- import { readFile as readFile2 } from "fs/promises";
533
- async function validateSchema(config, configDir) {
534
- const files = await discoverFragmentFiles(config, configDir);
535
- const errors = [];
536
- const warnings = [];
537
- for (const file of files) {
538
- try {
539
- const fragment = await loadFragmentFile(file.absolutePath);
540
- if (!fragment) {
541
- errors.push({
542
- file: file.relativePath,
543
- message: "No default export found",
544
- details: `Fragment files must have a default export from defineFragment()`
545
- });
546
- continue;
547
- }
548
- const result = fragmentDefinitionSchema.safeParse(fragment);
549
- if (!result.success) {
550
- const details = result.error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join("; ");
551
- errors.push({
552
- file: file.relativePath,
553
- message: "Invalid fragment schema",
554
- details
555
- });
556
- }
557
- } catch (error) {
558
- errors.push({
559
- file: file.relativePath,
560
- message: "Failed to load fragment file",
561
- details: error instanceof Error ? error.message : String(error)
562
- });
563
- }
564
- }
565
- return {
566
- valid: errors.length === 0,
567
- errors,
568
- warnings
569
- };
570
- }
571
- async function validateCoverage(config, configDir) {
572
- const fragmentFiles = await discoverFragmentFiles(config, configDir);
573
- const componentFiles = await discoverComponentFiles(config, configDir);
574
- const errors = [];
575
- const warnings = [];
576
- const documentedComponents = /* @__PURE__ */ new Set();
577
- for (const file of fragmentFiles) {
578
- try {
579
- const fragment = await loadFragmentFile(file.absolutePath);
580
- if (fragment?.meta?.name) {
581
- documentedComponents.add(fragment.meta.name);
582
- }
583
- } catch {
584
- }
585
- }
586
- for (const file of componentFiles) {
587
- const componentName = extractComponentName(file.relativePath);
588
- const fragmentPath = file.relativePath.replace(
589
- /\.(tsx?|jsx?)$/,
590
- BRAND.fileExtension
591
- );
592
- const hasFragmentFile = fragmentFiles.some(
593
- (s) => s.relativePath === fragmentPath
594
- );
595
- if (!hasFragmentFile && !documentedComponents.has(componentName)) {
596
- warnings.push({
597
- file: file.relativePath,
598
- message: `Component "${componentName}" has no fragment documentation`
599
- });
600
- }
601
- }
602
- return {
603
- valid: errors.length === 0,
604
- errors,
605
- warnings
606
- };
607
- }
608
- async function validateAll(config, configDir, options = {}) {
609
- const [schemaResult, coverageResult] = await Promise.all([
610
- validateSchema(config, configDir),
611
- validateCoverage(config, configDir)
612
- ]);
613
- if (options.snippets === false) {
614
- return {
615
- valid: schemaResult.valid && coverageResult.valid,
616
- errors: [...schemaResult.errors, ...coverageResult.errors],
617
- warnings: [...schemaResult.warnings, ...coverageResult.warnings]
618
- };
619
- }
620
- const snippetOptions = {
621
- ...options.snippetMode && { mode: options.snippetMode },
622
- ...options.componentStart && { componentStart: options.componentStart },
623
- ...typeof options.componentLimit === "number" ? { componentLimit: options.componentLimit } : {}
624
- };
625
- const snippetResult = await validateSnippetPolicy(config, configDir, snippetOptions);
626
- return {
627
- valid: schemaResult.valid && coverageResult.valid && snippetResult.errors.length === 0,
628
- errors: [...schemaResult.errors, ...coverageResult.errors, ...snippetResult.errors],
629
- warnings: [...schemaResult.warnings, ...coverageResult.warnings, ...snippetResult.warnings]
630
- };
631
- }
632
- async function validateSnippets(config, configDir, options = {}) {
633
- const snippetResult = await validateSnippetPolicy(config, configDir, {
634
- ...options.snippetMode && { mode: options.snippetMode },
635
- ...options.componentStart && { componentStart: options.componentStart },
636
- ...typeof options.componentLimit === "number" ? { componentLimit: options.componentLimit } : {}
637
- });
638
- return {
639
- valid: snippetResult.errors.length === 0,
640
- errors: snippetResult.errors,
641
- warnings: snippetResult.warnings
642
- };
643
- }
644
- async function validateDrift(config, configDir, options = {}) {
645
- const fragmentFiles = await discoverFragmentFiles(config, configDir);
646
- const errors = [];
647
- const warnings = [];
648
- const reports = [];
649
- if (fragmentFiles.length === 0) {
650
- return { valid: true, errors, warnings, reports };
651
- }
652
- const extractor = createComponentExtractor(options.tsconfig);
653
- try {
654
- for (const file of fragmentFiles) {
655
- try {
656
- const fragment = await loadFragmentFile(file.absolutePath);
657
- if (!fragment?.meta?.name) continue;
658
- const fileContent = await readFile2(file.absolutePath, "utf-8");
659
- const parsed = parseFragmentFile(fileContent, file.absolutePath);
660
- if (!parsed.componentImport) continue;
661
- const sourcePath = resolveComponentSourcePath(file.absolutePath, parsed.componentImport);
662
- if (!sourcePath) continue;
663
- const meta = extractor.extract(sourcePath, fragment.meta.name);
664
- if (!meta) continue;
665
- const drifts = diffProps(fragment.props, meta.props);
666
- let compositionDrift = null;
667
- const fragmentAi = fragment.ai;
668
- if (meta.composition && !fragmentAi?.compositionPattern) {
669
- compositionDrift = `Source has "${meta.composition.pattern}" composition but fragment has no ai.compositionPattern`;
670
- } else if (!meta.composition && fragmentAi?.compositionPattern) {
671
- compositionDrift = `Fragment declares "${fragmentAi.compositionPattern}" but source has no compound pattern`;
672
- } else if (meta.composition && fragmentAi?.compositionPattern && meta.composition.pattern !== fragmentAi.compositionPattern) {
673
- compositionDrift = `Composition pattern changed: fragment="${fragmentAi.compositionPattern}" source="${meta.composition.pattern}"`;
674
- }
675
- if (drifts.length > 0 || compositionDrift) {
676
- const report2 = {
677
- component: fragment.meta.name,
678
- file: file.relativePath,
679
- drifts,
680
- compositionDrift
681
- };
682
- reports.push(report2);
683
- for (const drift of drifts) {
684
- if (drift.kind === "removed") {
685
- errors.push({
686
- file: file.relativePath,
687
- message: `Prop "${drift.prop}" documented in fragment but removed from source`,
688
- details: `Fragment: ${drift.fragment} | Source: (not found)`
689
- });
690
- } else if (drift.kind === "added") {
691
- warnings.push({
692
- file: file.relativePath,
693
- message: `Prop "${drift.prop}" exists in source but not documented in fragment`
694
- });
695
- } else {
696
- warnings.push({
697
- file: file.relativePath,
698
- message: `Prop "${drift.prop}" ${drift.kind.replace("_", " ")}: fragment=${drift.fragment} source=${drift.source}`
699
- });
700
- }
701
- }
702
- if (compositionDrift) {
703
- warnings.push({
704
- file: file.relativePath,
705
- message: compositionDrift
706
- });
707
- }
708
- }
709
- } catch {
710
- }
711
- }
712
- } finally {
713
- extractor.dispose();
714
- }
715
- return {
716
- valid: errors.length === 0,
717
- errors,
718
- warnings,
719
- reports
720
- };
721
- }
722
- function diffProps(fragmentProps, sourceProps) {
723
- const drifts = [];
724
- const localSourceProps = Object.fromEntries(
725
- Object.entries(sourceProps).filter(([_, p]) => p.source === "local")
726
- );
727
- for (const [name, sourceProp] of Object.entries(localSourceProps)) {
728
- if (!(name in fragmentProps)) {
729
- drifts.push({
730
- prop: name,
731
- kind: "added",
732
- source: sourceProp.type,
733
- fragment: "(not documented)"
734
- });
735
- }
736
- }
737
- for (const [name, fragProp] of Object.entries(fragmentProps)) {
738
- if (!(name in localSourceProps)) {
739
- drifts.push({
740
- prop: name,
741
- kind: "removed",
742
- source: "(not found)",
743
- fragment: String(fragProp.type ?? "unknown")
744
- });
745
- continue;
746
- }
747
- const sourceProp = localSourceProps[name];
748
- if (fragProp.type && fragProp.type !== sourceProp.typeKind) {
749
- drifts.push({
750
- prop: name,
751
- kind: "type_changed",
752
- source: sourceProp.typeKind,
753
- fragment: String(fragProp.type)
754
- });
755
- }
756
- if (fragProp.required !== void 0 && fragProp.required !== sourceProp.required) {
757
- drifts.push({
758
- prop: name,
759
- kind: "required_changed",
760
- source: String(sourceProp.required),
761
- fragment: String(fragProp.required)
762
- });
763
- }
764
- if (fragProp.values && sourceProp.values) {
765
- const fragSet = new Set(fragProp.values);
766
- const srcSet = new Set(sourceProp.values);
767
- const added = sourceProp.values.filter((v) => !fragSet.has(v));
768
- const removed = Array.from(fragProp.values).filter((v) => !srcSet.has(v));
769
- if (added.length > 0 || removed.length > 0) {
770
- drifts.push({
771
- prop: name,
772
- kind: "values_changed",
773
- source: sourceProp.values.join(", "),
774
- fragment: Array.from(fragProp.values).join(", ")
775
- });
776
- }
777
- }
778
- if (fragProp.default !== void 0 && sourceProp.default !== void 0) {
779
- if (String(fragProp.default) !== sourceProp.default) {
780
- drifts.push({
781
- prop: name,
782
- kind: "default_changed",
783
- source: sourceProp.default,
784
- fragment: String(fragProp.default)
785
- });
786
- }
787
- }
788
- }
789
- return drifts;
790
- }
791
-
792
- // src/build.ts
793
- import { readFile as readFile3, writeFile, mkdir } from "fs/promises";
794
- import { resolve as resolve5, join as join5 } from "path";
795
- import { existsSync as existsSync6 } from "fs";
796
-
797
- // src/core/token-resolver.ts
798
- import { resolve as resolve2, dirname as dirname2, basename } from "path";
799
- import { existsSync as existsSync3, readdirSync } from "fs";
800
- function roundRgbValues(value) {
801
- return value.replace(
802
- /rgb\(([^)]+)\)/g,
803
- (_full, inner) => {
804
- const parts = inner.split(",").map((p) => p.trim());
805
- const rounded = parts.map((p) => {
806
- const num = parseFloat(p);
807
- return isNaN(num) ? p : String(Math.round(num));
808
- });
809
- return `rgb(${rounded.join(", ")})`;
810
- }
811
- ).replace(
812
- /rgba\(([^)]+)\)/g,
813
- (_full, inner) => {
814
- const parts = inner.split(",").map((p) => p.trim());
815
- const rounded = parts.map((p, i) => {
816
- if (i >= 3) return p;
817
- const num = parseFloat(p);
818
- return isNaN(num) ? p : String(Math.round(num));
819
- });
820
- return `rgba(${rounded.join(", ")})`;
821
- }
822
- );
823
- }
824
- async function resolveTokensWithSass(unresolvedTokens, tokensDir) {
825
- const resolvedMap = /* @__PURE__ */ new Map();
826
- const needsResolution = unresolvedTokens.filter(
827
- (t) => t.value.includes("#{") || t.value.includes("$")
828
- );
829
- if (needsResolution.length === 0) {
830
- return resolvedMap;
831
- }
832
- try {
833
- const sass = await import("./sass.node-4XJK6YBF.js");
834
- const variablesPath = findVariablesFile(tokensDir);
835
- if (!variablesPath) {
836
- return resolvedMap;
837
- }
838
- const fileName = basename(variablesPath);
839
- const moduleName = fileName.replace(/^_/, "").replace(/\.scss$/, "");
840
- const scssSource = `
841
- @use '${moduleName}' as vars;
842
- :root { @include vars.fui-css-variables; }
843
- `;
844
- const compiled = sass.compileString(scssSource, {
845
- loadPaths: [tokensDir, dirname2(tokensDir)],
846
- style: "expanded",
847
- // Suppress sass deprecation warnings during build
848
- logger: { warn() {
849
- }, debug() {
850
- } }
851
- });
852
- const cssVarRegex = /(--[\w-]+)\s*:\s*([^;]+)/g;
853
- let match;
854
- const allResolved = /* @__PURE__ */ new Map();
855
- while ((match = cssVarRegex.exec(compiled.css)) !== null) {
856
- allResolved.set(match[1], roundRgbValues(match[2].trim()));
857
- }
858
- for (const token of needsResolution) {
859
- const value = allResolved.get(token.name);
860
- if (value !== void 0) {
861
- resolvedMap.set(token.name, value);
862
- }
863
- }
864
- } catch {
865
- }
866
- return resolvedMap;
867
- }
868
- function findVariablesFile(tokensDir) {
869
- const candidates = ["_variables.scss", "variables.scss"];
870
- for (const name of candidates) {
871
- const path = resolve2(tokensDir, name);
872
- if (existsSync3(path)) {
873
- return path;
874
- }
875
- }
876
- try {
877
- const files = readdirSync(tokensDir).filter((f) => f.endsWith(".scss"));
878
- for (const file of files) {
879
- const path = resolve2(tokensDir, file);
880
- if (file.includes("variables") || file.includes("tokens")) {
881
- return path;
882
- }
883
- }
884
- } catch {
885
- }
886
- return null;
887
- }
888
-
889
- // src/core/graph-extractor.ts
890
- import ts3 from "typescript";
891
- import { readFileSync, existsSync as existsSync4 } from "fs";
892
- import { join as join3 } from "path";
893
- import { readdirSync as readdirSync2 } from "fs";
894
- import { EDGE_TYPE_WEIGHTS, computeHealthFromData } from "@fragments-sdk/context/graph";
895
- async function buildComponentGraph(fragments, blocks, componentDir, options) {
896
- const knownComponents = new Set(Object.keys(fragments));
897
- const allEdges = [];
898
- const autoDetected = /* @__PURE__ */ new Map();
899
- const warnings = [];
900
- if (!options?.skipSourceAnalysis) {
901
- const sourceEdges = extractImportAndHookEdges(componentDir, knownComponents);
902
- allEdges.push(...sourceEdges);
903
- const subComponentResults = extractSubComponents(componentDir, knownComponents);
904
- for (const [name, subs] of subComponentResults) {
905
- autoDetected.set(name, {
906
- ...autoDetected.get(name),
907
- subComponents: subs,
908
- compositionPattern: subs.length > 0 ? "compound" : "simple"
909
- });
910
- }
911
- }
912
- const jsxEdges = extractJsxUsageEdges(fragments, knownComponents);
913
- allEdges.push(...jsxEdges);
914
- const blockEdges = extractBlockEdges(blocks);
915
- allEdges.push(...blockEdges);
916
- const relationEdges = extractRelationEdges(fragments);
917
- allEdges.push(...relationEdges);
918
- const requiredChildrenMap = inferRequiredChildren(fragments, autoDetected);
919
- for (const [name, children] of requiredChildrenMap) {
920
- const existing = autoDetected.get(name) ?? {};
921
- autoDetected.set(name, { ...existing, requiredChildren: children });
922
- }
923
- const patternsMap = generateCommonPatterns(fragments, autoDetected);
924
- for (const [name, patterns] of patternsMap) {
925
- const existing = autoDetected.get(name) ?? {};
926
- autoDetected.set(name, { ...existing, commonPatterns: patterns });
927
- }
928
- const mergedEdges = mergeAndDeduplicate(allEdges);
929
- const nodes = Object.entries(fragments).map(([name, fragment]) => {
930
- const detected = autoDetected.get(name);
931
- return {
932
- name,
933
- category: fragment.meta.category,
934
- status: fragment.meta.status ?? "stable",
935
- compositionPattern: fragment.ai?.compositionPattern ?? detected?.compositionPattern,
936
- subComponents: fragment.ai?.subComponents ?? detected?.subComponents
937
- };
938
- });
939
- const blockIndex = /* @__PURE__ */ new Map();
940
- for (const [blockName, block] of Object.entries(blocks)) {
941
- for (const comp of block.components) {
942
- const existing = blockIndex.get(comp);
943
- if (existing) existing.push(blockName);
944
- else blockIndex.set(comp, [blockName]);
945
- }
946
- }
947
- const health = computeHealthFromData(nodes, mergedEdges, blockIndex);
948
- for (const [name, fragment] of Object.entries(fragments)) {
949
- const detected = autoDetected.get(name);
950
- if (!detected) continue;
951
- if (fragment.ai?.subComponents && detected.subComponents) {
952
- const declared = new Set(fragment.ai.subComponents);
953
- const found = new Set(detected.subComponents);
954
- const missing = detected.subComponents.filter((s) => !declared.has(s));
955
- const extra = fragment.ai.subComponents.filter((s) => !found.has(s));
956
- if (missing.length > 0) {
957
- warnings.push(
958
- `${name}: declares ${declared.size} subComponents but code has ${found.size}. Missing from declaration: ${missing.join(", ")}`
959
- );
960
- }
961
- if (extra.length > 0) {
962
- warnings.push(
963
- `${name}: declares subComponents [${extra.join(", ")}] not found in Object.assign`
964
- );
965
- }
966
- }
967
- }
968
- return {
969
- graph: { nodes, edges: mergedEdges, health },
970
- autoDetected,
971
- warnings
972
- };
973
- }
974
- function extractImportAndHookEdges(componentDir, knownComponents) {
975
- const edges = [];
976
- for (const componentName of knownComponents) {
977
- const indexPath = findComponentIndex(componentDir, componentName);
978
- if (!indexPath) continue;
979
- let sourceText;
980
- try {
981
- sourceText = readFileSync(indexPath, "utf-8");
982
- } catch {
983
- continue;
984
- }
985
- const sourceFile = ts3.createSourceFile(
986
- indexPath,
987
- sourceText,
988
- ts3.ScriptTarget.Latest,
989
- true,
990
- indexPath.endsWith(".tsx") ? ts3.ScriptKind.TSX : ts3.ScriptKind.TS
991
- );
992
- const visitNode = (node) => {
993
- if (ts3.isImportDeclaration(node)) {
994
- const moduleSpecifier = node.moduleSpecifier;
995
- if (ts3.isStringLiteral(moduleSpecifier)) {
996
- const importPath = moduleSpecifier.text;
997
- if (importPath.startsWith(".") || importPath.startsWith("/")) {
998
- const clause = node.importClause;
999
- if (clause) {
1000
- if (clause.name && isPascalCase(clause.name.text) && knownComponents.has(clause.name.text)) {
1001
- edges.push({
1002
- source: componentName,
1003
- target: clause.name.text,
1004
- type: "imports",
1005
- weight: EDGE_TYPE_WEIGHTS["imports"],
1006
- provenance: `source:${componentName}/index.tsx`
1007
- });
1008
- }
1009
- if (clause.namedBindings && ts3.isNamedImports(clause.namedBindings)) {
1010
- for (const element of clause.namedBindings.elements) {
1011
- const name = element.name.text;
1012
- if (isPascalCase(name) && knownComponents.has(name) && name !== componentName) {
1013
- edges.push({
1014
- source: componentName,
1015
- target: name,
1016
- type: "imports",
1017
- weight: EDGE_TYPE_WEIGHTS["imports"],
1018
- provenance: `source:${componentName}/index.tsx`
1019
- });
1020
- }
1021
- }
1022
- }
1023
- }
1024
- }
1025
- }
1026
- }
1027
- if (ts3.isCallExpression(node) && ts3.isIdentifier(node.expression)) {
1028
- const callName = node.expression.text;
1029
- const hookMatch = callName.match(/^use([A-Z][a-zA-Z]*)$/);
1030
- if (hookMatch) {
1031
- const hookTarget = hookMatch[1];
1032
- if (knownComponents.has(hookTarget) && hookTarget !== componentName) {
1033
- edges.push({
1034
- source: componentName,
1035
- target: hookTarget,
1036
- type: "hook-depends",
1037
- weight: EDGE_TYPE_WEIGHTS["hook-depends"],
1038
- provenance: `source:${componentName}/index.tsx`
1039
- });
1040
- }
1041
- }
1042
- }
1043
- ts3.forEachChild(node, visitNode);
1044
- };
1045
- ts3.forEachChild(sourceFile, visitNode);
1046
- }
1047
- return edges;
1048
- }
1049
- function extractSubComponents(componentDir, knownComponents) {
1050
- const result = /* @__PURE__ */ new Map();
1051
- for (const componentName of knownComponents) {
1052
- const indexPath = findComponentIndex(componentDir, componentName);
1053
- if (!indexPath) continue;
1054
- let sourceText;
1055
- try {
1056
- sourceText = readFileSync(indexPath, "utf-8");
1057
- } catch {
1058
- continue;
1059
- }
1060
- if (!sourceText.includes("Object.assign")) continue;
1061
- const sourceFile = ts3.createSourceFile(
1062
- indexPath,
1063
- sourceText,
1064
- ts3.ScriptTarget.Latest,
1065
- true,
1066
- indexPath.endsWith(".tsx") ? ts3.ScriptKind.TSX : ts3.ScriptKind.TS
1067
- );
1068
- const subComponents = [];
1069
- const visitNode = (node) => {
1070
- if (ts3.isCallExpression(node) && ts3.isPropertyAccessExpression(node.expression) && ts3.isIdentifier(node.expression.expression) && node.expression.expression.text === "Object" && node.expression.name.text === "assign" && node.arguments.length >= 2) {
1071
- const propsArg = node.arguments[1];
1072
- if (ts3.isObjectLiteralExpression(propsArg)) {
1073
- for (const prop of propsArg.properties) {
1074
- if (ts3.isShorthandPropertyAssignment(prop)) {
1075
- subComponents.push(prop.name.text);
1076
- } else if (ts3.isPropertyAssignment(prop) && ts3.isIdentifier(prop.name)) {
1077
- subComponents.push(prop.name.text);
1078
- }
1079
- }
1080
- }
1081
- }
1082
- ts3.forEachChild(node, visitNode);
1083
- };
1084
- ts3.forEachChild(sourceFile, visitNode);
1085
- if (subComponents.length > 0) {
1086
- result.set(componentName, subComponents);
1087
- }
1088
- }
1089
- return result;
1090
- }
1091
- function extractJsxUsageEdges(fragments, knownComponents) {
1092
- const edges = [];
1093
- const jsxTagRegex = /<([A-Z][a-zA-Z]*(?:\.[A-Z][a-zA-Z]*)?)/g;
1094
- for (const [name, fragment] of Object.entries(fragments)) {
1095
- const usedComponents = /* @__PURE__ */ new Set();
1096
- for (const variant of fragment.variants) {
1097
- if (!variant.code) continue;
1098
- let match;
1099
- jsxTagRegex.lastIndex = 0;
1100
- while ((match = jsxTagRegex.exec(variant.code)) !== null) {
1101
- let tagName = match[1];
1102
- if (tagName.includes(".")) {
1103
- tagName = tagName.split(".")[0];
1104
- }
1105
- if (knownComponents.has(tagName) && tagName !== name) {
1106
- usedComponents.add(tagName);
1107
- }
1108
- }
1109
- }
1110
- for (const target of usedComponents) {
1111
- edges.push({
1112
- source: name,
1113
- target,
1114
- type: "renders",
1115
- weight: EDGE_TYPE_WEIGHTS["renders"],
1116
- provenance: `variant:${name}`
1117
- });
1118
- }
1119
- }
1120
- return edges;
1121
- }
1122
- function extractBlockEdges(blocks) {
1123
- const edges = [];
1124
- for (const [blockName, block] of Object.entries(blocks)) {
1125
- const components = block.components;
1126
- for (let i = 0; i < components.length; i++) {
1127
- for (let j = i + 1; j < components.length; j++) {
1128
- edges.push({
1129
- source: components[i],
1130
- target: components[j],
1131
- type: "composes",
1132
- weight: EDGE_TYPE_WEIGHTS["composes"],
1133
- provenance: `block:${blockName}`
1134
- });
1135
- }
1136
- }
1137
- }
1138
- return edges;
1139
- }
1140
- function extractRelationEdges(fragments) {
1141
- const edges = [];
1142
- const relationToEdgeType = {
1143
- parent: "parent-of",
1144
- child: "parent-of",
1145
- // reversed: if A declares child B, edge is A parent-of B
1146
- composition: "composes",
1147
- alternative: "alternative-to",
1148
- sibling: "sibling-of"
1149
- };
1150
- for (const [name, fragment] of Object.entries(fragments)) {
1151
- if (!fragment.relations) continue;
1152
- for (const rel of fragment.relations) {
1153
- const edgeType = relationToEdgeType[rel.relationship];
1154
- if (!edgeType) continue;
1155
- let source;
1156
- let target;
1157
- if (rel.relationship === "parent") {
1158
- source = rel.component;
1159
- target = name;
1160
- } else {
1161
- source = name;
1162
- target = rel.component;
1163
- }
1164
- edges.push({
1165
- source,
1166
- target,
1167
- type: edgeType,
1168
- weight: EDGE_TYPE_WEIGHTS[edgeType],
1169
- note: rel.note,
1170
- provenance: "relation"
1171
- });
1172
- }
1173
- }
1174
- return edges;
1175
- }
1176
- function inferRequiredChildren(fragments, autoDetected) {
1177
- const result = /* @__PURE__ */ new Map();
1178
- for (const [name, fragment] of Object.entries(fragments)) {
1179
- const detected = autoDetected.get(name);
1180
- const subs = detected?.subComponents ?? fragment.ai?.subComponents;
1181
- if (!subs || subs.length === 0) continue;
1182
- const variantsWithCode = fragment.variants.filter((v) => v.code);
1183
- if (variantsWithCode.length === 0) continue;
1184
- const required = [];
1185
- for (const sub of subs) {
1186
- const inAll = variantsWithCode.every((v) => {
1187
- const patterns = [
1188
- new RegExp(`<${name}\\.${sub}[\\s/>]`),
1189
- new RegExp(`<${sub}[\\s/>]`)
1190
- ];
1191
- return patterns.some((p) => p.test(v.code));
1192
- });
1193
- if (inAll) required.push(sub);
1194
- }
1195
- if (required.length > 0) {
1196
- result.set(name, required);
1197
- }
1198
- }
1199
- return result;
1200
- }
1201
- function generateCommonPatterns(fragments, autoDetected) {
1202
- const result = /* @__PURE__ */ new Map();
1203
- for (const [name, fragment] of Object.entries(fragments)) {
1204
- const detected = autoDetected.get(name);
1205
- const subs = detected?.subComponents ?? fragment.ai?.subComponents;
1206
- if (!subs || subs.length === 0) continue;
1207
- const firstVariant = fragment.variants.find((v) => v.code);
1208
- if (!firstVariant?.code) continue;
1209
- const usedSubs = [];
1210
- for (const sub of subs) {
1211
- const patterns = [
1212
- new RegExp(`<${name}\\.${sub}`),
1213
- new RegExp(`<${sub}[\\s/>]`)
1214
- ];
1215
- if (patterns.some((p) => p.test(firstVariant.code))) {
1216
- usedSubs.push(sub);
1217
- }
1218
- }
1219
- if (usedSubs.length > 0) {
1220
- const pattern = `<${name}>
1221
- ${usedSubs.map((s) => ` <${name}.${s}>...</${name}.${s}>`).join("\n")}
1222
- </${name}>`;
1223
- result.set(name, [pattern]);
1224
- }
1225
- }
1226
- return result;
1227
- }
1228
- function mergeAndDeduplicate(edges) {
1229
- const edgeMap = /* @__PURE__ */ new Map();
1230
- for (const edge of edges) {
1231
- const key = `${edge.source}\u2192${edge.target}:${edge.type}`;
1232
- const existing = edgeMap.get(key);
1233
- if (!existing || edge.weight > existing.weight) {
1234
- edgeMap.set(key, edge);
1235
- }
1236
- }
1237
- return [...edgeMap.values()];
1238
- }
1239
- function isPascalCase(name) {
1240
- return /^[A-Z][a-zA-Z0-9]*$/.test(name);
1241
- }
1242
- function findComponentIndex(componentDir, componentName) {
1243
- const candidates = [
1244
- join3(componentDir, componentName, "index.tsx"),
1245
- join3(componentDir, componentName, "index.ts"),
1246
- join3(componentDir, componentName, `${componentName}.tsx`),
1247
- join3(componentDir, componentName, `${componentName}.ts`)
1248
- ];
1249
- for (const candidate of candidates) {
1250
- if (existsSync4(candidate)) {
1251
- return candidate;
1252
- }
1253
- }
1254
- try {
1255
- const entries = readdirSync2(componentDir, { withFileTypes: true });
1256
- for (const entry of entries) {
1257
- if (entry.isDirectory() && entry.name === componentName) {
1258
- const subCandidates = [
1259
- join3(componentDir, entry.name, "index.tsx"),
1260
- join3(componentDir, entry.name, "index.ts")
1261
- ];
1262
- for (const sc of subCandidates) {
1263
- if (existsSync4(sc)) return sc;
1264
- }
1265
- }
1266
- }
1267
- } catch {
1268
- }
1269
- return null;
1270
- }
1271
-
1272
- // src/build.ts
1273
- import { serializeGraph } from "@fragments-sdk/context/graph";
1274
-
1275
- // src/core/bundle-measurer.ts
1276
- import { build } from "esbuild";
1277
- import { gzipSync } from "zlib";
1278
- import { resolve as resolve4, dirname as dirname3, join as join4, basename as basename3 } from "path";
1279
- import { existsSync as existsSync5 } from "fs";
1280
- function resolveEntryPoint(fragmentFilePath, configDir) {
1281
- const absPath = resolve4(configDir, fragmentFilePath);
1282
- const dir = dirname3(absPath);
1283
- const candidates = ["index.tsx", "index.ts", "index.jsx", "index.js"];
1284
- for (const candidate of candidates) {
1285
- const path = join4(dir, candidate);
1286
- if (existsSync5(path)) return path;
1287
- }
1288
- return null;
1289
- }
1290
- function labelForPath(filePath) {
1291
- const lastNmIdx = filePath.lastIndexOf("node_modules/");
1292
- if (lastNmIdx >= 0) {
1293
- const afterNm = filePath.slice(lastNmIdx + "node_modules/".length);
1294
- if (afterNm.startsWith("@")) {
1295
- const parts = afterNm.split("/");
1296
- return parts.slice(0, 2).join("/");
1297
- }
1298
- return afterNm.split("/")[0];
1299
- }
1300
- const componentsIdx = filePath.indexOf("components/");
1301
- if (componentsIdx >= 0) {
1302
- const afterComponents = filePath.slice(componentsIdx + "components/".length);
1303
- const componentName = afterComponents.split("/")[0];
1304
- return componentName;
1305
- }
1306
- const srcIdx = filePath.indexOf("src/");
1307
- if (srcIdx >= 0) return filePath.slice(srcIdx);
1308
- return filePath;
1309
- }
1310
- function groupImportsByDirectDep(metafile, entryPoint) {
1311
- const inputs = metafile.inputs;
1312
- const outputKey = Object.keys(metafile.outputs)[0];
1313
- const outputMeta = outputKey ? metafile.outputs[outputKey] : void 0;
1314
- if (!outputMeta?.inputs) return [];
1315
- const bytesMap = /* @__PURE__ */ new Map();
1316
- for (const [path, info] of Object.entries(outputMeta.inputs)) {
1317
- if (info.bytesInOutput > 0) {
1318
- bytesMap.set(path, info.bytesInOutput);
1319
- }
1320
- }
1321
- let entryKey;
1322
- for (const key of Object.keys(inputs)) {
1323
- if (key === entryPoint || entryPoint.endsWith(key) || key.endsWith(basename3(entryPoint))) {
1324
- const entryDir = dirname3(entryPoint);
1325
- if (key.includes(basename3(entryDir))) {
1326
- entryKey = key;
1327
- break;
1328
- }
1329
- }
1330
- }
1331
- if (!entryKey) {
1332
- const entryBasename = basename3(dirname3(entryPoint));
1333
- for (const key of Object.keys(inputs)) {
1334
- if (key.includes(`/${entryBasename}/index.`)) {
1335
- entryKey = key;
1336
- break;
1337
- }
1338
- }
1339
- }
1340
- if (!entryKey || !inputs[entryKey]) {
1341
- return groupByPackage(bytesMap);
1342
- }
1343
- const directImports = inputs[entryKey].imports.map((imp) => imp.path).filter((p) => inputs[p]);
1344
- const claimed = /* @__PURE__ */ new Set();
1345
- claimed.add(entryKey);
1346
- const groupMap = /* @__PURE__ */ new Map();
1347
- for (const directPath of directImports) {
1348
- if (claimed.has(directPath)) continue;
1349
- const queue = [directPath];
1350
- const reachable = /* @__PURE__ */ new Set();
1351
- while (queue.length > 0) {
1352
- const current = queue.pop();
1353
- if (reachable.has(current) || claimed.has(current)) continue;
1354
- reachable.add(current);
1355
- claimed.add(current);
1356
- const entry = inputs[current];
1357
- if (entry?.imports) {
1358
- for (const imp of entry.imports) {
1359
- if (inputs[imp.path] && !claimed.has(imp.path)) {
1360
- queue.push(imp.path);
1361
- }
1362
- }
1363
- }
1364
- }
1365
- let totalBytes = 0;
1366
- for (const path of reachable) {
1367
- totalBytes += bytesMap.get(path) ?? 0;
1368
- }
1369
- if (totalBytes > 0) {
1370
- const label = labelForPath(directPath);
1371
- const existing = groupMap.get(label);
1372
- if (existing) {
1373
- existing.bytes += totalBytes;
1374
- } else {
1375
- const entry = { path: label, bytes: totalBytes };
1376
- groupMap.set(label, entry);
1377
- }
1378
- }
1379
- }
1380
- const entryLabel = labelForPath(entryKey);
1381
- const selfLabel = entryLabel + " (self)";
1382
- let selfBytes = bytesMap.get(entryKey) ?? 0;
1383
- const siblingGroup = groupMap.get(entryLabel);
1384
- if (siblingGroup) {
1385
- selfBytes += siblingGroup.bytes;
1386
- groupMap.delete(entryLabel);
1387
- }
1388
- if (selfBytes > 0) {
1389
- groupMap.set(selfLabel, { path: selfLabel, bytes: selfBytes });
1390
- }
1391
- let unclaimedBytes = 0;
1392
- for (const [path, bytes] of bytesMap) {
1393
- if (!claimed.has(path)) unclaimedBytes += bytes;
1394
- }
1395
- if (unclaimedBytes > 0) {
1396
- groupMap.set("(other)", { path: "(other)", bytes: unclaimedBytes });
1397
- }
1398
- return [...groupMap.values()].sort((a, b) => b.bytes - a.bytes);
1399
- }
1400
- function groupByPackage(bytesMap) {
1401
- const groups = /* @__PURE__ */ new Map();
1402
- for (const [path, bytes] of bytesMap) {
1403
- const label = labelForPath(path);
1404
- const key = label.includes("/") && !label.startsWith("components/") ? label.split("/").slice(0, label.startsWith("@") ? 2 : 1).join("/") : label;
1405
- groups.set(key, (groups.get(key) ?? 0) + bytes);
1406
- }
1407
- return [...groups.entries()].map(([path, bytes]) => ({ path, bytes })).sort((a, b) => b.bytes - a.bytes);
1408
- }
1409
- async function measureSingleComponent(entryPoint, name) {
1410
- const result = await build({
1411
- entryPoints: [entryPoint],
1412
- bundle: true,
1413
- write: false,
1414
- minify: true,
1415
- metafile: true,
1416
- format: "esm",
1417
- target: "es2020",
1418
- platform: "browser",
1419
- treeShaking: true,
1420
- external: [
1421
- "react",
1422
- "react-dom",
1423
- "react/jsx-runtime",
1424
- "react/jsx-dev-runtime",
1425
- // Optional peer deps — excluded from measurement
1426
- "recharts",
1427
- "shiki",
1428
- "react-day-picker",
1429
- "@tanstack/react-table",
1430
- "date-fns",
1431
- "@base-ui-components/*",
1432
- "@base-ui/react/*"
1433
- ],
1434
- loader: {
1435
- ".scss": "empty",
1436
- ".css": "empty",
1437
- ".svg": "empty",
1438
- ".png": "empty",
1439
- ".jpg": "empty",
1440
- ".gif": "empty",
1441
- ".woff": "empty",
1442
- ".woff2": "empty",
1443
- ".ttf": "empty",
1444
- ".eot": "empty"
1445
- },
1446
- logLevel: "silent"
1447
- });
1448
- const output = result.outputFiles[0];
1449
- const rawBytes = output.contents.byteLength;
1450
- const gzipBytes = gzipSync(output.contents).byteLength;
1451
- const imports = result.metafile ? groupImportsByDirectDep(result.metafile, entryPoint) : void 0;
1452
- return { name, rawBytes, gzipBytes, imports };
1453
- }
1454
- async function measureBundleSizes(fragments, configDir, options = {}) {
1455
- const concurrency = options.concurrency ?? 4;
1456
- const measurements = /* @__PURE__ */ new Map();
1457
- const errors = [];
1458
- const start = Date.now();
1459
- const entries = [];
1460
- for (const [name, fragment] of Object.entries(fragments)) {
1461
- const entryPoint = resolveEntryPoint(fragment.filePath, configDir);
1462
- if (entryPoint) {
1463
- entries.push({ name, entryPoint });
1464
- } else {
1465
- errors.push({
1466
- name,
1467
- error: `Could not resolve entry point from ${fragment.filePath}`
1468
- });
1469
- }
1470
- }
1471
- let completed = 0;
1472
- for (let i = 0; i < entries.length; i += concurrency) {
1473
- const batch = entries.slice(i, i + concurrency);
1474
- const results = await Promise.allSettled(
1475
- batch.map(
1476
- ({ name, entryPoint }) => measureSingleComponent(entryPoint, name)
1477
- )
1478
- );
1479
- for (let j = 0; j < results.length; j++) {
1480
- const result = results[j];
1481
- const { name } = batch[j];
1482
- completed++;
1483
- if (result.status === "fulfilled") {
1484
- measurements.set(name, result.value);
1485
- } else {
1486
- errors.push({
1487
- name,
1488
- error: result.reason instanceof Error ? result.reason.message : String(result.reason)
1489
- });
1490
- }
1491
- options.onProgress?.(completed, entries.length, name);
1492
- }
1493
- }
1494
- return {
1495
- measurements,
1496
- errors,
1497
- elapsed: Date.now() - start
1498
- };
1499
- }
1500
- function toPerformanceData(measurement, config, contractBudget) {
1501
- const budget = contractBudget ?? config.budgets.bundleSize;
1502
- const budgetPercent = Math.round(measurement.gzipBytes / budget * 100);
1503
- const imports = measurement.imports?.slice(0, 10).map((imp) => ({
1504
- path: imp.path,
1505
- bytes: imp.bytes,
1506
- percent: Math.round(imp.bytes / measurement.rawBytes * 100)
1507
- }));
1508
- return {
1509
- bundleSize: measurement.gzipBytes,
1510
- rawSize: measurement.rawBytes,
1511
- complexity: classifyComplexity(measurement.gzipBytes),
1512
- budgetPercent,
1513
- overBudget: budgetPercent > 100,
1514
- measuredAt: (/* @__PURE__ */ new Date()).toISOString(),
1515
- ...imports && imports.length > 0 ? { imports } : {}
1516
- };
1517
- }
1518
-
1519
- // src/build.ts
1520
- function normalizeParsedProps(parsedProps) {
1521
- return Object.fromEntries(
1522
- Object.entries(parsedProps).map(([name, prop]) => [
1523
- name,
1524
- {
1525
- type: prop.type ?? "custom",
1526
- description: prop.description ?? "",
1527
- default: prop.default,
1528
- required: prop.required,
1529
- values: prop.values,
1530
- constraints: prop.constraints
1531
- }
1532
- ])
1533
- );
1534
- }
1535
- function mergeDocumentedAndAutoProps(documentedProps, autoProps) {
1536
- return Object.fromEntries(
1537
- Object.keys(autoProps).filter((name) => autoProps[name].source === "local" || name in documentedProps).map((name) => {
1538
- const documented = documentedProps[name];
1539
- const auto = autoProps[name];
1540
- return [
1541
- name,
1542
- {
1543
- type: auto.typeKind,
1544
- description: documented?.description ?? auto.description ?? "",
1545
- default: auto.default !== void 0 ? auto.default : documented?.default,
1546
- required: auto.required,
1547
- values: auto.values ?? documented?.values,
1548
- constraints: documented?.constraints
1549
- }
1550
- ];
1551
- })
1552
- );
1553
- }
1554
- function compilePropsSummary(props) {
1555
- return Object.entries(props).filter(([_, p]) => p.source === "local").map(([name, prop]) => {
1556
- let summary = name + ": ";
1557
- if (prop.values && prop.values.length > 0) {
1558
- summary += prop.values.join("|");
1559
- } else {
1560
- summary += prop.typeKind;
1561
- }
1562
- if (prop.default !== void 0) {
1563
- summary += ` (default: ${prop.default})`;
1564
- }
1565
- if (prop.required) {
1566
- summary += " (required)";
1567
- }
1568
- return summary;
1569
- });
1570
- }
1571
- async function buildFragments(config, configDir) {
1572
- const files = await discoverFragmentFiles(config, configDir);
1573
- const errors = [];
1574
- const warnings = [];
1575
- const fragments = {};
1576
- const tsconfigCandidates = [
1577
- resolve5(configDir, "tsconfig.json"),
1578
- resolve5(configDir, "..", "tsconfig.json")
1579
- ];
1580
- const tsconfigPath = tsconfigCandidates.find((p) => existsSync6(p));
1581
- const extractor = createComponentExtractor(tsconfigPath);
1582
- for (const file of files) {
1583
- try {
1584
- const content = await readFile3(file.absolutePath, "utf-8");
1585
- if (!content.includes("defineFragment")) {
1586
- warnings.push({
1587
- file: file.relativePath,
1588
- warning: "No defineFragment() call found"
1589
- });
1590
- continue;
1591
- }
1592
- const parsed = parseFragmentFile(content, file.relativePath);
1593
- for (const warning of parsed.warnings) {
1594
- warnings.push({ file: file.relativePath, warning });
1595
- }
1596
- if (!parsed.meta.name) {
1597
- warnings.push({
1598
- file: file.relativePath,
1599
- warning: "Missing meta.name in fragment definition \u2014 skipped"
1600
- });
1601
- continue;
1602
- }
1603
- const documentedProps = normalizeParsedProps(parsed.props);
1604
- let mergedProps = documentedProps;
1605
- const componentExportName = parsed.componentName ?? parsed.meta.name;
1606
- const componentSourcePath = resolveComponentSourcePath(
1607
- file.absolutePath,
1608
- parsed.componentImport
1609
- );
1610
- let extractedMeta = null;
1611
- if (componentExportName && componentSourcePath) {
1612
- try {
1613
- extractedMeta = extractor.extract(componentSourcePath, componentExportName);
1614
- } catch {
1615
- }
1616
- if (extractedMeta) {
1617
- const autoProps = extractedMeta.props;
1618
- const hasAutoProps = Object.keys(autoProps).length > 0;
1619
- if (hasAutoProps) {
1620
- const removedDocumentedProps = Object.keys(documentedProps).filter(
1621
- (propName) => !(propName in autoProps)
1622
- );
1623
- if (removedDocumentedProps.length > 0) {
1624
- warnings.push({
1625
- file: file.relativePath,
1626
- warning: `Removed ${removedDocumentedProps.length} documented props not present in source API: ${removedDocumentedProps.join(", ")}`
1627
- });
1628
- }
1629
- mergedProps = mergeDocumentedAndAutoProps(documentedProps, autoProps);
1630
- } else if (Object.keys(documentedProps).length > 0) {
1631
- warnings.push({
1632
- file: file.relativePath,
1633
- warning: "Auto-props extraction returned no props; falling back to documented props"
1634
- });
1635
- }
1636
- }
1637
- } else if (!componentExportName) {
1638
- warnings.push({
1639
- file: file.relativePath,
1640
- warning: "Unable to resolve component export name for auto-props extraction"
1641
- });
1642
- } else if (!componentSourcePath) {
1643
- warnings.push({
1644
- file: file.relativePath,
1645
- warning: `Unable to resolve component source path from import: ${parsed.componentImport ?? "unknown"}`
1646
- });
1647
- }
1648
- let contract = parsed.contract;
1649
- if (!contract?.propsSummary && extractedMeta) {
1650
- const summary = compilePropsSummary(extractedMeta.props);
1651
- if (summary.length > 0) {
1652
- contract = { ...contract, propsSummary: summary };
1653
- }
1654
- }
1655
- let ai = parsed.ai;
1656
- if (extractedMeta?.composition) {
1657
- const comp = extractedMeta.composition;
1658
- ai = {
1659
- compositionPattern: comp.pattern,
1660
- subComponents: comp.parts.map((p) => p.name),
1661
- ...ai
1662
- // Manually authored ai fields take precedence
1663
- };
1664
- }
1665
- const compiled = {
1666
- filePath: file.relativePath,
1667
- meta: {
1668
- name: parsed.meta.name,
1669
- description: parsed.meta.description ?? "",
1670
- category: parsed.meta.category ?? "Uncategorized",
1671
- status: parsed.meta.status,
1672
- tags: parsed.meta.tags,
1673
- since: parsed.meta.since,
1674
- ...parsed.meta.dependencies && { dependencies: parsed.meta.dependencies },
1675
- figma: parsed.meta.figma
1676
- },
1677
- usage: {
1678
- when: parsed.usage.when ?? [],
1679
- whenNot: parsed.usage.whenNot ?? [],
1680
- guidelines: parsed.usage.guidelines,
1681
- accessibility: parsed.usage.accessibility
1682
- },
1683
- props: mergedProps,
1684
- relations: parsed.relations.map((rel) => ({
1685
- component: rel.component,
1686
- relationship: rel.relationship,
1687
- note: rel.note
1688
- })),
1689
- variants: parsed.variants.map((v) => ({
1690
- name: v.name,
1691
- description: v.description,
1692
- ...v.code && { code: v.code },
1693
- ...v.figma && { figma: v.figma },
1694
- ...v.args && { args: v.args }
1695
- })),
1696
- // Include AI metadata (auto-enriched or manual)
1697
- ...ai && { ai },
1698
- // Include contract metadata (auto-compiled or manual)
1699
- ...contract && { contract }
1700
- };
1701
- fragments[parsed.meta.name] = compiled;
1702
- } catch (error) {
1703
- errors.push({
1704
- file: file.relativePath,
1705
- error: error instanceof Error ? error.message : String(error)
1706
- });
1707
- }
1708
- }
1709
- extractor.dispose();
1710
- const blocks = {};
1711
- try {
1712
- const blockFiles = await discoverBlockFiles(configDir, config.exclude);
1713
- for (const file of blockFiles) {
1714
- try {
1715
- let raw = await loadFragmentFile(file.absolutePath);
1716
- if (raw && "default" in raw && typeof raw.default === "object") {
1717
- raw = raw.default;
1718
- }
1719
- const def = raw;
1720
- if (def && typeof def === "object" && "name" in def && "code" in def && "components" in def) {
1721
- const compiled = compileBlock(def, file.relativePath);
1722
- blocks[compiled.name] = compiled;
1723
- }
1724
- } catch (error) {
1725
- warnings.push({
1726
- file: file.relativePath,
1727
- warning: `Failed to load block: ${error instanceof Error ? error.message : String(error)}`
1728
- });
1729
- }
1730
- }
1731
- } catch {
1732
- }
1733
- let tokens;
1734
- try {
1735
- const tokenPatterns = config.tokens?.include;
1736
- const tokenFiles = await discoverTokenFiles(configDir, tokenPatterns, config.exclude);
1737
- if (tokenFiles.length > 0) {
1738
- const mergedCategories = {};
1739
- let prefix = "--";
1740
- let total = 0;
1741
- const fileContents = [];
1742
- for (const file of tokenFiles) {
1743
- const content = await readFile3(file.absolutePath, "utf-8");
1744
- fileContents.push({ content, path: file.relativePath });
1745
- }
1746
- const allContent = fileContents.map((f) => f.content).join("\n");
1747
- for (const { content, path } of fileContents) {
1748
- const parsed = parseTokenFile(allContent, path);
1749
- const fileParsed = parseTokenFile(content, path);
1750
- prefix = fileParsed.prefix;
1751
- total += fileParsed.total;
1752
- for (const [cat, catTokens] of Object.entries(fileParsed.categories)) {
1753
- if (!mergedCategories[cat]) {
1754
- mergedCategories[cat] = [];
1755
- }
1756
- for (const t of catTokens) {
1757
- if (!mergedCategories[cat].some((e) => e.name === t.name)) {
1758
- const combinedToken = Object.values(parsed.categories).flat().find((ct) => ct.name === t.name);
1759
- const resolvedValue = combinedToken?.resolvedValue ?? t.resolvedValue;
1760
- mergedCategories[cat].push({
1761
- name: t.name,
1762
- ...resolvedValue ? { value: resolvedValue } : t.value ? { value: t.value } : {},
1763
- description: t.description
1764
- });
1765
- }
1766
- }
1767
- }
1768
- }
1769
- if (total > 0) {
1770
- const allTokens = Object.values(mergedCategories).flat();
1771
- const unresolved = allTokens.filter(
1772
- (t) => t.value && (t.value.includes("#{") || t.value.includes("$"))
1773
- );
1774
- if (unresolved.length > 0 && tokenFiles.length > 0) {
1775
- const tokensDir = resolve5(configDir, tokenFiles[0].relativePath, "..");
1776
- const sassResolved = await resolveTokensWithSass(
1777
- unresolved,
1778
- tokensDir
1779
- );
1780
- if (sassResolved.size > 0) {
1781
- for (const catTokens of Object.values(mergedCategories)) {
1782
- for (const token of catTokens) {
1783
- const resolved = sassResolved.get(token.name);
1784
- if (resolved && token.value && (token.value.includes("#{") || token.value.includes("$"))) {
1785
- token.value = resolved;
1786
- }
1787
- }
1788
- }
1789
- }
1790
- }
1791
- tokens = { prefix, total, categories: mergedCategories };
1792
- }
1793
- }
1794
- } catch {
1795
- }
1796
- let packageName;
1797
- const pkgJsonPath = resolve5(configDir, "package.json");
1798
- if (existsSync6(pkgJsonPath)) {
1799
- try {
1800
- const pkg = JSON.parse(await readFile3(pkgJsonPath, "utf-8"));
1801
- if (pkg.name) packageName = pkg.name;
1802
- } catch {
1803
- }
1804
- }
1805
- const componentDir = resolve5(configDir, "src", "components");
1806
- let graphData;
1807
- try {
1808
- const graphResult = await buildComponentGraph(fragments, blocks, componentDir);
1809
- for (const [name, fragment] of Object.entries(fragments)) {
1810
- const detected = graphResult.autoDetected.get(name);
1811
- if (!detected) continue;
1812
- if (!fragment.ai) fragment.ai = {};
1813
- if (!fragment.ai.subComponents && detected.subComponents) {
1814
- fragment.ai.subComponents = detected.subComponents;
1815
- }
1816
- if (!fragment.ai.compositionPattern && detected.compositionPattern) {
1817
- fragment.ai.compositionPattern = detected.compositionPattern;
1818
- }
1819
- if (!fragment.ai.commonPatterns && detected.commonPatterns) {
1820
- fragment.ai.commonPatterns = detected.commonPatterns;
1821
- }
1822
- if (!fragment.ai.requiredChildren && detected.requiredChildren) {
1823
- fragment.ai.requiredChildren = detected.requiredChildren;
1824
- }
1825
- }
1826
- for (const w of graphResult.warnings) {
1827
- warnings.push({ file: "graph", warning: w });
1828
- }
1829
- graphData = serializeGraph(graphResult.graph);
1830
- } catch (error) {
1831
- warnings.push({
1832
- file: "graph",
1833
- warning: `Graph extraction failed: ${error instanceof Error ? error.message : String(error)}`
1834
- });
1835
- }
1836
- let performanceSummary;
1837
- if (config.performance) {
1838
- try {
1839
- const perfConfig = resolvePerformanceConfig(config.performance);
1840
- const perfResult = await measureBundleSizes(fragments, configDir, {
1841
- perfConfig
1842
- });
1843
- const tiers = { lightweight: 0, moderate: 0, heavy: 0 };
1844
- let overBudgetCount = 0;
1845
- for (const [name, measurement] of perfResult.measurements) {
1846
- const fragment = fragments[name];
1847
- const contractBudget = fragment?.contract?.performanceBudget;
1848
- const perfData = toPerformanceData(measurement, perfConfig, contractBudget);
1849
- fragment.performance = perfData;
1850
- tiers[perfData.complexity]++;
1851
- if (perfData.overBudget) overBudgetCount++;
1852
- }
1853
- performanceSummary = {
1854
- preset: perfConfig.preset,
1855
- budget: perfConfig.budgets.bundleSize,
1856
- total: perfResult.measurements.size,
1857
- overBudget: overBudgetCount,
1858
- tiers
1859
- };
1860
- for (const err of perfResult.errors) {
1861
- warnings.push({
1862
- file: "performance",
1863
- warning: `Could not measure ${err.name}: ${err.error}`
1864
- });
1865
- }
1866
- } catch (error) {
1867
- warnings.push({
1868
- file: "performance",
1869
- warning: `Performance measurement failed: ${error instanceof Error ? error.message : String(error)}`
1870
- });
1871
- }
1872
- }
1873
- const output = {
1874
- version: "1.0.0",
1875
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1876
- ...packageName && { packageName },
1877
- fragments,
1878
- ...Object.keys(blocks).length > 0 && { blocks },
1879
- ...tokens && { tokens },
1880
- ...graphData && { graph: graphData },
1881
- ...performanceSummary && { performanceSummary }
1882
- };
1883
- const outputPath = resolve5(configDir, config.outFile ?? BRAND.outFile);
1884
- await writeFile(outputPath, JSON.stringify(output));
1885
- return {
1886
- success: errors.length === 0,
1887
- outputPath,
1888
- fragmentCount: Object.keys(fragments).length,
1889
- errors,
1890
- warnings
1891
- };
1892
- }
1893
- async function buildFragmentsDir(config, configDir) {
1894
- const fragmentsDir = join5(configDir, BRAND.dataDir);
1895
- const componentsDir = join5(fragmentsDir, BRAND.componentsDir);
1896
- await mkdir(fragmentsDir, { recursive: true });
1897
- await mkdir(componentsDir, { recursive: true });
1898
- const registryResult = await generateRegistry({
1899
- projectRoot: configDir,
1900
- componentPatterns: config.components || ["src/**/*.tsx", "src/**/*.ts"],
1901
- storyPatterns: config.include || ["src/**/*.stories.tsx"],
1902
- fragmentsDir,
1903
- registryOptions: config.registry || {}
1904
- });
1905
- const errors = [...registryResult.errors];
1906
- const warnings = [...registryResult.warnings];
1907
- const indexPath = join5(fragmentsDir, "index.json");
1908
- await writeFile(indexPath, JSON.stringify(registryResult.index, null, 2));
1909
- const registryPath = join5(fragmentsDir, BRAND.registryFile);
1910
- await writeFile(registryPath, JSON.stringify(registryResult.registry, null, 2));
1911
- const contextResult = generateContextMd(registryResult.registry, {
1912
- format: "markdown",
1913
- compact: false,
1914
- include: {
1915
- props: false,
1916
- // AI can read TypeScript directly
1917
- relations: true,
1918
- code: false
1919
- }
1920
- });
1921
- const contextPath = join5(fragmentsDir, BRAND.contextFile);
1922
- await writeFile(contextPath, contextResult.content);
1923
- return {
1924
- success: errors.length === 0,
1925
- indexPath,
1926
- registryPath,
1927
- contextPath,
1928
- componentCount: registryResult.registry.componentCount,
1929
- errors,
1930
- warnings
1931
- };
1932
- }
1933
-
1934
- // src/screenshot.ts
1935
- import pc from "picocolors";
1936
- async function runScreenshotCommand(config, configDir, options = {}) {
1937
- const startTime = Date.now();
1938
- const errors = [];
1939
- const storage = new StorageManager({
1940
- projectRoot: configDir,
1941
- viewport: options.width && options.height ? { width: options.width, height: options.height } : config.screenshots?.viewport
1942
- });
1943
- await storage.initialize();
1944
- const fragmentFiles = await discoverFragmentFiles(config, configDir);
1945
- if (fragmentFiles.length === 0) {
1946
- console.log(pc.yellow("No fragment files found."));
1947
- return {
1948
- success: true,
1949
- captured: 0,
1950
- skipped: 0,
1951
- errors: [],
1952
- totalTimeMs: Date.now() - startTime
1953
- };
1954
- }
1955
- const fragments = [];
1956
- for (const file of fragmentFiles) {
1957
- try {
1958
- const fragment = await loadFragmentFile(file.absolutePath);
1959
- if (fragment) {
1960
- fragments.push({ path: file.relativePath, fragment });
1961
- }
1962
- } catch (error) {
1963
- errors.push({
1964
- component: file.relativePath,
1965
- variant: "",
1966
- error: error instanceof Error ? error.message : String(error)
1967
- });
1968
- }
1969
- }
1970
- const filteredFragments = options.component ? fragments.filter((s) => s.fragment.meta.name === options.component) : fragments;
1971
- if (options.component && filteredFragments.length === 0) {
1972
- console.log(pc.yellow(`Component "${options.component}" not found.`));
1973
- return {
1974
- success: false,
1975
- captured: 0,
1976
- skipped: 0,
1977
- errors: [],
1978
- totalTimeMs: Date.now() - startTime
1979
- };
1980
- }
1981
- const variantsToCapture = [];
1982
- for (const { fragment } of filteredFragments) {
1983
- const variants = options.variant ? fragment.variants.filter((v) => v.name === options.variant) : fragment.variants;
1984
- for (const variant of variants) {
1985
- variantsToCapture.push({
1986
- component: fragment.meta.name,
1987
- variant: variant.name,
1988
- render: variant.render
1989
- });
1990
- }
1991
- }
1992
- if (variantsToCapture.length === 0) {
1993
- console.log(pc.yellow("No variants to capture."));
1994
- return {
1995
- success: true,
1996
- captured: 0,
1997
- skipped: 0,
1998
- errors: [],
1999
- totalTimeMs: Date.now() - startTime
2000
- };
2001
- }
2002
- const theme = options.theme ?? DEFAULTS.theme;
2003
- const viewport = {
2004
- width: options.width ?? config.screenshots?.viewport?.width ?? DEFAULTS.viewport.width,
2005
- height: options.height ?? config.screenshots?.viewport?.height ?? DEFAULTS.viewport.height
2006
- };
2007
- console.log(pc.cyan(`
2008
- ${BRAND.name} Screenshot
2009
- `));
2010
- console.log(pc.dim(`Capturing variants (theme: ${theme}, viewport: ${viewport.width}x${viewport.height}):
2011
- `));
2012
- const pool = new BrowserPool({
2013
- viewport
2014
- });
2015
- const viewerPort = DEFAULTS.port;
2016
- const baseUrl = `http://localhost:${viewerPort}`;
2017
- const captureEngine = new CaptureEngine(pool, baseUrl);
2018
- let captured = 0;
2019
- let skipped = 0;
2020
- const captureOptions = {
2021
- theme,
2022
- viewport,
2023
- delay: config.screenshots?.delay ?? DEFAULTS.captureDelayMs
2024
- };
2025
- try {
2026
- console.log(pc.dim("Starting browser..."));
2027
- await pool.warmup();
2028
- console.log(pc.dim("Browser ready.\n"));
2029
- for (const { component, variant } of variantsToCapture) {
2030
- const hasExisting = storage.hasBaseline(component, variant, theme);
2031
- if (hasExisting && !options.update) {
2032
- console.log(` ${pc.dim("\u25CB")} ${component}/${variant} ${pc.dim("(skipped)")}`);
2033
- skipped++;
2034
- continue;
2035
- }
2036
- try {
2037
- const screenshot = await captureEngine.captureVariant(
2038
- component,
2039
- variant,
2040
- captureOptions
2041
- );
2042
- await storage.saveBaseline(screenshot);
2043
- const totalTime = screenshot.metadata.renderTimeMs + screenshot.metadata.captureTimeMs;
2044
- console.log(
2045
- ` ${pc.green("\u2713")} ${component}/${variant} ${pc.dim(formatMs(totalTime))}`
2046
- );
2047
- captured++;
2048
- } catch (error) {
2049
- const errorMsg = error instanceof Error ? error.message : String(error);
2050
- console.log(` ${pc.red("\u2717")} ${component}/${variant} ${pc.dim(errorMsg)}`);
2051
- errors.push({ component, variant, error: errorMsg });
2052
- }
2053
- }
2054
- } finally {
2055
- await pool.shutdown();
2056
- }
2057
- const totalTimeMs = Date.now() - startTime;
2058
- console.log();
2059
- if (errors.length === 0) {
2060
- console.log(pc.green(`\u2713 Captured ${captured} screenshot(s) in ${formatMs(totalTimeMs)}`));
2061
- } else {
2062
- console.log(pc.yellow(`\u26A0 Captured ${captured} screenshot(s) with ${errors.length} error(s)`));
2063
- }
2064
- if (skipped > 0) {
2065
- console.log(pc.dim(` ${skipped} skipped (use --update to recapture)`));
2066
- }
2067
- console.log(pc.dim(` Stored in ${storage.screenshotsDirPath}
2068
- `));
2069
- return {
2070
- success: errors.length === 0,
2071
- captured,
2072
- skipped,
2073
- errors,
2074
- totalTimeMs
2075
- };
2076
- }
2077
-
2078
- // src/diff.ts
2079
- import pc2 from "picocolors";
2080
- async function runDiffCommand(config, configDir, options = {}) {
2081
- const startTime = Date.now();
2082
- const results = [];
2083
- const storage = new StorageManager({
2084
- projectRoot: configDir,
2085
- viewport: config.screenshots?.viewport
2086
- });
2087
- await storage.initialize();
2088
- const threshold = options.threshold ?? config.screenshots?.threshold ?? DEFAULTS.diffThreshold;
2089
- const diffEngine = new DiffEngine(threshold);
2090
- const fragmentFiles = await discoverFragmentFiles(config, configDir);
2091
- if (fragmentFiles.length === 0) {
2092
- console.log(pc2.yellow("No fragment files found."));
2093
- return {
2094
- success: true,
2095
- total: 0,
2096
- passed: 0,
2097
- failed: 0,
2098
- missing: 0,
2099
- results: [],
2100
- totalTimeMs: Date.now() - startTime
2101
- };
2102
- }
2103
- const fragments = [];
2104
- for (const file of fragmentFiles) {
2105
- try {
2106
- const fragment = await loadFragmentFile(file.absolutePath);
2107
- if (fragment) {
2108
- fragments.push({ path: file.relativePath, fragment });
2109
- }
2110
- } catch {
2111
- }
2112
- }
2113
- const filteredFragments = options.component ? fragments.filter((s) => s.fragment.meta.name === options.component) : fragments;
2114
- if (options.component && filteredFragments.length === 0) {
2115
- console.log(pc2.yellow(`Component "${options.component}" not found.`));
2116
- return {
2117
- success: false,
2118
- total: 0,
2119
- passed: 0,
2120
- failed: 0,
2121
- missing: 0,
2122
- results: [],
2123
- totalTimeMs: Date.now() - startTime
2124
- };
2125
- }
2126
- const variantsToDiff = [];
2127
- for (const { fragment } of filteredFragments) {
2128
- const variants = options.variant ? fragment.variants.filter((v) => v.name === options.variant) : fragment.variants;
2129
- for (const variant of variants) {
2130
- variantsToDiff.push({
2131
- component: fragment.meta.name,
2132
- variant: variant.name
2133
- });
2134
- }
2135
- }
2136
- if (variantsToDiff.length === 0) {
2137
- console.log(pc2.yellow("No variants to compare."));
2138
- return {
2139
- success: true,
2140
- total: 0,
2141
- passed: 0,
2142
- failed: 0,
2143
- missing: 0,
2144
- results: [],
2145
- totalTimeMs: Date.now() - startTime
2146
- };
2147
- }
2148
- const theme = options.theme ?? DEFAULTS.theme;
2149
- const viewport = config.screenshots?.viewport ?? DEFAULTS.viewport;
2150
- console.log(pc2.cyan(`
2151
- ${BRAND.name} Diff
2152
- `));
2153
- console.log(pc2.dim(`Comparing against baselines (theme: ${theme}, threshold: ${threshold}%):
2154
- `));
2155
- const pool = new BrowserPool({
2156
- viewport
2157
- });
2158
- const viewerPort = DEFAULTS.port;
2159
- const baseUrl = `http://localhost:${viewerPort}`;
2160
- const captureEngine = new CaptureEngine(pool, baseUrl);
2161
- let passed = 0;
2162
- let failed = 0;
2163
- let missing = 0;
2164
- const captureOptions = {
2165
- theme,
2166
- viewport,
2167
- delay: config.screenshots?.delay ?? DEFAULTS.captureDelayMs
2168
- };
2169
- try {
2170
- await pool.warmup();
2171
- for (const { component, variant } of variantsToDiff) {
2172
- const baseline = await storage.loadBaseline(component, variant, theme);
2173
- if (!baseline) {
2174
- console.log(
2175
- ` ${pc2.yellow("?")} ${component}/${variant} ${pc2.dim("(no baseline)")}`
2176
- );
2177
- missing++;
2178
- continue;
2179
- }
2180
- try {
2181
- const current = await captureEngine.captureVariant(
2182
- component,
2183
- variant,
2184
- captureOptions
2185
- );
2186
- if (diffEngine.areIdentical(current, baseline)) {
2187
- console.log(` ${pc2.green("\u2713")} ${component}/${variant} ${pc2.dim("0.0%")}`);
2188
- results.push({
2189
- component,
2190
- variant,
2191
- theme,
2192
- result: {
2193
- matches: true,
2194
- diffPercentage: 0,
2195
- diffPixelCount: 0,
2196
- totalPixels: current.viewport.width * current.viewport.height,
2197
- changedRegions: [],
2198
- diffTimeMs: 0
2199
- }
2200
- });
2201
- passed++;
2202
- continue;
2203
- }
2204
- const diffResult = diffEngine.compare(current, baseline, { threshold });
2205
- if (diffResult.matches) {
2206
- console.log(
2207
- ` ${pc2.green("\u2713")} ${component}/${variant} ${pc2.dim(`${diffResult.diffPercentage}%`)}`
2208
- );
2209
- passed++;
2210
- } else {
2211
- let diffImagePath;
2212
- if (diffResult.diffImage) {
2213
- diffImagePath = await storage.saveDiff(
2214
- component,
2215
- variant,
2216
- theme,
2217
- diffResult.diffImage
2218
- );
2219
- }
2220
- console.log(
2221
- ` ${pc2.red("\u2717")} ${component}/${variant} ${pc2.yellow(`${diffResult.diffPercentage}%`)}` + (diffImagePath ? pc2.dim(` \u2192 ${diffImagePath}`) : "")
2222
- );
2223
- failed++;
2224
- results.push({
2225
- component,
2226
- variant,
2227
- theme,
2228
- result: diffResult,
2229
- diffImagePath
2230
- });
2231
- continue;
2232
- }
2233
- results.push({
2234
- component,
2235
- variant,
2236
- theme,
2237
- result: diffResult
2238
- });
2239
- } catch (error) {
2240
- const errorMsg = error instanceof Error ? error.message : String(error);
2241
- console.log(` ${pc2.red("!")} ${component}/${variant} ${pc2.dim(errorMsg)}`);
2242
- failed++;
2243
- }
2244
- }
2245
- } finally {
2246
- await pool.shutdown();
2247
- }
2248
- const totalTimeMs = Date.now() - startTime;
2249
- const total = passed + failed + missing;
2250
- console.log();
2251
- if (failed === 0 && missing === 0) {
2252
- console.log(pc2.green(`\u2713 All ${passed} variant(s) match baselines`));
2253
- } else if (failed > 0) {
2254
- console.log(pc2.red(`\u2717 ${failed} variant(s) differ from baselines`));
2255
- }
2256
- if (missing > 0) {
2257
- console.log(pc2.yellow(` ${missing} variant(s) have no baseline (run \`${BRAND.cliCommand} screenshot\`)`));
2258
- }
2259
- console.log(pc2.dim(` Completed in ${formatMs(totalTimeMs)}
2260
- `));
2261
- const success = failed === 0;
2262
- return {
2263
- success,
2264
- total,
2265
- passed,
2266
- failed,
2267
- missing,
2268
- results,
2269
- totalTimeMs
2270
- };
2271
- }
2272
-
2273
- // src/analyze.ts
2274
- import { existsSync as existsSync7 } from "fs";
2275
- import { readFile as readFile4, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
2276
- import { join as join6, dirname as dirname4 } from "path";
2277
- import pc3 from "picocolors";
2278
- async function runAnalyzeCommand(config, configDir, options = {}) {
2279
- const format = options.format ?? "html";
2280
- const minScore = options.minScore ?? 0;
2281
- console.log(pc3.cyan(`
2282
- ${BRAND.name} Analyzer
2283
- `));
2284
- const fragmentsPath = join6(configDir, config.outFile ?? "fragments.json");
2285
- if (!existsSync7(fragmentsPath)) {
2286
- console.log(pc3.red(`\u2717 No fragments.json found. Run \`${BRAND.cliCommand} build\` first.
2287
- `));
2288
- return {
2289
- success: false,
2290
- analytics: createEmptyAnalytics()
2291
- };
2292
- }
2293
- console.log(pc3.dim("Analyzing design system...\n"));
2294
- const content = await readFile4(fragmentsPath, "utf-8");
2295
- const data = JSON.parse(content);
2296
- const analytics = analyzeDesignSystem(data);
2297
- printConsoleSummary(analytics);
2298
- let outputPath;
2299
- if (format === "html" || format === "json") {
2300
- outputPath = options.output ?? getDefaultOutputPath(format, configDir);
2301
- await mkdir2(dirname4(outputPath), { recursive: true });
2302
- if (format === "html") {
2303
- const html = generateHtmlReport(analytics);
2304
- await writeFile2(outputPath, html);
2305
- console.log(pc3.green(`\u2713 Report generated: ${outputPath}
2306
- `));
2307
- } else {
2308
- await writeFile2(outputPath, JSON.stringify(analytics, null, 2));
2309
- console.log(pc3.green(`\u2713 JSON report generated: ${outputPath}
2310
- `));
2311
- }
2312
- if (options.open && format === "html") {
2313
- await openInBrowser(outputPath);
2314
- }
2315
- }
2316
- const passedCi = analytics.summary.overallScore >= minScore;
2317
- if (options.ci) {
2318
- if (passedCi) {
2319
- console.log(
2320
- pc3.green(`\u2713 Score ${analytics.summary.overallScore} meets minimum threshold ${minScore}
2321
- `)
2322
- );
2323
- } else {
2324
- console.log(
2325
- pc3.red(
2326
- `\u2717 Score ${analytics.summary.overallScore} below minimum threshold ${minScore}
2327
- `
2328
- )
2329
- );
2330
- }
2331
- }
2332
- return {
2333
- success: !options.ci || passedCi,
2334
- analytics,
2335
- outputPath
2336
- };
2337
- }
2338
- function printConsoleSummary(analytics) {
2339
- const { summary, coverage, recommendations } = analytics;
2340
- const grade = getGrade(summary.overallScore);
2341
- console.log(
2342
- pc3.bold(
2343
- `Overall Score: ${colorizeScore(summary.overallScore)} (${grade})
2344
- `
2345
- )
2346
- );
2347
- console.log(pc3.dim("Summary"));
2348
- console.log(` Components: ${pc3.white(summary.totalComponents.toString())}`);
2349
- console.log(` Variants: ${pc3.white(summary.totalVariants.toString())}`);
2350
- console.log(` Props: ${pc3.white(summary.totalProps.toString())}`);
2351
- console.log(` Categories: ${pc3.white(summary.categories.join(", "))}`);
2352
- console.log();
2353
- console.log(pc3.dim("Coverage"));
2354
- console.log(` Description: ${formatCoverage(coverage.fields.description)}`);
2355
- console.log(` Usage when: ${formatCoverage(coverage.fields.usageWhen)}`);
2356
- console.log(` Usage whenNot:${formatCoverage(coverage.fields.usageWhenNot)}`);
2357
- console.log(` Guidelines: ${formatCoverage(coverage.fields.guidelines)}`);
2358
- console.log(` Relations: ${formatCoverage(coverage.fields.relations)}`);
2359
- console.log();
2360
- if (recommendations.length > 0) {
2361
- console.log(pc3.dim("Top Recommendations"));
2362
- for (const rec of recommendations.slice(0, 3)) {
2363
- const priority = rec.priority === "high" ? pc3.red(`[${rec.priority}]`) : rec.priority === "medium" ? pc3.yellow(`[${rec.priority}]`) : pc3.dim(`[${rec.priority}]`);
2364
- console.log(` ${priority} ${rec.title}`);
2365
- }
2366
- console.log();
2367
- }
2368
- }
2369
- function formatCoverage(field) {
2370
- const pct = colorizeScore(field.percentage);
2371
- return `${pct} (${field.covered}/${field.total})`;
2372
- }
2373
- function colorizeScore(score) {
2374
- if (score >= 80) return pc3.green(`${score}%`);
2375
- if (score >= 60) return pc3.yellow(`${score}%`);
2376
- return pc3.red(`${score}%`);
2377
- }
2378
- function getDefaultOutputPath(format, configDir) {
2379
- const filename = format === "html" ? "fragments-report.html" : "fragments-report.json";
2380
- return join6(configDir, filename);
2381
- }
2382
- async function openInBrowser(path) {
2383
- const { platform } = await import("os");
2384
- const { exec } = await import("child_process");
2385
- const os = platform();
2386
- const cmd = os === "darwin" ? `open "${path}"` : os === "win32" ? `start "" "${path}"` : `xdg-open "${path}"`;
2387
- exec(cmd);
2388
- }
2389
- function createEmptyAnalytics() {
2390
- return {
2391
- analyzedAt: /* @__PURE__ */ new Date(),
2392
- summary: {
2393
- totalComponents: 0,
2394
- totalVariants: 0,
2395
- totalProps: 0,
2396
- categories: [],
2397
- overallScore: 0
2398
- },
2399
- inventory: {
2400
- byCategory: {},
2401
- byStatus: {},
2402
- byVariantCount: [],
2403
- byPropCount: []
2404
- },
2405
- coverage: {
2406
- overall: 0,
2407
- fields: {
2408
- description: { covered: 0, total: 0, percentage: 0 },
2409
- usageWhen: { covered: 0, total: 0, percentage: 0 },
2410
- usageWhenNot: { covered: 0, total: 0, percentage: 0 },
2411
- guidelines: { covered: 0, total: 0, percentage: 0 },
2412
- accessibility: { covered: 0, total: 0, percentage: 0 },
2413
- relations: { covered: 0, total: 0, percentage: 0 },
2414
- propDescriptions: { covered: 0, total: 0, percentage: 0 },
2415
- propConstraints: { covered: 0, total: 0, percentage: 0 }
2416
- },
2417
- incomplete: []
2418
- },
2419
- quality: {
2420
- missingWhenNot: [],
2421
- isolated: [],
2422
- deprecated: [],
2423
- fewVariants: [],
2424
- undocumentedProps: [],
2425
- unconstrainedProps: []
2426
- },
2427
- distribution: {
2428
- variantsPerComponent: [],
2429
- propsPerComponent: [],
2430
- componentsPerCategory: [],
2431
- statusDistribution: [],
2432
- tagFrequency: []
2433
- },
2434
- recommendations: []
2435
- };
2436
- }
2437
-
2438
- export {
2439
- resolveComponentSourcePath,
2440
- validateSchema,
2441
- validateCoverage,
2442
- validateAll,
2443
- validateSnippets,
2444
- validateDrift,
2445
- measureBundleSizes,
2446
- toPerformanceData,
2447
- buildFragments,
2448
- buildFragmentsDir,
2449
- runScreenshotCommand,
2450
- runDiffCommand,
2451
- runAnalyzeCommand
2452
- };
2453
- //# sourceMappingURL=chunk-LOYS64QS.js.map