@finedesign/cli 0.5.0 → 0.6.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.
@@ -2,10 +2,10 @@
2
2
  "schemaVersion": 1,
3
3
  "version": "1.25.0",
4
4
  "sourceKind": "repository-snapshot",
5
- "sourceRevision": "84cfbf3fb12672498c0a32d0374c9f88a22351ba",
5
+ "sourceRevision": "a88c1a76dc006929aa6ab9ce4f9de4ad0e926d0c",
6
6
  "sourceDirty": false,
7
- "contentHash": "b7a05ed31474496a1ffdc750cc738b1ad034578a4a828cfe03127520d791bafb",
8
- "catalogSha256": "8320b9ad699b658b483a1df4992126e9a54f67b3890c2746b6ce7b97862c26fb",
7
+ "contentHash": "c2edf1d31c61e83fa7996dca770a5e9ef87a5e67ce5fd55ccd4922a6e6bfe450",
8
+ "catalogSha256": "4b911bc129ea5a13070e2fcfac3a2f8d61087beb2758d2ae50b46e99180bba18",
9
9
  "skillFiles": {
10
10
  "references/component-guide.md": "612948840948e65f250998231eaa16fc41e8e27b9c03b19af32571422ca8185a",
11
11
  "references/docs-slug-map.md": "440ce5cf137fd22eabfcc5b51c3f55b85174aa643773ef0cedd5df542e77bbc2",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@finedesign/cli",
3
- "version": "0.5.0",
4
- "description": "Read-only, versioned Fine Design documentation for coding agents",
3
+ "version": "0.6.0",
4
+ "description": "Versioned Fine Design docs, code checks and agent setup for coding agents",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "registry": "https://registry.npmjs.org/",
package/src/cli.mjs CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { parseArgs } from 'node:util';
5
- import { queryCatalog, getComponentInfo, getComponentTokens, diffCatalogs } from './core/catalog.mjs';
5
+ import { queryCatalog, getComponentInfo, getComponentTokens, diffCatalogs, resolveComponentOrThrow } from './core/catalog.mjs';
6
6
  import { validateInput } from './core/contracts.mjs';
7
7
  import { loadCatalog, readIndex } from './core/data.mjs';
8
8
  import { resolveLintVersion, resolveVersion } from './core/version.mjs';
@@ -19,6 +19,8 @@ Commands:
19
19
  doc <component> Read component documentation
20
20
  token [component] [query] Inspect component or global Design Tokens
21
21
  example <component> [id] List examples or read one example's source and asset metadata
22
+ add <component> [id] Add/extract an example component into your project
23
+ init Initialize agent configuration (.cursorrules, Claude Skill, etc.)
22
24
  lint [files-or-dirs...] Scan code for Fine Design API traps and invalid imports
23
25
  diff [fromVer] [toVer] Compare component changes and migrations between versions
24
26
  doctor Inspect detected version, available catalogs and bundled Skill
@@ -29,6 +31,9 @@ Options:
29
31
  --fd-version <version> Exact Fine Design component version
30
32
  --project <directory> Project used to detect the installed version
31
33
  --component <name> Compare only this component (diff command only)
34
+ --agent <cursor|claude|codex|all> Target agent configuration (init command only)
35
+ --output <directory> Destination directory for extracted component (add command only)
36
+ --force Overwrite existing files (init and add commands)
32
37
  --runtime-url <url> Runtime hosting base URL (runtime command only)
33
38
  --format <text|json|markdown|html> Output format (markdown: doc/info/token; html: runtime)
34
39
  --section <heading> Doc section heading (exact or case-insensitive)
@@ -60,7 +65,10 @@ function runDoctor(values) {
60
65
  }
61
66
  } catch (error) {
62
67
  if (error instanceof ToolError && error.code === 'VERSION_NOT_DETECTED') {
63
- suggestions = error.context?.suggestions || [];
68
+ suggestions = [
69
+ 'For standalone HTML or an online preview, run "fine-design runtime list --format json" first and use the hosted version for component lookups. Verify rendering in the target preview separately.',
70
+ ...(error.context?.suggestions || [])
71
+ ];
64
72
  } else {
65
73
  throw error;
66
74
  }
@@ -79,6 +87,185 @@ function runDoctor(values) {
79
87
  };
80
88
  }
81
89
 
