@finedesign/cli 0.9.0 → 0.11.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.
@@ -0,0 +1,16 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "version": "1.25.1",
4
+ "sourceKind": "repository-snapshot",
5
+ "sourceRevision": "3d98d9e66715dfc929541518fc9b7b6d35125df3",
6
+ "sourceDirty": false,
7
+ "contentHash": "82938a71102f739db308fd19fa24cbf12b3c394bb7fa9bab5c51f9d9fe6da251",
8
+ "catalogSha256": "9969ca9ccabe8eecb5188f30264fb6e511f3ed9570490e0a5d48f20074525eee",
9
+ "skillFiles": {
10
+ "references/component-guide.md": "a183ebdfd651e003117bff47849268908a9d4e0e0c1a15d8670f204ca892b6d6",
11
+ "references/docs-slug-map.md": "067e823aab9b8101f5119e6fec9f86845feabf5286f003caa1a58b62dfd73f28",
12
+ "references/imports-and-setup.md": "cd9c8452d62bebecf2fb6a2ffd74772c673e41c3290f424d96674c3ad327bc74",
13
+ "references/theme-and-dark-mode.md": "2eccae4930ea993e7088eee03a4b4a0f1c839033079db5f21f8c60e0fe8168d1",
14
+ "SKILL.md": "e1024432c8b37d88057cfd851d40d3f1747b8b0354d12f9c4d510810757d62c8"
15
+ }
16
+ }
package/data/index.json CHANGED
@@ -8,7 +8,11 @@
8
8
  "1.25.0": {
9
9
  "catalog": "1.25.0/catalog.json",
10
10
  "manifest": "1.25.0/manifest.json"
11
+ },
12
+ "1.25.1": {
13
+ "catalog": "1.25.1/catalog.json",
14
+ "manifest": "1.25.1/manifest.json"
11
15
  }
12
16
  },
13
- "skillVersion": "1.25.0"
17
+ "skillVersion": "1.25.1"
14
18
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finedesign/cli",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Versioned Fine Design docs, code checks and agent setup for coding agents",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -9,10 +9,12 @@ Use the sections relevant to the task. Selection choices are defaults for new wo
9
9
  | Free text / numeric entry | `Input` / `InputNumber` |
10
10
  | Typing with suggestions | `AutoComplete`; ordinary dropdowns use `Select` |
11
11
  | Searchable or multi-select dropdown | `Select` with `showSearch` and/or `multiple` |
12
+ | Business dropdown with built-in paged loading | `Combo` / `Combo.Check` with `onFetchItems` |
12
13
  | Small set of visible choices | `Radio.Group` / `Check.Group` |
13
- | Tree selection / linked levels | `TreeSelect` / `MCascader` |
14
+ | Tree nodes / paths across linked levels | `TreeSelect` / `MCascader`, both with single and multiple selection |
14
15
  | Date-time point / interval | `Datetime` / `DatetimeRange` |
15
- | New tabular page | `NextTable`; use `virtualized` when needed for volume |
16
+ | New tabular page | `NextTable`, with `virtualized` for row virtualization |
17
+ | Horizontal column virtualization or a table pipeline | `VirtualTable` |
16
18
  | Identity / status / count | `Avatar` / `Tag` / `Badge` |
17
19
  | Loading / block placeholder / empty or error result | `Spin` / `Skeleton` / `Result` |
18
20
  | Persistent inline guidance / transient global feedback | `Instruction` / `Notification` or `Toast` |
@@ -29,7 +31,8 @@ Use the sections relevant to the task. Selection choices are defaults for new wo
29
31
  | `Button` | Destructive text actions use `type="text" danger`; `type="text-danger"` is not a public `ButtonType` |
30
32
  | `Select`, `AutoComplete` | `options` use `{ label, value }` |
31
33
  | `Combo`, `Combo.Check` | `items` use `{ text, value }`; `Combo.Check` is nested, not a separate root export |
32
- | `NextTable` | Declare `Column`, `HeaderCell`, and `Cell` children, not a `columns` array; prefer its `pagination` when it owns paging |
34
+ | `MCascader` | Use `options`, `showSearch`, and `allowClear`. Single selection returns one path, while multiple selection returns an array of paths. |
35
+ | `NextTable` | Declare `Column`, `HeaderCell`, and `Cell` children. When using `pagination`, pass the current page of rows in `data`. |
33
36
  | `Pagination`, `NextTable.pagination` | Use `page`, `size`, `sizeSet`, `count`; `sizeSet` contains the current `size`. To display the size chooser, also provide `showPageSize: size => String(size)`; `sizeSet` alone does not show it |
34
37
  | Legacy `DataTable` | Measurement may call `render('', {}, 0)`; guard the fields your renderer needs before reading records or attaching actions |
35
38
  | `PopConfirm` | Connect the confirmed mutation through `onOk` |
@@ -26,8 +26,8 @@ Use this map before fetching the overview page. If a name is missing or the curr
26
26
  | Tree | `Tree` | `tree-cn` | Root export |
