@finedesign/cli 0.2.0-rc.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +68 -155
- package/data/1.24.9/catalog.json +1 -1
- package/data/1.24.9/manifest.json +2 -2
- package/data/1.25.0/catalog.json +1 -1
- package/data/1.25.0/manifest.json +7 -8
- package/package.json +2 -1
- package/skills/fine-design/SKILL.md +2 -2
- package/skills/fine-design/references/component-guide.md +1 -1
- package/skills/fine-design/references/imports-and-setup.md +8 -8
- package/src/cli.mjs +165 -10
- package/src/core/catalog.mjs +300 -19
- package/src/core/contracts.mjs +8 -1
- package/src/core/html.cjs +152 -0
- package/src/core/lint.mjs +302 -0
- package/src/core/runtime.mjs +62 -0
- package/src/mcp.mjs +7 -3
- package/skills/fine-design/references/browser-runtime-legacy.json +0 -71
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parse } from '@babel/parser';
|
|
4
|
+
import { ToolError } from './errors.mjs';
|
|
5
|
+
import { suggestSimilarComponents } from './catalog.mjs';
|
|
6
|
+
|
|
7
|
+
const CODE_FILE_PATTERN = /\.(?:[cm]?[jt]sx?|html?)$/i;
|
|
8
|
+
const IGNORED_DIRS = new Set(['node_modules', '.git', 'dist', 'lib', 'es', '.dumi', 'coverage', 'artifacts']);
|
|
9
|
+
const BUTTON_TYPES = new Set(['primary', 'secondary', 'normal', 'negative', 'link', 'text', 'text-normal', 'bare']);
|
|
10
|
+
|
|
11
|
+
const KNOWN_TYPE_EXPORTS = new Set([
|
|
12
|
+
'AffixProps', 'AffixTarget', 'AlertProps', 'AlertType', 'AnchorProps', 'AvatarProps',
|
|
13
|
+
'BadgeProps', 'ButtonGroupProps', 'ButtonHTMLType', 'ButtonProps', 'ButtonSize', 'ButtonType',
|
|
14
|
+
'CheckGroupDirection', 'CheckGroupProps', 'CheckProps', 'ComboCheckProps',
|
|
15
|
+
'ComboDropdownAsyncParams', 'ComboDropdownGroupItem', 'ComboDropdownItem', 'ComboProps',
|
|
16
|
+
'DatePickerMode', 'DatePickerProps', 'DatetimeProps', 'DialogAnimation', 'DialogImperativeProps',
|
|
17
|
+
'DialogProps', 'DialogTheme', 'DialogTitleAlign', 'DrawerEdge', 'DrawerPlacement', 'DrawerProps',
|
|
18
|
+
'FileItem', 'FilePreviewActionProps', 'FilePreviewFileActionsRender', 'FilePreviewFileActionsRenderInfo',
|
|
19
|
+
'FilePreviewProps', 'FormItemProps', 'FormLayout', 'FormProps', 'IRuleDescriptor',
|
|
20
|
+
'InputCountConfig', 'InputCountInfo', 'InputProps', 'InputRef', 'InputSize', 'InputState',
|
|
21
|
+
'InputValue', 'TextAreaProps', 'InputNumberControlInfo', 'InputNumberControlTooltip',
|
|
22
|
+
'InputNumberControlTooltipProps', 'InputNumberProps', 'InputNumberRef', 'InputNumberSize',
|
|
23
|
+
'InputNumberState', 'InputNumberStep', 'InputNumberValidationProps', 'InputNumberValue',
|
|
24
|
+
'LabelProps', 'ListProps', 'PaginationProps', 'PaginationThemeType', 'RadioGroupDirection',
|
|
25
|
+
'RadioGroupProps', 'RadioProps', 'SegmentItemProps', 'SegmentProps', 'SkeletonProps',
|
|
26
|
+
'SpinProps', 'StepDirection', 'StepItemProps', 'StepProps', 'StepStatus', 'TableColumn',
|
|
27
|
+
'TableProps', 'TableRowSelection', 'TableSize', 'VirtualListHolderComponent', 'VirtualListProps',
|
|
28
|
+
'VirtualListRef', 'VirtualListScrollConfig', 'VirtualListScrollTo', 'BreadcrumbItem',
|
|
29
|
+
'BreadcrumbProps', 'CascaderPlacement', 'CascaderProps', 'MCascaderProps', 'DataTableProps',
|
|
30
|
+
'DataTableSize', 'DataTableColumnType', 'DataTableRowSelection', 'DividerDirection',
|
|
31
|
+
'DividerProp', 'InstructionProps', 'InstructionType', 'LocaleProviderProps', 'MenuItemProps',
|
|
32
|
+
'MenuProps', 'ModalMaskProps', 'PopConfirmProps', 'PopoverPlacement', 'PopoverProps',
|
|
33
|
+
'ProgressProps', 'PromptProps', 'ResultProps', 'ResultSize', 'SplitterProps', 'SwitchProps',
|
|
34
|
+
'TabDirection', 'TabItemProp', 'TabProp', 'TabSize', 'TabTheme', 'TagProps', 'TagShape',
|
|
35
|
+
'TagSize', 'TooltipEffect', 'TooltipPlacement', 'TooltipProps', 'TreeProps', 'TreeRef',
|
|
36
|
+
'TreeDropPosition', 'TreeEventDataNode', 'TriggerProps', 'UploadCustomRequest', 'UploadFile',
|
|
37
|
+
'UploadProgress', 'UploadProps', 'UploadRef', 'MessageProps', 'NotificationProps', 'ToastProps',
|
|
38
|
+
'ToastType', 'ColorPickerProps', 'GradientColorPickerProps', 'SingleColorPickerProps',
|
|
39
|
+
'VirtualTableProps', 'Column', 'ColumnAlign', 'RenderInfo', 'SortOrder', 'SpanRect',
|
|
40
|
+
'WatermarkProps', 'AutoCompleteProps', 'CarouselProps', 'CarouselRef', 'CollapseProps',
|
|
41
|
+
'ConfigProviderProps', 'Theme', 'ThemeAlgorithm', 'ThemeToken', 'DropdownButtonProps',
|
|
42
|
+
'DropdownButtonType', 'DropdownProps', 'ImageProps', 'NavigationDividerProps',
|
|
43
|
+
'NavigationItemGroupProps', 'NavigationItemProps', 'NavigationItemType', 'NavigationProps',
|
|
44
|
+
'NavigationTheme', 'SubNavigationProps', 'SelectDisplayValueType', 'SelectProps',
|
|
45
|
+
'SliderRangeProps', 'SliderRef', 'SliderSingleProps', 'TreeSelectProps', 'TreeTagProps',
|
|
46
|
+
'TypographyProps', 'TIMEZONE_KEY', 'NextTableCellProps', 'NextTableColumnGroupProps',
|
|
47
|
+
'NextTableColumnProps', 'NextTableHeaderCellProps', 'NextTableProps'
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
const EXTRA_VALUE_EXPORTS = new Set([
|
|
51
|
+
'DateUtils',
|
|
52
|
+
'getAllCheckedKeys',
|
|
53
|
+
'getHalfCheckedKeys'
|
|
54
|
+
]);
|
|
55
|
+
|
|
56
|
+
function collectFiles(targetPath) {
|
|
57
|
+
const resolved = path.resolve(targetPath);
|
|
58
|
+
if (!fs.existsSync(resolved)) {
|
|
59
|
+
throw new ToolError('INVALID_ARGUMENT', `Lint target does not exist: ${targetPath}`, 2);
|
|
60
|
+
}
|
|
61
|
+
const results = [];
|
|
62
|
+
function walk(current) {
|
|
63
|
+
const stat = fs.statSync(current);
|
|
64
|
+
if (stat.isFile()) {
|
|
65
|
+
if (CODE_FILE_PATTERN.test(current)) results.push(current);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (!stat.isDirectory()) return;
|
|
69
|
+
for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
70
|
+
if (entry.isDirectory()) {
|
|
71
|
+
if (!IGNORED_DIRS.has(entry.name) && !entry.name.startsWith('.')) {
|
|
72
|
+
walk(path.join(current, entry.name));
|
|
73
|
+
}
|
|
74
|
+
} else if (entry.isFile() && CODE_FILE_PATTERN.test(entry.name)) {
|
|
75
|
+
results.push(path.join(current, entry.name));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
walk(resolved);
|
|
80
|
+
return results;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function lineOfIndex(content, index) {
|
|
84
|
+
let line = 1;
|
|
85
|
+
for (let i = 0; i < index; i++) {
|
|
86
|
+
if (content.charCodeAt(i) === 10) line++;
|
|
87
|
+
}
|
|
88
|
+
return line;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function codeSources(file, content) {
|
|
92
|
+
if (!/\.html?$/i.test(file)) return [{ content, startLine: 1 }];
|
|
93
|
+
return [...content.matchAll(/<!--[\s\S]*?-->|<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)]
|
|
94
|
+
.filter((match) => {
|
|
95
|
+
if (match[1] === undefined) return false;
|
|
96
|
+
const type = match[1].match(/\btype\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
|
97
|
+
return !type || /^(?:module|(?:text|application)\/(?:javascript|ecmascript|babel|typescript))$/i.test(type[1] ?? type[2] ?? type[3]);
|
|
98
|
+
})
|
|
99
|
+
.map((match) => ({ content: match[2], startLine: lineOfIndex(content, match.index + match[0].indexOf('>') + 1) }));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function bindPattern(pattern, scope) {
|
|
103
|
+
if (!pattern) return;
|
|
104
|
+
if (pattern.type === 'Identifier') scope.bindings.set(pattern.name, null);
|
|
105
|
+
else if (pattern.type === 'ObjectPattern') {
|
|
106
|
+
for (const prop of pattern.properties) bindPattern(prop.type === 'RestElement' ? prop.argument : prop.value, scope);
|
|
107
|
+
} else if (pattern.type === 'ArrayPattern') {
|
|
108
|
+
for (const element of pattern.elements) bindPattern(element, scope);
|
|
109
|
+
} else if (pattern.type === 'AssignmentPattern') bindPattern(pattern.left, scope);
|
|
110
|
+
else if (pattern.type === 'RestElement') bindPattern(pattern.argument, scope);
|
|
111
|
+
else if (pattern.type === 'TSParameterProperty') bindPattern(pattern.parameter, scope);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function collectScopes(program) {
|
|
115
|
+
const scopes = new WeakMap();
|
|
116
|
+
function collect(node, scope) {
|
|
117
|
+
if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') bindPattern(node.id, scope);
|
|
118
|
+
const isFunction = /Function(?:Declaration|Expression)$|Method$/.test(node.type);
|
|
119
|
+
if (isFunction || ['Program', 'BlockStatement', 'CatchClause', 'ForStatement', 'ForInStatement', 'ForOfStatement', 'SwitchStatement', 'StaticBlock', 'ClassDeclaration', 'ClassExpression'].includes(node.type)) {
|
|
120
|
+
scope = { parent: scope, bindings: new Map(), varScope: isFunction || node.type === 'Program' || node.type === 'StaticBlock' ? null : scope.varScope };
|
|
121
|
+
scope.varScope ||= scope;
|
|
122
|
+
if (isFunction || node.type === 'ClassExpression') bindPattern(node.id, scope);
|
|
123
|
+
for (const param of node.params || []) bindPattern(param, scope);
|
|
124
|
+
if (node.type === 'CatchClause') bindPattern(node.param, scope);
|
|
125
|
+
}
|
|
126
|
+
scopes.set(node, scope);
|
|
127
|
+
if (node.type === 'ImportDeclaration') {
|
|
128
|
+
for (const spec of node.specifiers) {
|
|
129
|
+
bindPattern(spec.local, scope);
|
|
130
|
+
if (node.source.value === '@fx-ui/fine-design' && node.importKind !== 'type' && spec.importKind !== 'type') {
|
|
131
|
+
if (spec.type === 'ImportSpecifier') scope.bindings.set(spec.local.name, { component: spec.imported.name ?? spec.imported.value });
|
|
132
|
+
else if (spec.type === 'ImportNamespaceSpecifier') scope.bindings.set(spec.local.name, { namespace: true });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} else if (node.type === 'VariableDeclaration') {
|
|
136
|
+
const targetScope = node.kind === 'var' ? scope.varScope : scope;
|
|
137
|
+
for (const declaration of node.declarations) {
|
|
138
|
+
bindPattern(declaration.id, targetScope);
|
|
139
|
+
if (declaration.id.type !== 'ObjectPattern') continue;
|
|
140
|
+
for (const prop of declaration.id.properties) {
|
|
141
|
+
if (prop.type !== 'ObjectProperty' || prop.computed) continue;
|
|
142
|
+
const local = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value;
|
|
143
|
+
if (local.type === 'Identifier') targetScope.bindings.set(local.name, { component: String(prop.key.name ?? prop.key.value), source: declaration.init, scope });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
for (const child of Object.values(node)) {
|
|
148
|
+
if (Array.isArray(child)) child.filter((item) => item?.type).forEach((item) => collect(item, scope));
|
|
149
|
+
else if (child?.type) collect(child, scope);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
collect(program);
|
|
153
|
+
return scopes;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function findBinding(scope, name) {
|
|
157
|
+
for (; scope; scope = scope.parent) {
|
|
158
|
+
if (scope.bindings.has(name)) return scope.bindings.get(name);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isFineDesignNamespace(node, scope) {
|
|
163
|
+
if (!node) return false;
|
|
164
|
+
if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
|
|
165
|
+
const binding = findBinding(scope, node.name);
|
|
166
|
+
return Boolean(binding?.namespace || (node.name === 'FineDesign' && binding === undefined));
|
|
167
|
+
}
|
|
168
|
+
return ['MemberExpression', 'JSXMemberExpression'].includes(node.type) && !node.computed &&
|
|
169
|
+
node.object.name === 'window' && node.property.name === 'FineDesign' && findBinding(scope, 'window') === undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// shortcut: resolve direct imports/destructuring only; add data-flow analysis if reassigned aliases need checking.
|
|
173
|
+
function componentName(node, scope) {
|
|
174
|
+
if (node.type === 'JSXIdentifier') {
|
|
175
|
+
const binding = findBinding(scope, node.name);
|
|
176
|
+
if (binding?.component && (!Object.hasOwn(binding, 'source') || isFineDesignNamespace(binding.source, binding.scope))) return binding.component;
|
|
177
|
+
} else if (node.type === 'JSXMemberExpression' && isFineDesignNamespace(node.object, scope)) {
|
|
178
|
+
return node.property.name;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function lintFiles(catalog, targets = ['.']) {
|
|
183
|
+
const files = [...new Set(targets.flatMap((t) => collectFiles(t)))];
|
|
184
|
+
const validValueExports = new Set(EXTRA_VALUE_EXPORTS);
|
|
185
|
+
const aliasToOwner = new Map();
|
|
186
|
+
for (const component of catalog.components) {
|
|
187
|
+
for (const exp of component.exports) {
|
|
188
|
+
if (!exp.includes('.')) validValueExports.add(exp);
|
|
189
|
+
}
|
|
190
|
+
if (component.id === 'svg-icon') {
|
|
191
|
+
for (const icon of component.aliases) validValueExports.add(icon);
|
|
192
|
+
} else {
|
|
193
|
+
for (const alias of component.aliases) {
|
|
194
|
+
aliasToOwner.set(alias.toLowerCase(), component);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const diagnostics = [];
|
|
200
|
+
|
|
201
|
+
for (const file of files) {
|
|
202
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
203
|
+
const typescript = /\.[cm]?tsx?$/i.test(file);
|
|
204
|
+
const report = (node, rule, severity, message, suggestion) => diagnostics.push({
|
|
205
|
+
file, line: node.loc.start.line, rule, severity, message, suggestion
|
|
206
|
+
});
|
|
207
|
+
const checkExport = (name, node, allowTypes = false, typeOnly = false) => {
|
|
208
|
+
if (validValueExports.has(name) || (allowTypes && KNOWN_TYPE_EXPORTS.has(name))) return;
|
|
209
|
+
if (typeOnly && name.endsWith('Props')) return;
|
|
210
|
+
|
|
211
|
+
const owner = aliasToOwner.get(name.toLowerCase());
|
|
212
|
+
let suggestion = 'Run "fine-design list" or "fine-design search" to verify public exports.';
|
|
213
|
+
if (owner) {
|
|
214
|
+
suggestion = `"${name}" is not a root export; use "${owner.exports.join(' / ')}"${name.includes('.') ? '' : ` (or compound subcomponent on ${owner.exports[0]})`} instead.`;
|
|
215
|
+
} else if (/(?:Outlined|Filled)$/.test(name)) {
|
|
216
|
+
const similarIcons = suggestSimilarComponents(catalog, name, 3);
|
|
217
|
+
suggestion = `"${name}" is not one of the 56 built-in icons.${similarIcons.length ? ` Closest matches: ${similarIcons.join(', ')}.` : ''} Run "fine-design doc SvgIcon --section 内置图标列表" to view all valid icon names.`;
|
|
218
|
+
} else {
|
|
219
|
+
const similar = suggestSimilarComponents(catalog, name, 3);
|
|
220
|
+
if (similar.length) suggestion = `Did you mean: ${similar.join(', ')}?`;
|
|
221
|
+
}
|
|
222
|
+
report(node, 'unknown-export', 'error', `Unknown export "${name}" from @fx-ui/fine-design.`, suggestion);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
function visit(node, scopes) {
|
|
226
|
+
const scope = scopes.get(node);
|
|
227
|
+
if (node.type === 'ImportDeclaration') {
|
|
228
|
+
const source = node.source.value;
|
|
229
|
+
if (/^(?:@fx-ui\/fine-design\/(?:es|lib)\/icons|@ant-design\/icons)$/.test(source)) {
|
|
230
|
+
report(node, 'deep-or-foreign-icon-import', 'error', `Avoid importing icons from "${source}".`,
|
|
231
|
+
'Import the 56 built-in icons or SvgIcon directly from "@fx-ui/fine-design".');
|
|
232
|
+
}
|
|
233
|
+
if (source === '@fx-ui/fine-design') {
|
|
234
|
+
for (const spec of node.specifiers.filter((item) => item.type === 'ImportSpecifier')) {
|
|
235
|
+
const typeOnly = node.importKind === 'type' || spec.importKind === 'type';
|
|
236
|
+
checkExport(spec.imported.name ?? spec.imported.value, spec, typescript || typeOnly, typeOnly);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
} else if (node.type === 'VariableDeclarator' && node.id.type === 'ObjectPattern') {
|
|
240
|
+
const init = node.init;
|
|
241
|
+
if (isFineDesignNamespace(init, scope)) {
|
|
242
|
+
for (const prop of node.id.properties) {
|
|
243
|
+
if (prop.type === 'ObjectProperty' && !prop.computed) checkExport(String(prop.key.name ?? prop.key.value), prop);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
} else if (node.type === 'JSXOpeningElement') {
|
|
247
|
+
const component = componentName(node.name, scope);
|
|
248
|
+
for (const attr of node.attributes.filter((item) => item.type === 'JSXAttribute')) {
|
|
249
|
+
const name = attr.name.name;
|
|
250
|
+
const value = (attr.value?.expression || attr.value)?.value;
|
|
251
|
+
if (component === 'Button' && name === 'type' && typeof value === 'string' && !BUTTON_TYPES.has(value)) {
|
|
252
|
+
report(attr, 'invalid-button-type', 'error', `Invalid Button type="${value}".`,
|
|
253
|
+
'Use type="primary" / "secondary" / "normal" / "negative" / "link" / "text" / "text-normal" / "bare", with the boolean danger prop for destructive actions.');
|
|
254
|
+
} else if (component === 'NextTable' && name === 'columns') {
|
|
255
|
+
report(attr, 'next-table-columns-prop', 'error', 'NextTable does not accept a "columns" prop.',
|
|
256
|
+
'Declare <NextTable.Column>, <NextTable.HeaderCell>, and <NextTable.Cell dataKey="..."> children instead.');
|
|
257
|
+
} else if (component === 'Dialog' && name === 'onCloseBtnClick') {
|
|
258
|
+
report(attr, 'dialog-deprecated-close-btn', 'warning', 'Dialog "onCloseBtnClick" is deprecated and fires alongside "onCancel" when clicking the close button.',
|
|
259
|
+
'Handle close and cancel solely via "onCancel".');
|
|
260
|
+
} else if (component === 'Tag' && name === 'color') {
|
|
261
|
+
report(attr, 'tag-color-prop', 'warning', 'Tag does not support a "color" prop.',
|
|
262
|
+
'Use semantic type ("default" | "primary" | "success" | "warning" | "error") or custom style={{ color, backgroundColor }}.');
|
|
263
|
+
} else if (component === 'ConfigProvider' && name === 'prefixCls' && value === 'fd') {
|
|
264
|
+
report(attr, 'config-provider-dumi-prefix', 'warning', 'ConfigProvider has hardcoded prefixCls="fd" (used only by the Dumi doc site).',
|
|
265
|
+
'Remove prefixCls="fd" so components match the default "f-" CSS class prefix in production and UMD builds.');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
for (const child of Object.values(node)) {
|
|
270
|
+
if (Array.isArray(child)) child.filter((item) => item?.type).forEach((item) => visit(item, scopes));
|
|
271
|
+
else if (child?.type) visit(child, scopes);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
for (const source of codeSources(file, content)) {
|
|
276
|
+
let ast;
|
|
277
|
+
try {
|
|
278
|
+
ast = parse(source.content, {
|
|
279
|
+
sourceType: 'unambiguous', startLine: source.startLine, attachComment: false,
|
|
280
|
+
plugins: [...(typescript ? [['typescript', { dts: /\.d\.[cm]?ts$/i.test(file) }]] : []),
|
|
281
|
+
...(!typescript || /tsx$/i.test(file) ? ['jsx'] : [])]
|
|
282
|
+
});
|
|
283
|
+
} catch (error) {
|
|
284
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
285
|
+
report({ loc: { start: error.loc } }, 'parse-error', 'error', error.message, 'Fix the syntax error before checking Fine Design APIs.');
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
visit(ast.program, collectScopes(ast.program));
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const errorCount = diagnostics.filter((d) => d.severity === 'error').length;
|
|
293
|
+
const warningCount = diagnostics.filter((d) => d.severity === 'warning').length;
|
|
294
|
+
return {
|
|
295
|
+
version: catalog.version,
|
|
296
|
+
scannedFiles: files.length,
|
|
297
|
+
errorCount,
|
|
298
|
+
warningCount,
|
|
299
|
+
passed: errorCount === 0,
|
|
300
|
+
diagnostics
|
|
301
|
+
};
|
|
302
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { exactVersion, readIndex } from './data.mjs';
|
|
2
|
+
import { ToolError } from './errors.mjs';
|
|
3
|
+
|
|
4
|
+
export const defaultRuntimeURL = 'https://fine-design-runtime.pages.dev/';
|
|
5
|
+
const hosted = { fineDesign: ['@fx-ui/fine-design', 'fine-design', 'fine-design.min.js'], fineDesignCss: ['@fx-ui/fine-design', 'fine-design', 'fine-design.min.css'], vanAnalysis: ['@van/analysis', 'van-analysis', 'van-analysis.min.js'], vanAnalysisCss: ['@van/analysis', 'van-analysis', 'van-analysis.min.css'] };
|
|
6
|
+
const invalid = (message) => { throw new ToolError('RUNTIME_INVALID', message, 1); };
|
|
7
|
+
|
|
8
|
+
export function validateRuntimeManifest(manifest) {
|
|
9
|
+
if (manifest?.schemaVersion !== 1 || !exactVersion.test(manifest.version) || !manifest.resources || Object.keys(manifest.resources).sort().join(',') !== ['react', 'reactDOM', ...Object.keys(hosted)].sort().join(',')) invalid('Invalid current runtime manifest.');
|
|
10
|
+
for (const [key, entry] of Object.entries(manifest.resources)) {
|
|
11
|
+
if (!entry || !exactVersion.test(entry.version) || !/^[a-f0-9]{64}$/.test(entry.sha256) || entry.integrity !== `sha256-${Buffer.from(entry.sha256, 'hex').toString('base64')}` || !Number.isSafeInteger(entry.size) || entry.size <= 0 || entry.type !== (key.endsWith('Css') ? 'style' : 'script')) invalid(`Invalid runtime resource: ${key}`);
|
|
12
|
+
if (hosted[key]) {
|
|
13
|
+
const [pkg, directory, filename] = hosted[key];
|
|
14
|
+
if (entry.package !== pkg || entry.path !== `${directory}/${entry.version}/${filename}` || entry.url) invalid(`Unexpected versioned resource path: ${key}`);
|
|
15
|
+
} else {
|
|
16
|
+
const pkg = key === 'react' ? 'react' : 'react-dom';
|
|
17
|
+
if (entry.package !== pkg || entry.path || entry.url !== `https://cdn.jsdelivr.net/npm/${pkg}@${entry.version}/umd/${pkg}.production.min.js`) invalid(`Unexpected React runtime: ${key}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const r = manifest.resources;
|
|
21
|
+
if (r.fineDesign.version !== manifest.version || r.fineDesignCss.version !== manifest.version || r.react.version !== r.reactDOM.version || r.vanAnalysis.version !== r.vanAnalysisCss.version) invalid('Runtime package versions do not match.');
|
|
22
|
+
return manifest;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function readRuntime(value = defaultRuntimeURL) {
|
|
26
|
+
let base;
|
|
27
|
+
try { base = new URL(value); } catch { invalid('Invalid runtime URL.'); }
|
|
28
|
+
if ((base.protocol !== 'https:' && !(base.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname))) || base.username || base.password || base.search || base.hash) invalid('Use an HTTPS runtime URL without credentials, query or fragment; HTTP is allowed on loopback.');
|
|
29
|
+
if (!base.pathname.endsWith('/')) base.pathname += '/';
|
|
30
|
+
const manifestURL = new URL('manifest.json', base);
|
|
31
|
+
let manifest;
|
|
32
|
+
try {
|
|
33
|
+
const response = await fetch(manifestURL, { redirect: 'error', signal: AbortSignal.timeout(15000), headers: { Accept: 'application/json' } });
|
|
34
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
35
|
+
if (!/application\/json/i.test(response.headers.get('content-type') || '')) throw new Error('Expected JSON MIME type');
|
|
36
|
+
const chunks = []; let size = 0;
|
|
37
|
+
for await (const chunk of response.body) {
|
|
38
|
+
size += chunk.length;
|
|
39
|
+
if (size > 1024 * 1024) throw new Error('Runtime metadata exceeds 1 MB');
|
|
40
|
+
chunks.push(chunk);
|
|
41
|
+
}
|
|
42
|
+
manifest = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
43
|
+
} catch (error) { throw new ToolError('RUNTIME_UNAVAILABLE', `Cannot read ${manifestURL}: ${error.message}. No other version was selected.`, 1); }
|
|
44
|
+
return { runtimeURL: base.href, manifestURL: manifestURL.href, manifest: validateRuntimeManifest(manifest) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function listRuntimes(runtimeURL) {
|
|
48
|
+
const current = await readRuntime(runtimeURL);
|
|
49
|
+
return { runtimeURL: current.runtimeURL, schemaVersion: 1, versions: [current.manifest.version] };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function resolveRuntime({ version, runtimeURL }) {
|
|
53
|
+
if (!exactVersion.test(version)) throw new ToolError('INVALID_ARGUMENT', 'Specify an exact component version.', 2);
|
|
54
|
+
const current = await readRuntime(runtimeURL);
|
|
55
|
+
if (current.manifest.version !== version) throw new ToolError('RUNTIME_VERSION_NOT_FOUND', `Only Fine Design ${current.manifest.version} is currently hosted; ${version} is unavailable. Historical UMD files are not retained.`, 3, { availableVersions: [current.manifest.version] });
|
|
56
|
+
const resources = Object.fromEntries(Object.entries(current.manifest.resources).map(([key, entry]) => [key, { ...entry, url: entry.url || new URL(entry.path, current.manifestURL).href }]));
|
|
57
|
+
const tags = ['fineDesignCss', 'react', 'reactDOM', 'fineDesign'].map((key) => {
|
|
58
|
+
const entry = resources[key];
|
|
59
|
+
return entry.type === 'style' ? `<link rel="stylesheet" href="${entry.url}" integrity="${entry.integrity}" crossorigin="anonymous">` : `<script src="${entry.url}" integrity="${entry.integrity}" crossorigin="anonymous"></script>`;
|
|
60
|
+
}).join('\n');
|
|
61
|
+
return { version, docsAvailable: Object.hasOwn(readIndex().versions, version), manifestURL: current.manifestURL, exampleURL: new URL('index.html', current.runtimeURL).href, resources, tags };
|
|
62
|
+
}
|
package/src/mcp.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { queryCatalog } from './core/catalog.mjs';
|
|
|
7
7
|
import { loadCatalog } from './core/data.mjs';
|
|
8
8
|
import { schemas, validateInput } from './core/contracts.mjs';
|
|
9
9
|
import { errorResult } from './core/errors.mjs';
|
|
10
|
+
import { listRuntimes, resolveRuntime } from './core/runtime.mjs';
|
|
10
11
|
|
|
11
12
|
export async function startMcp() {
|
|
12
13
|
const packageInfo = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
@@ -14,17 +15,20 @@ export async function startMcp() {
|
|
|
14
15
|
const descriptions = {
|
|
15
16
|
search_components: 'Search components, subcomponents and built-in icons; use nextOffset to browse subsequent pages.',
|
|
16
17
|
get_component_doc: 'Read component documentation, or pass summary: true to list section headings and example IDs first.',
|
|
17
|
-
get_component_example: 'Read example source files, dependencies and asset metadata. Set includeAssets to include binary base64 and oversized JSON fixture content.'
|
|
18
|
+
get_component_example: 'Read example source files, dependencies and asset metadata. Set includeAssets to include binary base64 and oversized JSON fixture content.',
|
|
19
|
+
list_browser_runtimes: 'Read the one currently hosted UMD version from its online manifest. Requires network access.',
|
|
20
|
+
get_browser_runtime: 'Resolve an exact component version to versioned current UMD URLs and SRI loading tags. Requires network access; never falls back to another version.'
|
|
18
21
|
};
|
|
19
22
|
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: Object.entries(schemas).map(([name, schema]) => ({
|
|
20
23
|
name, description: descriptions[name], inputSchema: z.toJSONSchema(schema, { target: 'draft-07' }),
|
|
21
|
-
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint:
|
|
24
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: name === 'get_browser_runtime' || name === 'list_browser_runtimes' }
|
|
22
25
|
})) }));
|
|
23
26
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
24
27
|
try {
|
|
25
28
|
const { name, arguments: input } = request.params;
|
|
26
29
|
const args = validateInput(name, input);
|
|
27
|
-
|
|
30
|
+
const result = name === 'get_browser_runtime' ? await resolveRuntime(args) : name === 'list_browser_runtimes' ? await listRuntimes(args.runtimeURL) : queryCatalog(loadCatalog(args.version), name, args);
|
|
31
|
+
return { content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
28
32
|
} catch (error) {
|
|
29
33
|
return { isError: true, content: [{ type: 'text', text: JSON.stringify(errorResult(error)) }] };
|
|
30
34
|
}
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"schemaVersion": 1,
|
|
3
|
-
"sourceState": "legacy-unversioned",
|
|
4
|
-
"checkedOn": "2026-11-02",
|
|
5
|
-
"resources": {
|
|
6
|
-
"react": {
|
|
7
|
-
"package": "react",
|
|
8
|
-
"version": "18.3.1",
|
|
9
|
-
"type": "script",
|
|
10
|
-
"global": "React",
|
|
11
|
-
"url": "https://cdn.jsdelivr.net/npm/react@18.3.1/umd/react.production.min.js",
|
|
12
|
-
"cors": true,
|
|
13
|
-
"size": 10751,
|
|
14
|
-
"sha256": "d949f1c3687aedadcedac85261865f29b17cd273997e7f6b2bfc53b2f9d4c4dd",
|
|
15
|
-
"integrity": "sha256-2Unxw2h67a3O2shSYYZfKbF80nOZfn9rK/xTsvnUxN0="
|
|
16
|
-
},
|
|
17
|
-
"reactDOM": {
|
|
18
|
-
"package": "react-dom",
|
|
19
|
-
"version": "18.3.1",
|
|
20
|
-
"type": "script",
|
|
21
|
-
"global": "ReactDOM",
|
|
22
|
-
"url": "https://cdn.jsdelivr.net/npm/react-dom@18.3.1/umd/react-dom.production.min.js",
|
|
23
|
-
"cors": true,
|
|
24
|
-
"size": 131835,
|
|
25
|
-
"sha256": "35f4f974f4b2bcd44da73963347f8952e341f83909e4498227d4e26b98f66f0d",
|
|
26
|
-
"integrity": "sha256-NfT5dPSyvNRNpzljNH+JUuNB+DkJ5EmCJ9Tia5j2bw0="
|
|
27
|
-
},
|
|
28
|
-
"fineDesign": {
|
|
29
|
-
"package": "@fx-ui/fine-design",
|
|
30
|
-
"version": null,
|
|
31
|
-
"type": "script",
|
|
32
|
-
"global": "FineDesign",
|
|
33
|
-
"url": "https://docs.fanruan.design/assets/react/fine-design-runtime/fine-design/fine-design.min.js",
|
|
34
|
-
"cors": false,
|
|
35
|
-
"size": 953541,
|
|
36
|
-
"sha256": "f2d13832e2102c1b14661e7b493cc40deefb074177ea711ffde03a782cad0cbe",
|
|
37
|
-
"integrity": "sha256-8tE4MuIQLBsUZh57STzEDe77B0F36nEf/eA6eCytDL4="
|
|
38
|
-
},
|
|
39
|
-
"fineDesignCss": {
|
|
40
|
-
"package": "@fx-ui/fine-design",
|
|
41
|
-
"version": null,
|
|
42
|
-
"type": "style",
|
|
43
|
-
"url": "https://docs.fanruan.design/assets/react/fine-design-runtime/fine-design/fine-design.min.css",
|
|
44
|
-
"cors": false,
|
|
45
|
-
"size": 534135,
|
|
46
|
-
"sha256": "099aa50dd23f91ebd7bba853dac37087a5e54fbc9609d6563ffc7a1659c57e1d",
|
|
47
|
-
"integrity": "sha256-CZqlDdI/kevXu6hT2sNwh6XlT7yWCdZWP/x6FlnFfh0="
|
|
48
|
-
},
|
|
49
|
-
"vanAnalysis": {
|
|
50
|
-
"package": "@van/analysis",
|
|
51
|
-
"version": null,
|
|
52
|
-
"type": "script",
|
|
53
|
-
"global": "VanNext",
|
|
54
|
-
"url": "https://docs.fanruan.design/assets/react/fine-design-runtime/van-analysis/van-analysis.min.js",
|
|
55
|
-
"cors": false,
|
|
56
|
-
"size": 1050632,
|
|
57
|
-
"sha256": "45ef12733c41ac3e13fe6b4a264d3e7a79403b93b2a88e6aa966598beaaac740",
|
|
58
|
-
"integrity": "sha256-Re8SczxBrD4T/mtKJk0+enlAO5OyqI5qqWZZi+qqx0A="
|
|
59
|
-
},
|
|
60
|
-
"vanAnalysisCss": {
|
|
61
|
-
"package": "@van/analysis",
|
|
62
|
-
"version": null,
|
|
63
|
-
"type": "style",
|
|
64
|
-
"url": "https://docs.fanruan.design/assets/react/fine-design-runtime/van-analysis/van-analysis.min.css",
|
|
65
|
-
"cors": false,
|
|
66
|
-
"size": 20787,
|
|
67
|
-
"sha256": "aebde3aecbe4f89cc459e7ce9e9f978290b538d6e90ed8aa0cbf74cf9227e25e",
|
|
68
|
-
"integrity": "sha256-rr3jrsvk+JzEWefOnp+XgpC1ONbpDtiqDL90z5In4l4="
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
}
|