90
+ function runInit(values) {
91
+ const projectDir = path.resolve(values.project || process.cwd());
92
+ if (!fs.existsSync(projectDir) || !fs.statSync(projectDir).isDirectory()) {
93
+ throw new ToolError('INVALID_ARGUMENT', `Project directory does not exist: ${projectDir}`, 2);
94
+ }
95
+ const agent = (values.agent || 'all').toLowerCase();
96
+ const validAgents = ['cursor', 'claude', 'codex', 'all'];
97
+ if (!validAgents.includes(agent)) {
98
+ throw new ToolError('INVALID_ARGUMENT', `Invalid agent "${values.agent}". Allowed: ${validAgents.join(', ')}`, 2);
99
+ }
100
+
101
+ const bundledSkillDir = fileURLToPath(new URL('../skills/fine-design', import.meta.url));
102
+ const created = [];
103
+ const updated = [];
104
+
105
+ const agentInstructions = `# Fine Design Rules
106
+
107
+ 开发或修改 Fine Design 页面时,在目标项目目录运行 CLI。项目已安装 CLI 时用 \`npx fine-design\`,否则用 \`npx -y @finedesign/cli\`。
108
+
109
+ 1. 运行 \`doctor --format json\` 并读取 \`bundledSkillPath\` 指向的 Skill。先确定交付形式。接入现有 React 工程时沿用项目组件版本、壳层和同类页面。
110
+ 2. 交付独立 HTML 或无构建预览时,先单独运行 \`runtime list --format json\`,根据退出码判断清单是否可用。用 \`versions\` 返回的版本解析 UMD 资源,再查组件 API。
111
+ 3. 按目标版本用 \`info\` 查组件 API。\`list --format json\` 从 \`components\` 数组读取组件,\`example <组件>\` 先列示例 ID,按需再读源码。
112
+ 4. 对改动文件运行 \`lint\` 并执行项目已有检查。分别记录工程检查、UMD 清单解析和目标预览中的关键交互结果,标明未验证项。
113
+ `;
114
+
115
+ const cursorMdcContent = `---
116
+ description: Fine Design component library guidelines, API traps and verification rules
117
+ globs: **/*.{tsx,jsx,ts,js,html}
118
+ alwaysApply: false
119
+ ---
120
+
121
+ ${agentInstructions}`;
122
+
123
+ if (agent === 'cursor' || agent === 'all') {
124
+ const cursorRulesFile = path.join(projectDir, '.cursorrules');
125
+ if (!fs.existsSync(cursorRulesFile) || values.force) {
126
+ fs.writeFileSync(cursorRulesFile, agentInstructions, 'utf8');
127
+ created.push('.cursorrules');
128
+ } else {
129
+ const existing = fs.readFileSync(cursorRulesFile, 'utf8');
130
+ if (!existing.includes('fine-design') && !existing.includes('@finedesign/cli')) {
131
+ fs.appendFileSync(cursorRulesFile, `\n\n${agentInstructions}`, 'utf8');
132
+ updated.push('.cursorrules');
133
+ }
134
+ }
135
+ const cursorRulesDir = path.join(projectDir, '.cursor', 'rules');
136
+ fs.mkdirSync(cursorRulesDir, { recursive: true });
137
+ const mdcFile = path.join(cursorRulesDir, 'fine-design.mdc');
138
+ if (!fs.existsSync(mdcFile) || values.force) {
139
+ fs.writeFileSync(mdcFile, cursorMdcContent, 'utf8');
140
+ created.push('.cursor/rules/fine-design.mdc');
141
+ }
142
+ }
143
+
144
+ if (agent === 'claude' || agent === 'all') {
145
+ const claudeSkillsDir = path.join(projectDir, '.claude', 'skills', 'fine-design');
146
+ if (fs.existsSync(bundledSkillDir) && (!fs.existsSync(claudeSkillsDir) || values.force)) {
147
+ fs.mkdirSync(claudeSkillsDir, { recursive: true });
148
+ fs.cpSync(bundledSkillDir, claudeSkillsDir, { recursive: true });
149
+ created.push('.claude/skills/fine-design/');
150
+ }
151
+ const claudeMdFile = path.join(projectDir, 'CLAUDE.md');
152
+ if (!fs.existsSync(claudeMdFile) || values.force) {
153
+ fs.writeFileSync(claudeMdFile, agentInstructions, 'utf8');
154
+ created.push('CLAUDE.md');
155
+ } else {
156
+ const existing = fs.readFileSync(claudeMdFile, 'utf8');
157
+ if (!existing.includes('fine-design') && !existing.includes('@finedesign/cli')) {
158
+ fs.appendFileSync(claudeMdFile, `\n\n${agentInstructions}`, 'utf8');
159
+ updated.push('CLAUDE.md');
160
+ }
161
+ }
162
+ }
163
+
164
+ if (agent === 'codex' || agent === 'all') {
165
+ const codexSkillsDir = path.join(projectDir, '.agents', 'skills', 'fine-design');
166
+ if (fs.existsSync(bundledSkillDir) && (!fs.existsSync(codexSkillsDir) || values.force)) {
167
+ fs.mkdirSync(codexSkillsDir, { recursive: true });
168
+ fs.cpSync(bundledSkillDir, codexSkillsDir, { recursive: true });
169
+ created.push('.agents/skills/fine-design/');
170
+ }
171
+ const agentsMdFile = path.join(projectDir, 'AGENTS.md');
172
+ if (!fs.existsSync(agentsMdFile) || values.force) {
173
+ fs.writeFileSync(agentsMdFile, agentInstructions, 'utf8');
174
+ created.push('AGENTS.md');
175
+ } else {
176
+ const existing = fs.readFileSync(agentsMdFile, 'utf8');
177
+ if (!existing.includes('fine-design') && !existing.includes('@finedesign/cli')) {
178
+ fs.appendFileSync(agentsMdFile, `\n\n${agentInstructions}`, 'utf8');
179
+ updated.push('AGENTS.md');
180
+ }
181
+ }
182
+ }
183
+
184
+ return {
185
+ projectDir,
186
+ agent,
187
+ created: [...new Set(created)],
188
+ updated: [...new Set(updated)]
189
+ };
190
+ }
191
+
192
+ function runAdd(componentArg, exampleArg, values) {
193
+ if (!componentArg) {
194
+ throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design add <component> [id] [options]', 2);
195
+ }
196
+ const version = resolveVersion(values['fd-version'], values.project);
197
+ const catalog = loadCatalog(version);
198
+ const resolvedComp = resolveComponentOrThrow(catalog, componentArg);
199
+
200
+ let exampleId = exampleArg;
201
+ if (!exampleId) {
202
+ if (resolvedComp.examples?.some((ex) => ex.id === 'basic')) {
203
+ exampleId = 'basic';
204
+ } else if (resolvedComp.examples?.length > 0) {
205
+ exampleId = resolvedComp.examples[0].id;
206
+ } else {
207
+ throw new ToolError('EXAMPLE_NOT_FOUND', `Component "${resolvedComp.title || resolvedComp.id}" has no examples available.`, 4);
208
+ }
209
+ }
210
+
211
+ const example = queryCatalog(catalog, 'get_component_example', {
212
+ version,
213
+ component: resolvedComp.id,
214
+ exampleId,
215
+ includeAssets: true
216
+ });
217
+ if (!example?.files?.length) {
218
+ throw new ToolError('EXAMPLE_NOT_FOUND', `Example "${exampleId}" not found for ${resolvedComp.id}.`, 4);
219
+ }
220
+
221
+ const projectDir = path.resolve(values.project || process.cwd());
222
+ let targetDir;
223
+ if (values.output) {
224
+ targetDir = path.resolve(projectDir, values.output);
225
+ } else {
226
+ const hasSrc = fs.existsSync(path.join(projectDir, 'src'));
227
+ targetDir = hasSrc
228
+ ? path.join(projectDir, 'src', 'components', resolvedComp.id)
229
+ : path.join(projectDir, 'components', resolvedComp.id);
230
+ }
231
+ let sourceDir = path.posix.dirname(example.entry);
232
+ while (sourceDir !== '.' && example.files.some((file) => !file.path.startsWith(`${sourceDir}/`))) {
233
+ sourceDir = path.posix.dirname(sourceDir);
234
+ }
235
+ const prefix = sourceDir === '.' ? '' : `${sourceDir}/`;
236
+ const files = example.files.map((file) => ({ file, destPath: path.join(targetDir, file.path.slice(prefix.length)) }));
237
+ const writtenFiles = [];
238
+
239
+ for (const { destPath } of files) {
240
+ if (fs.existsSync(destPath) && !values.force) {
241
+ throw new ToolError('FILE_EXISTS', `File already exists: ${path.relative(projectDir, destPath)}. Use --force to overwrite.`, 1);
242
+ }
243
+ }
244
+ for (const { file, destPath } of files) {
245
+ fs.mkdirSync(path.dirname(destPath), { recursive: true });
246
+ if (file.encoding === 'base64') {
247
+ fs.writeFileSync(destPath, Buffer.from(file.content, 'base64'));
248
+ } else {
249
+ fs.writeFileSync(destPath, file.content, 'utf8');
250
+ }
251
+ writtenFiles.push(path.relative(projectDir, destPath));
252
+ }
253
+
254
+ const requiredDependencies = (example.dependencies || []).filter(
255
+ (dep) => !['react', 'react-dom', '@fx-ui/fine-design'].includes(dep)
256
+ );
257
+
258
+ return {
259
+ component: resolvedComp.id,
260
+ exampleId,
261
+ version,
262
+ targetDir: path.relative(projectDir, targetDir) || '.',
263
+ writtenFiles,
264
+ dependencies: example.dependencies || [],
265
+ requiredDependencies
266
+ };
267
+ }
268
+
82
269
  export async function main(argv) {
83
270
  let format = 'text';
84
271
  try {
@@ -86,7 +273,8 @@ export async function main(argv) {
86
273
  help: { type: 'boolean' }, version: { type: 'boolean' }, 'fd-version': { type: 'string' }, project: { type: 'string' },
87
274
  format: { type: 'string' }, section: { type: 'string' }, toc: { type: 'boolean' }, summary: { type: 'boolean' },
88
275
  offset: { type: 'string' }, limit: { type: 'string' }, 'include-assets': { type: 'boolean' },
89
- 'runtime-url': { type: 'string' }, component: { type: 'string' }
276
+ 'runtime-url': { type: 'string' }, component: { type: 'string' },
277
+ agent: { type: 'string' }, output: { type: 'string' }, force: { type: 'boolean' }
90
278
  }});