27
27
  | AutoComplete | `AutoComplete` | `auto-complete-cn` | Root export |
28
28
  | Check | `Check` | `check-cn` | Root export |
29
- | MCascader | `MCascader` | `m-cascader-cn` | Public docs route exists; page title is Cascader |
30
- | Cascader | `MCascader` preferred | `m-cascader-cn` | Online `cascader-cn` is 404; docs indicate legacy Cascader is being replaced |
29
+ | MCascader | `MCascader` | `m-cascader-cn` | The main page documents `MCascader`. |
30
+ | Cascader | `Cascader` | `m-cascader-cn` | The 旧版 Cascader tab documents the legacy API. |
31
31
  | ColorPicker | `ColorPicker` | `color-picker-cn` | Root export |
32
32
  | DatePicker | `DatePicker` | `date-picker-cn` | Low-level date panel root export; standard date input uses `Datetime` |
33
33
  | Datetime | `Datetime` | `datetime-cn` | Root export |
@@ -49,8 +49,8 @@ Use this map before fetching the overview page. If a name is missing or the curr
49
49
  | Image | `Image` | `image-cn` | Root export |
50
50
  | List | `List` | `list-cn` | Root export |
51
51
  | Progress | `Progress` | `progress-cn` | Root export |
52
- | Table | `Table` | `next-table-cn` | Online public table docs currently live at `next-table-cn`; `table-cn` returns 404 |
53
- | NextTable | `NextTable` | `next-table-cn` | Same public table docs route |
52
+ | Table | `Table` | `next-table-cn` | The 旧版 Table tab documents the legacy API. |
53
+ | NextTable | `NextTable` | `next-table-cn` | The main page documents `NextTable`. |
54
54
  | Tag | `Tag` | `tag-cn` | Root export |
55
55
  | Alert | `Alert` | `alert-cn` | Root export |
56
56
  | Dialog | `Dialog` | `dialog-cn` | Root export |
@@ -49,18 +49,15 @@ Use browser/CDN mode for standalone pages, embedded pages and previews without a
49
49
 
50
50
  ### Select Resources
51
51
 
52
- Run `npx -y @finedesign/cli runtime list --format json` first and check its exit code. Use a version from its `versions` result with `npx -y @finedesign/cli runtime --fd-version <exact-version> --format html > demo.html` for a standalone starting page, or `--format json` for resources (MCP: `list_browser_runtimes` / `get_browser_runtime`). Use `--runtime-url` only for an explicitly selected preview. Only the currently hosted version is available; offline documentation may include more versions. An unavailable version is an error, not a reason to change the requested version. If discovery fails, report the actual error instead of guessing asset URLs or repeatedly probing unrelated packages.
52
+ Run `npx -y @finedesign/cli runtime list --format json` first and check its exit code. Use a version from its `versions` result with `npx -y @finedesign/cli runtime --fd-version <exact-version> --format html > demo.html` for a standalone starting page, or `--format json` for resources (MCP: `list_browser_runtimes` / `get_browser_runtime`). Use `--runtime-url` only for an explicitly selected preview.
53
53
 
54
- 1. Read the public [runtime manifest](https://fine-design-runtime.pages.dev/manifest.json). In this repository it is generated under `tools/fine-design/public/assets/react/fine-design-runtime/`. The manifest directly contains `version` and `resources`; there is no discovery pointer or historical version index.
55
- 2. Resolve resource `path` relative to that manifest; `url` is used exactly. Hosted paths include the precise package version, such as `fine-design/1.25.0/fine-design.min.js`. There is no hash directory or releaseId. Resource SHA-256 and SRI still verify the exact bytes.
56
- 3. The host retains only the current release files. Old URLs may disappear on upgrade; save matching resources yourself for long-lived standalone pages. Do not claim historical runtime availability from the CLI's offline catalog.
57
- 4. If the manifest cannot be retrieved, report the failure and use an explicitly selected verified host or previously saved matching resources. The old unversioned website resources have been removed; do not fall back to them or substitute another component version.
54
+ The public npm package `@finedesign/runtime` contains the UMD script, stylesheet and manifest. Discovery reads the latest manifest. For a known published version use `https://cdn.jsdelivr.net/npm/@finedesign/runtime@<exact-version>/manifest.json`. Resolve resource paths relative to that exact manifest and preserve the supplied URLs, hashes and SRI. If a requested version is unavailable, report the error or use matching previously saved resources.
58
55
 
59
56
  For offline or CSP-restricted previews, use `fine-design runtime --fd-version <exact-version> --output ./demo` with a new destination directory. `--dry-run --format json` previews file paths. The export verifies sizes/SHA-256 before writing local resources, preserves SRI and records their remote provenance in `runtime-lock.json`. Initial export needs network access; subsequent pages reference only local resources. The host must still permit page scripts/styles. Existing destinations are rejected rather than overwritten.
60
57
 
61
58
  Load `fineDesignCss`, then `react`, `reactDOM`, `fineDesign`. Pin exact URLs and integrity in generated HTML and use `crossorigin="anonymous"`; the host must provide CORS. Do not drop SRI from a selected versioned runtime to hide an error. Avoid async scripts and conflicting second React instances. If an embedding host lacks compatible React globals, use a separate document/iframe.
62
59
 
63
- Use `--runtime-url <verified-base-url>` only for a clearly selected host. The default public host is `https://fine-design-runtime.pages.dev/`, verified after production deployment; local testing alone does not prove a host is live. Optional chart resources are loaded only for chart requests.
60
+ Use `--runtime-url <verified-base-url>` for an explicitly selected alternative host. Use the VanChart skill for chart resources.
64
61
 
65
62
  ### Mount And Verify
66
63
 
@@ -76,4 +73,4 @@ ReactDOM.createRoot(document.getElementById('root')).render(
76
73
  );
77
74
  ```
78
75
 
79
- The repository's `npm run build:public-assets` builds the production component before generating the single latest manifest and browser example under tools. Deploy only the generated runtime directory with CORS; do not relabel a stale component build. Full local release checks are in `tools/fine-design/README.md`.
76
+ Run `npm run build:public-assets` to build the production npm runtime tarball. See `tools/fine-design/README.md` for publishing and verification.
package/src/cli.mjs CHANGED
@@ -3,19 +3,22 @@ import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { parseArgs } from 'node:util';
5
5
  import { queryCatalog, getComponentInfo, getComponentTokens, diffCatalogs, resolveComponentOrThrow } from './core/catalog.mjs';
6
- import { validateInput } from './core/contracts.mjs';
6
+ import { MAX_CONTEXT_COMPONENTS, validateInput } from './core/contracts.mjs';
7
7
  import { loadCatalog, readIndex } from './core/data.mjs';
8
8
  import { resolveLintVersion, resolveVersion } from './core/version.mjs';
9
9
  import { ToolError, errorResult } from './core/errors.mjs';
10
10
  import { listRuntimes, resolveRuntime, exportRuntime } from './core/runtime.mjs';
11
11
  import html from './core/html.cjs';
12
12
 
13
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
14
+
13
15
  const help = `Usage: fine-design <command> [arguments] [options]
14
16
 
15
17
  Commands:
16
18
  list List all components in the target version
17
19
  search [query] Search or browse components
18
20
  info <component> Show component overview and API/props sections
21
+ context <component...> Get a compact API and example index for one to six components
19
22
  doc <component> Read component documentation
20
23
  token [component] [query] Inspect component or global Design Tokens
21
24
  example <component> [id] List examples or read one example's source and asset metadata
@@ -33,10 +36,11 @@ Options:
33
36
  --project <directory> Project used to detect the installed version
34
37
  --component <name> Compare only this component (diff command only)
35
38
  --agent <cursor|claude|codex|all> Target agent configuration (init command only)
39
+ --rules-only Write agent rules that use the CLI's bundled Skill (init only)
36
40
  --output <directory> Destination for an example or offline runtime (add and runtime)
37
41
  --force Update managed files or overwrite examples (init and add)
38
42
  --dry-run Preview changes without writing (init, add and runtime --output)
39
- --runtime-url <url> Runtime hosting base URL (runtime command only)
43
+ --runtime-url <url> Runtime hosting base URL or npm (runtime command only)
40
44
  --format <text|json|markdown|html> Output format (markdown: doc/info/token/figma; html: runtime)
41
45
  --section <heading> Doc section heading (exact or case-insensitive)
42
46
  --toc, --summary Show only doc metadata, section headings and example IDs
@@ -51,7 +55,6 @@ function runDoctor(values) {
51
55
  if (!fs.existsSync(projectDir) || !fs.statSync(projectDir).isDirectory()) {
52
56
  throw new ToolError('INVALID_ARGUMENT', `Project directory does not exist: ${projectDir}`, 2);
53
57
  }
54
- const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
55
58
  const index = readIndex();
56
59
  const availableVersions = Object.keys(index.versions);
57
60
  const bundledSkillPath = fileURLToPath(new URL('../skills/fine-design/SKILL.md', import.meta.url));
@@ -114,9 +117,12 @@ function runInit(values) {
114
117
  const skipped = [];
115
118
  const warnings = [];
116
119
 
117
- const agentInstructions = `# Fine Design Rules
120
+ const ruleIntro = `# Fine Design Rules
121
+
122
+ 开发或修改 Fine Design 页面时,以及调试或评审涉及 \`@fx-ui/fine-design\` / \`window.FineDesign\` 的代码时,在目标工作目录主动调用 CLI。项目已安装 \`${pkg.version}\` 时用 \`npx fine-design\`,全局已安装该版本时用 \`fine-design\`,其余情况用 \`npx -y --prefer-offline ${pkg.name}@${pkg.version}\`。同一任务的查询和检查使用同一个 CLI 入口。`;
123
+ const agentInstructions = values['rules-only'] ? `${ruleIntro}
118
124
 
119
- 开发或修改 Fine Design 页面时,以及调试或评审涉及 \`@fx-ui/fine-design\` / \`window.FineDesign\` 的代码时,主动调用 CLI 核对组件 API,无需用户提醒。无关任务不触发。在目标工作目录运行:项目内已安装 CLI 时用 \`npx fine-design\`,否则使用全局 \`fine-design\`;两者均不可用时用 \`npx -y @finedesign/cli\`。
125
+ 首次处理当前工程的 Fine Design 任务时,运行 \`doctor --format json\` 并读取 \`bundledSkillPath\` 指向的 Skill。同一会话中工作目录和版本无变化时复用诊断与资料。按目标组件版本核对 API,改动后对涉及的文件运行 \`lint\` 并执行项目已有检查。` : `${ruleIntro}
120
126
 
121
127
  1. 首次处理当前工作目录的 Fine Design 任务时,运行 \`doctor --format json\`,读取 \`bundledSkillPath\` 指向的 Skill;当前会话已加载则复用,不重复读取。同一工作目录、CLI 和组件版本未变化时复用诊断结果。先确定交付形式;接入现有 React 工程时沿用项目组件版本、壳层和同类页面。
122
128
  2. 交付独立 HTML 或无构建预览时,先单独运行 \`runtime list --format json\`,根据退出码判断清单是否可用。用 \`versions\` 返回的版本解析 UMD 资源,再查组件 API。
@@ -192,12 +198,12 @@ ${agentInstructions}`;
192
198
  }
193
199
 
194
200
  if (agent === 'claude' || agent === 'all') {
195
- writeSkill('.claude/skills/fine-design');
201
+ if (!values['rules-only']) writeSkill('.claude/skills/fine-design');
196
202
  writeInstructions('CLAUDE.md');
197
203
  }
198
204
 
199
205
  if (agent === 'codex' || agent === 'all') {
200
- writeSkill('.agents/skills/fine-design');
206
+ if (!values['rules-only']) writeSkill('.agents/skills/fine-design');
201
207
  writeInstructions('AGENTS.md');
202
208
  }
203
209
 
@@ -308,18 +314,19 @@ export async function main(argv) {
308
314
  format: { type: 'string' }, section: { type: 'string' }, toc: { type: 'boolean' }, summary: { type: 'boolean' },
309
315
  offset: { type: 'string' }, limit: { type: 'string' }, 'include-assets': { type: 'boolean' },
310
316
  'runtime-url': { type: 'string' }, component: { type: 'string' },
311
- agent: { type: 'string' }, output: { type: 'string' }, force: { type: 'boolean' }, 'dry-run': { type: 'boolean' }
317
+ agent: { type: 'string' }, 'rules-only': { type: 'boolean' }, output: { type: 'string' }, force: { type: 'boolean' }, 'dry-run': { type: 'boolean' }
312
318
  }});