91
279
  format = values.format || 'text';
92
280
  if (!['text', 'json', 'markdown', 'html'].includes(format)) throw new ToolError('INVALID_ARGUMENT', 'Unknown output format.', 2);
@@ -97,6 +285,9 @@ export async function main(argv) {
97
285
  const summaryFlag = Boolean(values.toc || values.summary);
98
286
  if (command !== 'runtime' && (values['runtime-url'] !== undefined)) throw new ToolError('INVALID_ARGUMENT', 'Runtime options are only supported for runtime.', 2);
99
287
  if (command !== 'diff' && values.component !== undefined) throw new ToolError('INVALID_ARGUMENT', '--component is only supported for diff.', 2);
288
+ if (command !== 'init' && values.agent !== undefined) throw new ToolError('INVALID_ARGUMENT', '--agent is only supported for init.', 2);
289
+ if (command !== 'add' && values.output !== undefined) throw new ToolError('INVALID_ARGUMENT', '--output is only supported for add.', 2);
290
+ if (!['init', 'add'].includes(command) && values.force !== undefined) throw new ToolError('INVALID_ARGUMENT', '--force is only supported for init and add.', 2);
100
291
  if (format === 'markdown' && !['doc', 'info', 'token'].includes(command)) {
101
292
  throw new ToolError('INVALID_ARGUMENT', 'Markdown output format is only supported for the doc, info and token commands.', 2);
102
293
  }
@@ -128,6 +319,44 @@ export async function main(argv) {
128
319
  }
129
320
  return;
130
321
  }