313
319
  format = values.format || 'text';
314
320
  if (!['text', 'json', 'markdown', 'html'].includes(format)) throw new ToolError('INVALID_ARGUMENT', 'Unknown output format.', 2);
315
321
  if (values.help || (!positionals.length && !values.version && !argv.length)) { console.log(help); return; }
316
- if (values.version && argv.length === 1) { console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version); return; }
322
+ if (values.version && argv.length === 1) { console.log(pkg.version); return; }
317
323
  const [command, ...args] = positionals;
318
324
  if (command === 'mcp' && args.length === 0 && argv.length === 1) { await (await import('./mcp.mjs')).startMcp(); return; }
319
325
  const summaryFlag = Boolean(values.toc || values.summary);
320
326
  if (command !== 'runtime' && (values['runtime-url'] !== undefined)) throw new ToolError('INVALID_ARGUMENT', 'Runtime options are only supported for runtime.', 2);
321
327
  if (command !== 'diff' && values.component !== undefined) throw new ToolError('INVALID_ARGUMENT', '--component is only supported for diff.', 2);
322
328
  if (command !== 'init' && values.agent !== undefined) throw new ToolError('INVALID_ARGUMENT', '--agent is only supported for init.', 2);
329
+ if (command !== 'init' && values['rules-only'] !== undefined) throw new ToolError('INVALID_ARGUMENT', '--rules-only is only supported for init.', 2);
323
330
  if (!['add', 'runtime'].includes(command) && values.output !== undefined) throw new ToolError('INVALID_ARGUMENT', '--output is only supported for add and runtime.', 2);
324
331
  if (!['init', 'add'].includes(command) && values.force !== undefined) throw new ToolError('INVALID_ARGUMENT', '--force is only supported for init and add.', 2);
325
332
  if (!['init', 'add', 'runtime'].includes(command) && values['dry-run'] !== undefined) throw new ToolError('INVALID_ARGUMENT', '--dry-run is only supported for init, add and runtime --output.', 2);