322
+ if (command === 'init') {
323
+ if (values.version || args.length > 0 || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || values['fd-version'] !== undefined || !['text', 'json'].includes(format)) {
324
+ throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design init [--agent <cursor|claude|codex|all>] [--project <dir>] [--force] [--format text|json]', 2);
325
+ }
326
+ const report = runInit(values);
327
+ if (format === 'json') {
328
+ console.log(JSON.stringify(report));
329
+ } else {
330
+ const lines = [
331
+ `Initialized Fine Design agent configuration (${report.agent}) in ${report.projectDir}:`,
332
+ ' Created files:',
333
+ ...(report.created.length ? report.created.map((f) => ` - ${f}`) : [' - none']),
334
+ ' Updated files:',
335
+ ...(report.updated.length ? report.updated.map((f) => ` - ${f}`) : [' - none'])
336
+ ];
337
+ console.log(lines.join('\n'));
338
+ }
339
+ return;
340
+ }
341
+ if (command === 'add') {
342
+ if (values.version || args.length < 1 || args.length > 2 || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined || !['text', 'json'].includes(format)) {
343
+ throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design add <component> [id] [--output <dir>] [--force] [--fd-version <version>] [--format text|json]', 2);
344
+ }
345
+ const report = runAdd(args[0], args[1], values);
346
+ if (format === 'json') {
347
+ console.log(JSON.stringify(report));
348
+ } else {
349
+ const lines = [
350
+ `Added ${report.component} (${report.exampleId}) to ${report.targetDir}:`,
351
+ ...report.writtenFiles.map((f) => ` - ${f}`)
352
+ ];
353
+ if (report.requiredDependencies.length) {
354
+ lines.push('', 'Required dependencies:', ` npm install ${report.requiredDependencies.join(' ')}`);
355
+ }
356
+ console.log(lines.join('\n'));
357
+ }
358
+ return;
359
+ }
131
360
  if (command === 'list') {
132
361
  if (values.version || args.length > 0 || values.section !== undefined || summaryFlag || values.offset !== undefined || values.limit !== undefined || values['include-assets'] !== undefined) {
133
362
  throw new ToolError('INVALID_ARGUMENT', 'Invalid options for list. Use --help for usage.', 2);
@@ -84,7 +84,7 @@ function sourceMetadata(catalog) {
84
84
  };
85
85
  }
86
86
 
87
- function resolveComponentOrThrow(catalog, rawComponent) {
87
+ export function resolveComponentOrThrow(catalog, rawComponent) {
88
88
  const targetName = rawComponent.toLowerCase();
89
89
  const component =
90
90
  catalog.components.find((item) =>
@@ -5,23 +5,23 @@ const version = z.string().min(1).max(80);
5
5
  const component = z.string().min(1).max(100);
6
6
  export const schemas = {
7
7
  search_components: z.object({
8
- version,
8
+ version: version.optional(),
9
9
  query: z.string().max(200),
10
10
  offset: z.number().int().min(0).max(10000).optional(),
11
11
  limit: z.number().int().min(1).max(200).optional()
12
12
  }).strict(),
13
13
  get_component_doc: z.object({
14
- version,
14
+ version: version.optional(),
15
15
  component,
16
16
  section: z.string().min(1).max(200).optional(),
17
17
  summary: z.boolean().optional().describe('Return only metadata, section headings and example IDs without full markdown.')
18
18
  }).strict(),
19
19
  get_component_info: z.object({
20
- version,
20
+ version: version.optional(),
21
21
  component
22
22
  }).strict(),
23
23
  get_component_tokens: z.object({
24
- version,
24
+ version: version.optional(),
25
25
  component: component.optional(),
26
26
  query: z.string().max(200).optional()
27
27
  }).strict(),
@@ -38,9 +38,9 @@ export const schemas = {
38
38
  path: z.string().min(1).max(1024).optional()
39
39
  }).strict(),
40
40
  list_browser_runtimes: z.object({ runtimeURL: z.string().max(2048).optional() }).strict(),
41
- get_browser_runtime: z.object({ version, runtimeURL: z.string().max(2048).optional() }).strict(),
41
+ get_browser_runtime: z.object({ version: version.optional(), runtimeURL: z.string().max(2048).optional() }).strict(),
42
42
  get_component_example: z.object({
43
- version,
43
+ version: version.optional(),
44
44
  component,
45
45
  exampleId: z.string().min(1).max(200).optional().describe('Omit to list available example IDs and titles.'),
46
46
  includeAssets: z.boolean().optional().describe('Include binary asset content as base64 and full oversized JSON fixture content; default returns metadata/preview for large assets.')
package/src/core/lint.mjs CHANGED
@@ -138,6 +138,9 @@ function collectScopes(program) {
138
138
  const targetScope = node.kind === 'var' ? scope.varScope : scope;
139
139
  for (const declaration of node.declarations) {
140
140
  bindPattern(declaration.id, targetScope);
141
+ if (declaration.id.type === 'Identifier' && declaration.init) {
142
+ targetScope.bindings.set(declaration.id.name, { initializer: declaration.init, scope });
143
+ }
141
144
  if (declaration.id.type !== 'ObjectPattern') continue;
142
145
  for (const prop of declaration.id.properties) {
143
146
  if (prop.type !== 'ObjectProperty' || prop.computed) continue;
@@ -161,24 +164,47 @@ function findBinding(scope, name) {
161
164
  }
162
165
  }
163
166
 
167
+ function isGlobalMember(node, scope, object, property) {
168
+ return ['MemberExpression', 'JSXMemberExpression'].includes(node?.type) && !node.computed &&
169
+ node.object.name === object && node.property.name === property && findBinding(scope, object) === undefined;
170
+ }
171
+
164
172
  function isFineDesignNamespace(node, scope) {
165
- if (!node) return false;
166
- if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
173
+ if (node?.type === 'Identifier' || node?.type === 'JSXIdentifier') {
167
174
  const binding = findBinding(scope, node.name);
168
- return Boolean(binding?.namespace || (node.name === 'FineDesign' && binding === undefined));
175
+ return Boolean(binding?.namespace || (node.name === 'FineDesign' && binding === undefined) ||
176
+ isGlobalMember(binding?.initializer, binding?.scope, 'window', 'FineDesign'));
169
177
  }
170
- return ['MemberExpression', 'JSXMemberExpression'].includes(node.type) && !node.computed &&
171
- node.object.name === 'window' && node.property.name === 'FineDesign' && findBinding(scope, 'window') === undefined;
178
+ return isGlobalMember(node, scope, 'window', 'FineDesign');
172
179
  }
173
180
 
174
- // shortcut: resolve direct imports/destructuring only; add data-flow analysis if reassigned aliases need checking.
181
+ // shortcut: resolve imports and direct initializers in the same script, add data-flow analysis if reassigned or cross-script aliases need checking.
175
182
  function componentName(node, scope) {
176
- if (node.type === 'JSXIdentifier') {
183
+ if (node?.type === 'JSXIdentifier' || node?.type === 'Identifier') {
177
184
  const binding = findBinding(scope, node.name);
178
185
  if (binding?.component && (!Object.hasOwn(binding, 'source') || isFineDesignNamespace(binding.source, binding.scope))) return binding.component;
179
- } else if (node.type === 'JSXMemberExpression' && isFineDesignNamespace(node.object, scope)) {
180
- return node.property.name;
186
+ node = binding?.initializer;
187
+ scope = binding?.scope;
188
+ }
189
+ if (['MemberExpression', 'JSXMemberExpression'].includes(node?.type) && !node.computed) {
190
+ if (isFineDesignNamespace(node.object, scope)) return node.property.name;
191
+ const parent = componentName(node.object, scope);
192
+ if (parent) return `${parent}.${node.property.name}`;
193
+ }
194
+ }
195
+
196
+ function isReactCreateElement(node, scope) {
197
+ if (node.type === 'Identifier') {
198
+ const binding = findBinding(scope, node.name);
199
+ node = binding?.initializer;
200
+ scope = binding?.scope;
181
201
  }
202
+ if (node?.type !== 'MemberExpression' || node.computed || node.property.name !== 'createElement') return false;
203
+ if (isGlobalMember(node.object, scope, 'window', 'React')) return true;
204
+ if (node.object.type !== 'Identifier') return false;
205
+ const binding = findBinding(scope, node.object.name);
206
+ return (node.object.name === 'React' && binding === undefined) ||
207
+ isGlobalMember(binding?.initializer, binding?.scope, 'window', 'React');
182
208
  }
183
209
 
184
210
  export function lintFiles(catalog, targets = ['.']) {
@@ -206,6 +232,12 @@ export function lintFiles(catalog, targets = ['.']) {
206
232
  const report = (node, rule, severity, message, suggestion) => diagnostics.push({
207
233
  file, line: node.loc.start.line, rule, severity, message, suggestion
208
234
  });
235
+ const checkButtonType = (node, value) => {
236
+ if (typeof value === 'string' && !BUTTON_TYPES.has(value)) {
237
+ report(node, 'invalid-button-type', 'error', `Invalid Button type="${value}".`,
238
+ 'Use type="primary" / "secondary" / "normal" / "negative" / "link" / "text" / "text-normal" / "bare", with the boolean danger prop for destructive actions.');
239
+ }
240
+ };
209
241
  const checkExport = (name, node, allowTypes = false, typeOnly = false) => {
210
242
  if (validValueExports.has(name) || (allowTypes && KNOWN_TYPE_EXPORTS.has(name))) return;
211
243
  if (typeOnly && name.endsWith('Props')) return;
@@ -232,6 +264,10 @@ export function lintFiles(catalog, targets = ['.']) {
232
264
  report(node, 'deep-or-foreign-icon-import', 'error', `Avoid importing icons from "${source}".`,
233
265
  'Import the 56 built-in icons or SvgIcon directly from "@fx-ui/fine-design".');
234
266
  }
267
+ if (source === '@fx-ui/fine-design/dist/fine-design.min.css') {
268
+ report(node, 'invalid-package-stylesheet', 'error', `"${source}" uses the hosted UMD filename as a package import.`,
269
+ 'Import "@fx-ui/fine-design/dist/fine_design.css" in React projects. For standalone HTML, load the stylesheet URL from the runtime manifest.');
270
+ }
235
271
  if (source === '@fx-ui/fine-design') {
236
272
  for (const spec of node.specifiers.filter((item) => item.type === 'ImportSpecifier')) {
237
273
  const typeOnly = node.importKind === 'type' || spec.importKind === 'type';
@@ -245,17 +281,74 @@ export function lintFiles(catalog, targets = ['.']) {
245
281
  if (prop.type === 'ObjectProperty' && !prop.computed) checkExport(String(prop.key.name ?? prop.key.value), prop);
246
282
  }
247
283
  }
284
+ } else if (node.type === 'CallExpression' && node.arguments[1]?.type === 'ObjectExpression' &&
285
+ isReactCreateElement(node.callee, scope) && componentName(node.arguments[0], scope) === 'Button') {
286
+ const type = node.arguments[1].properties.findLast((prop) =>
287
+ prop.type === 'SpreadElement' || prop.computed || (prop.key.name ?? prop.key.value) === 'type');
288
+ if (type?.type === 'ObjectProperty' && !type.computed) checkButtonType(type, type.value.value);
248
289
  } else if (node.type === 'JSXOpeningElement') {
249
290
  const component = componentName(node.name, scope);
250
- for (const attr of node.attributes.filter((item) => item.type === 'JSXAttribute')) {
291
+ const jsxAttrs = node.attributes.filter((item) => item.type === 'JSXAttribute');
292
+ const attrNames = new Set(jsxAttrs.map((item) => item.name?.name));
293
+
294
+ if (component === 'Pagination' && attrNames.has('sizeSet') && !attrNames.has('showPageSize')) {
295
+ const sizeSetAttr = jsxAttrs.find((item) => item.name?.name === 'sizeSet');
296
+ report(sizeSetAttr, 'pagination-missing-showpagesize', 'warning',
297
+ 'Pagination has "sizeSet" but lacks "showPageSize".',
298
+ 'Provide showPageSize={(size) => String(size)} so the page size selector is displayed.');
299
+ }
300
+
301
+ for (const attr of jsxAttrs) {
251
302
  const name = attr.name.name;
252
303
  const value = (attr.value?.expression || attr.value)?.value;
253
- if (component === 'Button' && name === 'type' && typeof value === 'string' && !BUTTON_TYPES.has(value)) {
254
- report(attr, 'invalid-button-type', 'error', `Invalid Button type="${value}".`,
255
- 'Use type="primary" / "secondary" / "normal" / "negative" / "link" / "text" / "text-normal" / "bare", with the boolean danger prop for destructive actions.');
304
+ if (component === 'Button' && name === 'type') {
305
+ checkButtonType(attr, value);
256
306
  } else if (component === 'NextTable' && name === 'columns') {
257
307
  report(attr, 'next-table-columns-prop', 'error', 'NextTable does not accept a "columns" prop.',
258
308
  'Declare <NextTable.Column>, <NextTable.HeaderCell>, and <NextTable.Cell dataKey="..."> children instead.');
309
+ } else if (component === 'NextTable' && name === 'pagination' && attr.value?.type === 'JSXExpressionContainer' && attr.value.expression?.type === 'ObjectExpression') {
310
+ const props = attr.value.expression.properties;
311
+ const propMap = new Map();
312
+ for (const prop of props) {
313
+ if (prop.type === 'ObjectProperty' && !prop.computed) {
314
+ propMap.set(prop.key.name ?? prop.key.value, prop);
315
+ }
316
+ }
317
+ if (propMap.has('current')) {
318
+ report(propMap.get('current'), 'pagination-current-prop', 'error',
319
+ 'NextTable pagination object does not accept a "current" property.',
320
+ 'Use "page" instead of "current" to specify the active page.');
321
+ }
322
+ if (propMap.has('pageSize')) {
323
+ report(propMap.get('pageSize'), 'pagination-pagesize-prop', 'error',
324
+ 'NextTable pagination object does not accept a "pageSize" property.',
325
+ 'Use "size" instead of "pageSize" to specify the page size.');
326
+ }
327
+ if (propMap.has('sizeSet') && !propMap.has('showPageSize')) {
328
+ report(propMap.get('sizeSet'), 'pagination-missing-showpagesize', 'warning',
329
+ 'NextTable pagination object has "sizeSet" but lacks "showPageSize".',
330
+ 'Provide showPageSize: (size) => String(size) so the page size selector is displayed.');
331
+ }
332
+ } else if (component === 'Select' && name === 'items') {
333
+ report(attr, 'select-items-prop', 'error',
334
+ 'Select does not accept an "items" prop.',
335
+ 'Use "options" ({ label, value }[]) for Select, or use Combo / Combo.Check if you intended a Combo dropdown with items.');
336
+ } else if ((component === 'Combo' || component === 'Combo.Check') && name === 'options') {
337
+ report(attr, 'combo-options-prop', 'error',
338
+ `${component} does not accept an "options" prop.`,
339
+ `Use "items" ({ text, value }[]) for ${component}.`);
340
+ } else if (component === 'PopConfirm' && name === 'onConfirm') {
341
+ report(attr, 'popconfirm-onconfirm-prop', 'error',
342
+ 'PopConfirm does not accept an "onConfirm" prop.',
343
+ 'Use "onOk" for confirmation callback in PopConfirm.');
344
+ } else if (component === 'Pagination' && name === 'current') {
345
+ report(attr, 'pagination-current-prop', 'error',
346
+ 'Pagination does not accept a "current" prop.',
347
+ 'Use "page" instead of "current" to specify the active page.');
348
+ } else if (component === 'Pagination' && name === 'pageSize') {
349
+ report(attr, 'pagination-pagesize-prop', 'error',
350
+ 'Pagination does not accept a "pageSize" prop.',
351
+ 'Use "size" instead of "pageSize" to specify the page size.');
259
352
  } else if (component === 'Dialog' && name === 'onCloseBtnClick') {
260
353
  report(attr, 'dialog-deprecated-close-btn', 'warning', 'Dialog "onCloseBtnClick" is deprecated and fires alongside "onCancel" when clicking the close button.',
261
354
  'Handle close and cancel solely via "onCancel".');
@@ -40,7 +40,12 @@ async function readRuntime(value = defaultRuntimeURL) {
40
40
  chunks.push(chunk);
41
41
  }
42
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); }
43
+ } catch (error) {
44
+ throw new ToolError('RUNTIME_UNAVAILABLE', `Cannot read ${manifestURL}: ${error.message}. No other version was selected.`, 1, {
45
+ manifestURL: manifestURL.href,
46
+ suggestions: ['Check access to the manifest from this environment or pass --runtime-url with a verified host.']
47
+ });
48
+ }
44
49
  return { runtimeURL: base.href, manifestURL: manifestURL.href, manifest: validateRuntimeManifest(manifest) };
45
50
  }
46
51
 
@@ -50,13 +55,14 @@ export async function listRuntimes(runtimeURL) {
50
55
  }
51
56
 
52
57
  export async function resolveRuntime({ version, runtimeURL }) {
53
- if (!exactVersion.test(version)) throw new ToolError('INVALID_ARGUMENT', 'Specify an exact component version.', 2);
58
+ if (version !== undefined && !exactVersion.test(version)) throw new ToolError('INVALID_ARGUMENT', 'Specify an exact component version.', 2);
54
59
  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] });
60
+ const targetVersion = version || current.manifest.version;
61
+ if (current.manifest.version !== targetVersion) throw new ToolError('RUNTIME_VERSION_NOT_FOUND', `Only Fine Design ${current.manifest.version} is currently hosted; ${targetVersion} is unavailable. Historical UMD files are not retained.`, 3, { availableVersions: [current.manifest.version] });
56
62
  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
63
  const tags = ['fineDesignCss', 'react', 'reactDOM', 'fineDesign'].map((key) => {
58
64
  const entry = resources[key];
59
65
  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
66
  }).join('\n');
61
- return { version, docsAvailable: Object.hasOwn(readIndex().versions, version), manifestURL: current.manifestURL, exampleURL: new URL('index.html', current.runtimeURL).href, resources, tags };
67
+ return { version: targetVersion, docsAvailable: Object.hasOwn(readIndex().versions, targetVersion), manifestURL: current.manifestURL, exampleURL: new URL('index.html', current.runtimeURL).href, resources, tags };
62
68
  }
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { exactVersion } from './data.mjs';
3
+ import { exactVersion, readIndex } from './data.mjs';
4
4
  import { ToolError } from './errors.mjs';
5
5
 
6
6
  export function resolveVersion(explicit, project = process.cwd()) {
@@ -52,3 +52,13 @@ export function resolveLintVersion(explicit, targets) {
52
52
  const [version] = versions;
53
53
  return version;
54
54
  }
55
+
56
+ export function resolveMcpVersion(explicit, project = process.cwd()) {
57
+ if (explicit !== undefined) return explicit;
58
+ try {
59
+ return resolveVersion(undefined, project);
60
+ } catch {
61
+ const index = readIndex();
62
+ return index.skillVersion || Object.keys(index.versions).sort().at(-1);
63
+ }
64
+ }