@@ -345,7 +352,10 @@ export async function main(argv) {
345
352
  if (format === 'json') {
346
353
  console.log(JSON.stringify(result));
347
354
  } else if (format === 'markdown') {
348
- const rows = result.matched.map((c) => `| \`${c.component}\` | \`${c.designName}\` | \`${c.nodeId}\` | \`${c.templateId}\` | ${c.businessInputs ? c.businessInputs.replace(/\|/g, '\\|') : '-'} |`);
355
+ const rows = result.matched.map((c) => {
356
+ const sources = c.sourceComponents.map((name) => `\`${name}\``).join(', ');
357
+ return `| ${sources} | \`${c.component}\` | \`${c.designName}\` | \`${c.nodeId}\` | \`${c.templateId}\` | ${c.businessInputs ? c.businessInputs.replace(/\|/g, '\\|') : '-'} |`;
358
+ });
349
359
  const unmappedRows = result.unmapped.map((u) => `- **${u.component}**: ${u.note}`);
350
360
  console.log([
351
361
  `# Fine Design 页面物料清单 (Figma BOM)`,
@@ -355,8 +365,8 @@ export async function main(argv) {
355
365
  `- **检测到组件总数**: ${result.totalDetected}`,
356
366
  '',
357
367
  `## 已连接设计组件 (${result.matched.length})`,
358
- '| 代码组件 | 设计名称 | Node ID | Code Connect 模板 | 业务入参要求 |',
359
- '| --- | --- | --- | --- | --- |',
368
+ '| 源码组件 | 映射组件 | 设计名称 | Node ID | Code Connect 模板 | 业务入参要求 |',
369
+ '| --- | --- | --- | --- | --- | --- |',
360
370
  ...rows,
361
371
  ...(result.unmapped.length ? [
362
372
  '',
@@ -370,7 +380,11 @@ export async function main(argv) {
370
380
  ] : [])
371
381
  ].join('\n'));
372
382
  } else {
373
- const lines = result.matched.map((c) => ` ${c.component.padEnd(18)} ${c.nodeId.padEnd(16)} ${c.templateId.padEnd(24)} ${c.designName}`);
383
+ const lines = result.matched.map((c) => {
384
+ const sources = c.sourceComponents.join(', ');
385
+ const sourceHint = sources === c.component ? '' : ` (source: ${sources})`;
386
+ return ` ${c.component.padEnd(18)} ${c.nodeId.padEnd(16)} ${c.templateId.padEnd(24)} ${c.designName}${sourceHint}`;
387
+ });
374
388
  console.log([
375
389
  `Fine Design Page Component Manifest (${result.matched.length} mapped / ${result.totalDetected} total):`,
376
390
  `Target: ${result.target} (File Key: ${result.fileKey})`,
@@ -519,7 +533,7 @@ export async function main(argv) {
519
533
  console.log(format === 'json' ? JSON.stringify(report) : `${report.dryRun ? 'Preview' : 'Exported'} Fine Design ${report.version} to ${report.targetDir}:\n${report.plannedFiles.map((name) => ` ${name}`).join('\n')}`);
520
534
  return;
521
535
  }
522
- console.log(format === 'html' ? html.exampleHTML(result.resources, './').trimEnd() : format === 'json' ? JSON.stringify(result) : list ? result.versions.join('\n') : `Fine Design ${result.version} (offline docs: ${result.docsAvailable ? 'available' : 'not bundled'})\n${result.tags}\nExample: ${result.exampleURL}`);
536
+ console.log(format === 'html' ? html.exampleHTML(result.resources, './').trimEnd() : format === 'json' ? JSON.stringify(result) : list ? result.versions.join('\n') : `Fine Design ${result.version} (offline docs: ${result.docsAvailable ? 'available' : 'not bundled'})\n${result.tags}${result.exampleURL ? `\nExample: ${result.exampleURL}` : ''}`);
523
537
  return;
524
538
  }
525
539
  if (command === 'doctor') {
@@ -545,7 +559,7 @@ export async function main(argv) {
545
559
  }
546
560
  if (command === 'init') {
547
561
  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)) {
548
- throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design init [--agent <cursor|claude|codex|all>] [--project <dir>] [--force] [--dry-run] [--format text|json]', 2);
562
+ throw new ToolError('INVALID_ARGUMENT', 'Usage: fine-design init [--agent <cursor|claude|codex|all>] [--rules-only] [--project <dir>] [--force] [--dry-run] [--format text|json]', 2);
549
563
  }
550
564
  const report = runInit(values);
551
565
  if (format === 'json') {
@@ -724,11 +738,12 @@ export async function main(argv) {
724
738
  }
725
739
  return;
726
740
  }
727
- const tools = { search: 'search_components', doc: 'get_component_doc', example: 'get_component_example' };
741
+ const tools = { search: 'search_components', doc: 'get_component_doc', example: 'get_component_example', context: 'get_generation_context' };
728
742
  if (
729
743
  !Object.hasOwn(tools, command) ||
730
744
  values.version ||
731
745
  (command === 'search' && args.length > 1) ||
746
+ (command === 'context' && (args.length < 1 || args.length > MAX_CONTEXT_COMPONENTS)) ||
732
747
  (command === 'doc' && args.length !== 1) ||
733
748
  (command === 'example' && (args.length < 1 || args.length > 2)) ||
734
749
  (values.section !== undefined && command !== 'doc') ||
@@ -742,25 +757,36 @@ export async function main(argv) {
742
757
  if (values.offset !== undefined && !/^\d+$/.test(values.offset)) throw new ToolError('INVALID_ARGUMENT', 'Offset must be a non-negative integer.', 2);
743
758
  if (values.limit !== undefined && !/^[1-9]\d*$/.test(values.limit)) throw new ToolError('INVALID_ARGUMENT', 'Limit must be a positive integer.', 2);
744
759
  const version = resolveVersion(values['fd-version'], values.project);
745
- const input = {
746
- version,
747
- ...(command === 'search'
748
- ? {
749
- query: args[0] ?? '',
750
- ...(values.offset !== undefined && { offset: Number(values.offset) }),
751
- ...(values.limit !== undefined && { limit: Number(values.limit) })
752
- }
753
- : {
754
- component: args[0],
755
- ...(command === 'doc' && values.section !== undefined && { section: values.section }),
756
- ...(command === 'doc' && summaryFlag && { summary: true }),
757
- ...(command === 'example' && { exampleId: args[1], ...(values['include-assets'] !== undefined && { includeAssets: values['include-assets'] }) })
758
- })
759
- };
760
+ const input = { version };
761
+ if (command === 'context') {
762
+ input.components = args;
763
+ } else if (command === 'search') {
764
+ Object.assign(input, {
765
+ query: args[0] ?? '',
766
+ ...(values.offset !== undefined && { offset: Number(values.offset) }),
767
+ ...(values.limit !== undefined && { limit: Number(values.limit) })
768
+ });
769
+ } else {
770
+ Object.assign(input, {
771
+ component: args[0],
772
+ ...(command === 'doc' && values.section !== undefined && { section: values.section }),
773
+ ...(command === 'doc' && summaryFlag && { summary: true }),
774
+ ...(command === 'example' && { exampleId: args[1], ...(values['include-assets'] !== undefined && { includeAssets: values['include-assets'] }) })
775
+ });
776
+ }
760
777
  validateInput(tools[command], input);
761
778
  const result = queryCatalog(loadCatalog(version), tools[command], input);
762
779
  if (format === 'json') {
763
780
  console.log(JSON.stringify(result));
781
+ } else if (command === 'context') {
782
+ const summaries = result.components.map(({ component, title, exports, sections, examples }) => [
783
+ `${title} (${exports.join(', ')})`,
784
+ `API sections · ${sections.map(({ heading }) => heading).join(', ') || 'none'}`,
785
+ `Examples · ${examples.map(({ id }) => id).join(', ') || 'none'}`,
786
+ ...sections.flatMap(({ markdown }) => markdown ? [markdown] : []),
787
+ `Read more with fine-design doc ${component} --toc --fd-version ${result.version}`
788
+ ].join('\n'));
789
+ console.log([`Fine Design ${result.version} context`, ...summaries].join('\n\n'));
764
790
  } else if (command === 'doc') {
765
791
  if (result.summary) {
766
792
  if (format === 'markdown') {
@@ -4,8 +4,17 @@ import { validateInput } from './contracts.mjs';
4
4
  import { sha256 } from './data.mjs';
5
5
 
6
6
  const MAX_INLINE_JSON_BYTES = 16 * 1024;
7
+ const MAX_CONTEXT_BYTES = 12 * 1024;
7
8
  const CHART_QUERY_PATTERN = /chart|vanchart|图表|折线|柱状|饼图|散点|雷达|漏斗|仪表盘|热力图|词云/i;
8
9
  const PREFERRED_COMPONENTS = new Set(['next-table', 'm-cascader']);
10
+ const SEARCH_RECOMMENDATIONS = new Map([
11
+ ['表格', 'next-table'],
12
+ ['下拉', 'select'],
13
+ ['下拉选择', 'select'],
14
+ ['多选下拉', 'select'],
15
+ ['级联', 'm-cascader'],
16
+ ['级联选择', 'm-cascader']
17
+ ]);
9
18
  const API_SECTION_PATTERN = /API|属性|Props|事件|方法|Ref|参数|配置|Column|Cell|HeaderCell|Rule|Option|Theme|统一弹层/i;
10
19
  const NON_API_SECTION_NAMES = new Set(['何时使用', '代码演示', '代码展示', '设计变量', '内置图标列表']);
11
20
 
@@ -84,12 +93,14 @@ function sourceMetadata(catalog) {
84
93
  };
85
94
  }
86
95
 
96
+ function matchesComponentName(component, name) {
97
+ return component.id === name || component.exports.some((exportName) => exportName.toLowerCase() === name);
98
+ }
99
+
87
100
  export function resolveComponentOrThrow(catalog, rawComponent) {
88
101
  const targetName = rawComponent.toLowerCase();
89
102
  const component =
90
- catalog.components.find((item) =>
91
- [item.id, ...item.exports].some((name) => name.toLowerCase() === targetName)
92
- ) ||
103
+ catalog.components.find((item) => matchesComponentName(item, targetName)) ||
93
104
  catalog.components.find((item) =>
94
105
  item.aliases.some((name) => name.toLowerCase() === targetName)
95
106
  );
@@ -104,8 +115,7 @@ export function resolveComponentOrThrow(catalog, rawComponent) {
104
115
  return component;
105
116
  }
106
117
 
107
- function scoreComponent(component, terms, rawQuery) {
108
- const q = rawQuery.toLowerCase().trim();
118
+ function scoreComponent(component, terms, q) {
109
119
  const primary = [component.id, component.title, ...component.exports].map((s) => s.toLowerCase());
110
120
  const secondary = [component.subtitle, ...component.aliases].filter(Boolean).map((s) => s.toLowerCase());
111
121
  const headings = [
@@ -140,12 +150,16 @@ function scoreComponent(component, terms, rawQuery) {
140
150
  export function queryCatalog(catalog, tool, args) {
141
151
  args = validateInput(tool, args);
142
152
  if (args.version !== catalog.version) throw new ToolError('VERSION_NOT_SUPPORTED', 'Requested Fine Design version is not available.', 3, { requestedVersion: args.version, availableVersions: [catalog.version] });
153
+ if (tool === 'get_generation_context') return getGenerationContext(catalog, args.components);
143
154
  const source = sourceMetadata(catalog);
144
155
  if (tool === 'search_components') {
145
156
  const pageSize = args.limit || 20;
146
157
  const offset = args.offset || 0;
147
- const terms = args.query.toLowerCase().trim().split(/\s+/).filter(Boolean);
158
+ const query = args.query.toLowerCase().trim();
159
+ const terms = query.split(/\s+/).filter(Boolean);
160
+ const recommended = SEARCH_RECOMMENDATIONS.get(query);
148
161
  const filtered = catalog.components.filter((component) => {
162
+ if (component.id === recommended) return true;
149
163
  const text = [
150
164
  component.id,
151
165
  component.title,
@@ -160,9 +174,15 @@ export function queryCatalog(catalog, tool, args) {
160
174
  .toLowerCase();
161
175
  return terms.every((term) => text.includes(term));
162
176
  });
163
- const matches = terms.length > 0
164
- ? [...filtered].sort((a, b) => scoreComponent(b, terms, args.query) - scoreComponent(a, terms, args.query) || a.id.localeCompare(b.id))
165
- : filtered;
177
+ const priority = (component) => {
178
+ if (matchesComponentName(component, query)) return 2;
179
+ return component.id === recommended ? 1 : 0;
180
+ };
181
+ const matches = terms.length > 0 ? filtered.sort((a, b) =>
182
+ priority(b) - priority(a) ||
183
+ scoreComponent(b, terms, query) - scoreComponent(a, terms, query) ||
184
+ a.id.localeCompare(b.id)
185
+ ) : filtered;
166
186
  let suggestions;
167
187
  if (matches.length === 0) {
168
188
  if (CHART_QUERY_PATTERN.test(args.query)) {
@@ -311,16 +331,90 @@ export function queryCatalog(catalog, tool, args) {
311
331
  throw new Error(`Unknown tool: ${tool}`);
312
332
  }
313
333
 
314
- export function getComponentInfo(catalog, { component: rawComponent }) {
315
- const source = sourceMetadata(catalog);
316
- const component = resolveComponentOrThrow(catalog, rawComponent);
334
+ function selectApiSections(component) {
317
335
  const topLevelApiSections = component.sections.filter((s) => s.markdown.startsWith('## ') && API_SECTION_PATTERN.test(s.heading));
318
336
  const apiSections = topLevelApiSections.length > 0
319
337
  ? topLevelApiSections
320
338
  : component.sections.filter((s) => API_SECTION_PATTERN.test(s.heading) && !NON_API_SECTION_NAMES.has(s.heading));
321
- const selectedSections = apiSections.length > 0
339
+ return apiSections.length > 0
322
340
  ? apiSections
323
341
  : component.sections.filter((s) => !NON_API_SECTION_NAMES.has(s.heading));
342
+ }
343
+
344
+ function getGenerationContext(catalog, names) {
345
+ const selected = [...new Set(names.map((name) => resolveComponentOrThrow(catalog, name)))];
346
+ const result = {
347
+ ...sourceMetadata(catalog),
348
+ components: selected.map((component) => ({
349
+ component: component.id,
350
+ title: component.title,
351
+ exports: component.exports,
352
+ docsAvailable: component.docsAvailable,
353
+ sections: [],
354
+ examples: []
355
+ })),
356
+ truncated: false
357
+ };
358
+ const fits = () => Buffer.byteLength(JSON.stringify(result)) <= MAX_CONTEXT_BYTES;
359
+ if (!fits()) throw new ToolError('INVALID_ARGUMENT', 'Component metadata exceeds the context budget. Request fewer components.', 2);
360
+
361
+ const addReference = (references, reference) => {
362
+ references.push(reference);
363
+ if (fits()) return true;
364
+ references.pop();
365
+ result.truncated = true;
366
+ return false;
367
+ };
368
+ const candidates = selected.map((component, index) => {
369
+ const summary = result.components[index];
370
+ const apiSections = new Set(selectApiSections(component));
371
+ const seenHeadings = new Set();
372
+ const inlineSections = [];
373
+ let includeChildren = false;
374
+
375
+ for (const [sectionIndex, section] of component.sections.entries()) {
376
+ const topLevel = section.markdown.startsWith('## ');
377
+ if (topLevel) includeChildren = apiSections.has(section);
378
+ // doc --section resolves the first exact heading in the catalog.
379
+ if (seenHeadings.has(section.heading)) continue;
380
+ seenHeadings.add(section.heading);
381
+ if (!includeChildren && !apiSections.has(section)) continue;
382
+
383
+ const reference = { heading: section.heading };
384
+ if (!addReference(summary.sections, reference)) continue;
385
+ if (topLevel && component.sections[sectionIndex + 1]?.markdown.startsWith('### ')) {
386
+ result.truncated = true;
387
+ } else {
388
+ inlineSections.push({ reference, markdown: section.markdown });
389
+ }
390
+ }
391
+ if (component.examples.length > 3) result.truncated = true;
392
+ for (const { id, title } of component.examples.slice(0, 3)) {
393
+ addReference(summary.examples, { id, title });
394
+ }
395
+ // Give each component a chance to include a complete section before larger tables.
396
+ return inlineSections.sort((a, b) => Buffer.byteLength(a.markdown) - Buffer.byteLength(b.markdown));
397
+ });
398
+
399
+ const rounds = Math.max(...candidates.map((sections) => sections.length));
400
+ for (let round = 0; round < rounds; round++) {
401
+ for (const sections of candidates) {
402
+ const candidate = sections[round];
403
+ if (!candidate) continue;
404
+ candidate.reference.markdown = candidate.markdown;
405
+ if (!fits()) {
406
+ delete candidate.reference.markdown;
407
+ result.truncated = true;
408
+ }
409
+ }
410
+ }
411
+ return result;
412
+ }
413
+
414
+ export function getComponentInfo(catalog, { component: rawComponent }) {
415
+ const source = sourceMetadata(catalog);
416
+ const component = resolveComponentOrThrow(catalog, rawComponent);
417
+ const selectedSections = selectApiSections(component);
324
418
  return {
325
419
  ...source,
326
420
  component: component.id,
@@ -487,7 +581,7 @@ export function diffCatalogs(fromCatalog, toCatalog, component) {
487
581
  migrationScope: 'general',
488
582
  migrations: [
489
583
  { components: ['table', 'data-table', 'next-table'], legacy: 'Table / DataTable', recommended: 'NextTable', note: 'Use <NextTable> with declarative <NextTable.Column>, <NextTable.HeaderCell>, and <NextTable.Cell dataKey="..."> children.' },
490
- { components: ['cascader', 'm-cascader'], legacy: 'Cascader', recommended: 'MCascader', note: 'Legacy Cascader has no online docs page; prefer MCascader for new pages.' },
584
+ { components: ['cascader', 'm-cascader'], legacy: 'Cascader', recommended: 'MCascader', note: 'For new pages, use MCascader with options, showSearch, and allowClear.' },
491
585
  { components: ['dialog'], legacy: 'Dialog.onCloseBtnClick', recommended: 'Dialog.onCancel', note: 'onCloseBtnClick is deprecated and fires alongside onCancel when clicking the close button.' }
492
586
  ].filter(({ components }) => !componentId || components.includes(componentId))
493
587
  .map(({ components, ...migration }) => migration)
@@ -3,6 +3,7 @@ import { ToolError } from './errors.mjs';
3
3
 
4
4
  const version = z.string().min(1).max(80);
5
5
  const component = z.string().min(1).max(100);
6
+ export const MAX_CONTEXT_COMPONENTS = 6;
6
7
  export const schemas = {
7
8
  search_components: z.object({
8
9
  version: version.optional(),
@@ -20,6 +21,10 @@ export const schemas = {
20
21
  version: version.optional(),
21
22
  component
22
23
  }).strict(),
24
+ get_generation_context: z.object({
25
+ version,
26
+ components: z.array(component).min(1).max(MAX_CONTEXT_COMPONENTS)
27
+ }).strict(),
23
28
  get_component_tokens: z.object({
24
29
  version: version.optional(),
25
30
  component: component.optional(),
@@ -196,6 +196,7 @@ export function scanFigmaComponents(targetPath) {
196
196
  if (match) {
197
197
  matched.set(match.component, {
198
198
  component: match.component,
199
+ sourceComponents: [...(matched.get(match.component)?.sourceComponents ?? []), name],
199
200
  designName: match.designName,
200
201
  nodeId: match.nodeId,
201
202
  url: match.url,